title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
Python simple and very short DP solution | stone-game-iv | 0 | 1 | ```\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp = [0]*(n+1)\n for i in range(1, n+1):\n j = 1\n while j*j <= i and not dp[i]:\n dp[i] = dp[i-j*j]^1\n j+=1\n return dp[n]\n```\n**Like it? please upvote...** | 6 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
Python simple and very short DP solution | stone-game-iv | 0 | 1 | ```\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp = [0]*(n+1)\n for i in range(1, n+1):\n j = 1\n while j*j <= i and not dp[i]:\n dp[i] = dp[i-j*j]^1\n j+=1\n return dp[n]\n```\n**Like it? please upvote...** | 6 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
Stone Game IV solution in Python with rigorous explaination. | stone-game-iv | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nLet $i$ be variable with the current leftmost stone index and $turn$ be the variable which indicates whose turn it is. $-1\\to Bob, 1\\to Alice$ \nLet\'s first look at the base cases:\n- If the end of the sequence is reached, then whoevers turn it is ... | 0 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
Stone Game IV solution in Python with rigorous explaination. | stone-game-iv | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nLet $i$ be variable with the current leftmost stone index and $turn$ be the variable which indicates whose turn it is. $-1\\to Bob, 1\\to Alice$ \nLet\'s first look at the base cases:\n- If the end of the sequence is reached, then whoevers turn it is ... | 0 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
Python3 || recursive DP || easy to understand | stone-game-iv | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code uses dynamic programming to determine if Alice can win a game where the players take turns removing a non-zero square number of stones from a pile. It\'s built around the idea of calculating whether, starting with a certain numbe... | 0 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
Python3 || recursive DP || easy to understand | stone-game-iv | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code uses dynamic programming to determine if Alice can win a game where the players take turns removing a non-zero square number of stones from a pile. It\'s built around the idea of calculating whether, starting with a certain numbe... | 0 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
Video Solution | Explanation With Drawings | In Depth | C++ | Java | Python 3 | number-of-good-pairs | 1 | 1 | # Intuition and approach dicussed in detail in video solution\nhttps://youtu.be/iE2klzxiLHE\n\n# Complexity\n\n# Code\nC++\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int, int> numFreqMp;\n int answer = 0;\n for(auto num : nums){\n answ... | 2 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
✅one line|BEATS 100% Runtime||Explanation✅ | number-of-good-pairs | 1 | 1 | # Intution\nwe have to count the occurrence of the same elements\nwith` A[i] == A[j]` and `i < j`\n\n# Approach\n- We will `intiliaze ans with 0` and an empty` unordered map` to store the occurrence of the element \n- For each element in the given array:\n- Here there will be 2 cases\n 1. if element/number is `present... | 161 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
NOOB CODE : Easy to Understand | number-of-good-pairs | 0 | 1 | \n\n# Approach\n1. Initialize a variable `c` to 0. This variable will be used to count the number of identical pairs.\n\n2. Use nested loops to iterate through the elements in the `nums` list. The outer loo... | 2 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
Using dictionary | number-of-good-pairs | 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)$$ --... | 1 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
Title: Unveiling Good Pairs with a One-Liner: A Pythonic Approach | number-of-good-pairs | 0 | 1 | # Simple Efficient One-Line Code for Identical Pairs\n\n## Intuition\nUpon reading the problem, it becomes evident that we need to count the number of pairs where the elements are identical. This is reminiscent of the combination formula, where we choose 2 items out of `n` items. The formula for this is `n(n-1)/2`. Giv... | 0 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
Easy apporach for beginners | number-of-good-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt the beinging of reading the question we will know that we need two loops one for ith index and other for the jth index.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we need to sort the list. So that we ... | 1 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
Number of Good Pairs Solution | number-of-good-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key intuition behind this code is to efficiently count the number of good pairs without explicitly checking all pairs in a nested loop. By using a dictionary to keep track of the count of each number, you can determine how many good p... | 1 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
Beats 94% runtime Easy python solution | number-of-good-pairs | 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. -->\nFind the frequency of each number and if it is greater than 1 then caluculate the nC2 value for that and add the result to sum \n\n# Complexity\n- Time complexity:O(n... | 1 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
range, len, for loop | number-of-good-pairs | 0 | 1 | # Code\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n count = 0\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] == nums[j]:\n count += 1\n return count\n``` | 1 | Given an array of integers `nums`, return _the number of **good pairs**_.
A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`.
**Example 1:**
**Input:** nums = \[1,2,3,1,1,3\]
**Output:** 4
**Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
**Example 2:**
**Input:** nu... | Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations. |
[Python] Sum of Arithmetic Progression with explanation **100.00% Faster** | number-of-substrings-with-only-1s | 0 | 1 | There is a ***pattern***, you will find that the ***result is the sum of arithmetic progression***.\nArithmetic progression: **t(n) = a + d(n-1)**\nSum of arithmetic progression: **s(n) = (n / 2) * (2a + d(n-1))**\n\nIn this problem, the first term(a) will be the the length of "1" and the number of terms will also be t... | 8 | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times... | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way w... |
[Python] Sum of Arithmetic Progression with explanation **100.00% Faster** | number-of-substrings-with-only-1s | 0 | 1 | There is a ***pattern***, you will find that the ***result is the sum of arithmetic progression***.\nArithmetic progression: **t(n) = a + d(n-1)**\nSum of arithmetic progression: **s(n) = (n / 2) * (2a + d(n-1))**\n\nIn this problem, the first term(a) will be the the length of "1" and the number of terms will also be t... | 8 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' h... | Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2. |
ONE-LINER || FASTER THAN 98% || SC 90% || | number-of-substrings-with-only-1s | 0 | 1 | ```\n return sum(map(lambda x: ((1+len(x))*len(x)//2)%(10**9+7), s.split(\'0\')))\n```\nIF THIS HELP U KINDLY UPVOTE THIS TO HELP OTHERS TO GET THIS SOLUTION\nIF U DONT GET IT KINDLY COMMENT AND FEEL FREE TO ASK\nAND CORRECT MEIF I AM WRONG | 3 | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times... | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way w... |
ONE-LINER || FASTER THAN 98% || SC 90% || | number-of-substrings-with-only-1s | 0 | 1 | ```\n return sum(map(lambda x: ((1+len(x))*len(x)//2)%(10**9+7), s.split(\'0\')))\n```\nIF THIS HELP U KINDLY UPVOTE THIS TO HELP OTHERS TO GET THIS SOLUTION\nIF U DONT GET IT KINDLY COMMENT AND FEEL FREE TO ASK\nAND CORRECT MEIF I AM WRONG | 3 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' h... | Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2. |
Easy Python Solution | number-of-substrings-with-only-1s | 0 | 1 | # Code\n```\nclass Solution:\n def numSub(self, nums: str) -> int:\n # stores the count of ones\n count = 0\n\n # stores the final answer\n answer = 0\n\n for i in range(len(nums)):\n if nums[i] == \'1\':\n count = count + 1\n else:\n ... | 0 | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times... | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way w... |
Easy Python Solution | number-of-substrings-with-only-1s | 0 | 1 | # Code\n```\nclass Solution:\n def numSub(self, nums: str) -> int:\n # stores the count of ones\n count = 0\n\n # stores the final answer\n answer = 0\n\n for i in range(len(nums)):\n if nums[i] == \'1\':\n count = count + 1\n else:\n ... | 0 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' h... | Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2. |
Just iterate and count consecutive 1s | number-of-substrings-with-only-1s | 0 | 1 | # Intuition\nJust traverse the string and count consecutive 1s and then calculate the output using the formula [(n * (n+1))//2]. \n\n\n\n# Complexity\n- Time complexity:\nO(N): Linear time, because we are iterating only once\n\n- Space complexity:\nO(1): Constant space complexity\n\n# Code\n```\nclass Solution:\n de... | 0 | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times... | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way w... |
Just iterate and count consecutive 1s | number-of-substrings-with-only-1s | 0 | 1 | # Intuition\nJust traverse the string and count consecutive 1s and then calculate the output using the formula [(n * (n+1))//2]. \n\n\n\n# Complexity\n- Time complexity:\nO(N): Linear time, because we are iterating only once\n\n- Space complexity:\nO(1): Constant space complexity\n\n# Code\n```\nclass Solution:\n de... | 0 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' h... | Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2. |
Simple approach defeat 100% | number-of-substrings-with-only-1s | 0 | 1 | \n\n\n\n# Complexity\nO(n) (n = len(s))\n\n\n# Code\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n vals = s.split(\'0\')\n _sum = 0\n for _bin in vals:\n n = len(_bin)\n _sum += n * (n+1) // 2\n return _sum % (10**9 + 7)\n \n``` | 0 | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times... | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way w... |
Simple approach defeat 100% | number-of-substrings-with-only-1s | 0 | 1 | \n\n\n\n# Complexity\nO(n) (n = len(s))\n\n\n# Code\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n vals = s.split(\'0\')\n _sum = 0\n for _bin in vals:\n n = len(_bin)\n _sum += n * (n+1) // 2\n return _sum % (10**9 + 7)\n \n``` | 0 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' h... | Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2. |
Sum of natural numbers , beats 98% | number-of-substrings-with-only-1s | 0 | 1 | # Intuition\nuse sum of first n natural numbers\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSplit the string using 0s and for each element in the array use sum of n natural numbers to count total combinations\n\nfor example for string 111111\n\nso split array will be [\'111111\']... | 0 | Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times... | Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way w... |
Sum of natural numbers , beats 98% | number-of-substrings-with-only-1s | 0 | 1 | # Intuition\nuse sum of first n natural numbers\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSplit the string using 0s and for each element in the array use sum of n natural numbers to count total combinations\n\nfor example for string 111111\n\nso split array will be [\'111111\']... | 0 | Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' h... | Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2. |
Python BFS Solution with Intuition and Approach | path-with-maximum-probability | 0 | 1 | # Intuition and Approach\nStart by building a `hashmap (graph)`, where `key` is the `node` and value is the value of `(probability, neighbor_node)`\n\nNext just like in a `standard breadth first search` we use a `queue` in this we will use a `priority queue` aka a `maxHeap`.\n\nKeep a dictionary `dist` to keep track of... | 1 | You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probab... | Find the minimum prefix sum. |
Python BFS Solution with Intuition and Approach | path-with-maximum-probability | 0 | 1 | # Intuition and Approach\nStart by building a `hashmap (graph)`, where `key` is the `node` and value is the value of `(probability, neighbor_node)`\n\nNext just like in a `standard breadth first search` we use a `queue` in this we will use a `priority queue` aka a `maxHeap`.\n\nKeep a dictionary `dist` to keep track of... | 1 | Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`.
Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot).
**Examp... | Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs. |
Python | Dijkstra | Beats 100% | Easy to Understand | path-with-maximum-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can be solved using Dijkstra\'s algorithm to find the path with the maximum probability of success. We can represent the graph as an adjacency list, where each node has a list of its neighbors and the corresponding edge probab... | 1 | You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probab... | Find the minimum prefix sum. |
Python | Dijkstra | Beats 100% | Easy to Understand | path-with-maximum-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can be solved using Dijkstra\'s algorithm to find the path with the maximum probability of success. We can represent the graph as an adjacency list, where each node has a list of its neighbors and the corresponding edge probab... | 1 | Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`.
Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot).
**Examp... | Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs. |
Problem Of the Day 28/06/2023 | path-with-maximum-probability | 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)$$ --... | 1 | You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probab... | Find the minimum prefix sum. |
Problem Of the Day 28/06/2023 | path-with-maximum-probability | 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)$$ --... | 1 | Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`.
Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot).
**Examp... | Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs. |
SIMPLE PYTHON SOLUTION | path-with-maximum-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSHORTEST PATH\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... | 1 | You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probab... | Find the minimum prefix sum. |
SIMPLE PYTHON SOLUTION | path-with-maximum-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSHORTEST PATH\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... | 1 | Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`.
Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot).
**Examp... | Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs. |
[Python3] geometric median | best-position-for-a-service-centre | 0 | 1 | This problem is to compute a quantity called "geometric median". There are algorithms dedicated to solve such problems such as Weiszfeld\'s algorithm. But those algorithms leverages on statistical routines such as weighted least squares. \n\nSince this is a 2d toy problem, we could use some "brute force" grid searching... | 72 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
[Python3] geometric median | best-position-for-a-service-centre | 0 | 1 | This problem is to compute a quantity called "geometric median". There are algorithms dedicated to solve such problems such as Weiszfeld\'s algorithm. But those algorithms leverages on statistical routines such as weighted least squares. \n\nSince this is a 2d toy problem, we could use some "brute force" grid searching... | 72 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Python solution gradient descent. Explanation | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal of this problem is to find the minimum distance sum of all the given positions. We can approach this problem using an optimization technique called gradient descent. Gradient descent is an iterative process in which the solution ... | 2 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Python solution gradient descent. Explanation | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal of this problem is to find the minimum distance sum of all the given positions. We can approach this problem using an optimization technique called gradient descent. Gradient descent is an iterative process in which the solution ... | 2 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
[Python] Gradient Descent with Armijo stepsize rule | best-position-for-a-service-centre | 0 | 1 | The problem is written as:\n.\nThe gradient is\n\n\n\n\n```python\nclass Solution:\n def getMinDi... | 23 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
[Python] Gradient Descent with Armijo stepsize rule | best-position-for-a-service-centre | 0 | 1 | The problem is written as:\n.\nThe gradient is\n\n\n\n\n```python\nclass Solution:\n def getMinDi... | 23 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Simple gradient descent. | best-position-for-a-service-centre | 0 | 1 | \n# Code\n```\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n if len(positions) == 1:\n return 0\n def grad(x, y, xs, ys):\n norm = [ sqrt( (x-xi)**2 + (y-yi) **2 ) for xi, yi in zip(xs, ys)] \n dx = sum([ (x - xi) / ni for xi, ni in ... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Simple gradient descent. | best-position-for-a-service-centre | 0 | 1 | \n# Code\n```\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n if len(positions) == 1:\n return 0\n def grad(x, y, xs, ys):\n norm = [ sqrt( (x-xi)**2 + (y-yi) **2 ) for xi, yi in zip(xs, ys)] \n dx = sum([ (x - xi) / ni for xi, ni in ... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
The Alternating Direction Method of Multipliers (ADMM) | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe objective is convex, decomposible but not everywhere differentiable. It is suitable for the alternating direction method of multipliers (ADMM), but not gradient descent.\n\n# Approach\n<!-- Describe your approach to solving the proble... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
The Alternating Direction Method of Multipliers (ADMM) | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe objective is convex, decomposible but not everywhere differentiable. It is suitable for the alternating direction method of multipliers (ADMM), but not gradient descent.\n\n# Approach\n<!-- Describe your approach to solving the proble... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Python: Weiszfeld's algorithm for Geometric Median | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first I thought "gee, why isn\'t this an Easy problem? I\'ll just compute the center of gravity (2D mean) of the points, then sum up the distance from the center to all the points. But when I tried it, it became clear that this wasn... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Python: Weiszfeld's algorithm for Geometric Median | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first I thought "gee, why isn\'t this an Easy problem? I\'ll just compute the center of gravity (2D mean) of the points, then sum up the distance from the center to all the points. But when I tried it, it became clear that this wasn... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Python simple gradient descent | best-position-for-a-service-centre | 0 | 1 | # Code\n```\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n step_size = 50\n alpha = 0.7\n cur_pos = (0, 0)\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n while step_size > 10**(-9):\n cur_distance = get_distance(positions, cur_pos... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Python simple gradient descent | best-position-for-a-service-centre | 0 | 1 | # Code\n```\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n step_size = 50\n alpha = 0.7\n cur_pos = (0, 0)\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n while step_size > 10**(-9):\n cur_distance = get_distance(positions, cur_pos... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Weiszfeld's algorithm | Commented and Explained | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBest position for a service is a geometric median. These are related to Fermat\'s theorem and are part of the higher level algorithmic problems on Leetcode. Check the wiki here for more : https://en.wikipedia.org/wiki/Geometric_median\n\n... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Weiszfeld's algorithm | Commented and Explained | best-position-for-a-service-centre | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBest position for a service is a geometric median. These are related to Fermat\'s theorem and are part of the higher level algorithmic problems on Leetcode. Check the wiki here for more : https://en.wikipedia.org/wiki/Geometric_median\n\n... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
3-Line Python Solution by using Scipy for Optimization | best-position-for-a-service-centre | 0 | 1 | # Approach\nThis is a typical optimization problem. The object is to find the optimal $$(\\bar{x}, \\bar{y})$$ pair that minimizes $$ \\sum_{i}{\\sqrt{ (\\bar{x}-x_i)^2 + \\sqrt{(\\bar{y} - y_i)^2} } }$$. The answer $$(\\bar{x}, \\bar{y})$$ can be obtained by a multivariate optimization algorithm such as gradient desce... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
3-Line Python Solution by using Scipy for Optimization | best-position-for-a-service-centre | 0 | 1 | # Approach\nThis is a typical optimization problem. The object is to find the optimal $$(\\bar{x}, \\bar{y})$$ pair that minimizes $$ \\sum_{i}{\\sqrt{ (\\bar{x}-x_i)^2 + \\sqrt{(\\bar{y} - y_i)^2} } }$$. The answer $$(\\bar{x}, \\bar{y})$$ can be obtained by a multivariate optimization algorithm such as gradient desce... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Python (Geometric Median) | best-position-for-a-service-centre | 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)$$ --... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Python (Geometric Median) | best-position-for-a-service-centre | 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)$$ --... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
NOT effective but easy to understand solution O(11200*n) | best-position-for-a-service-centre | 0 | 1 | # Intuition\nSorry for my english, I know it can be bad + this is the first solution I post\nI hope this helps someone understand the problem\n\n\n# Approach\nSo, I determine the best position first with an accuracy of integers then to tenths, to hundredths and thousandths\nI do it by brute force, over and over again a... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
NOT effective but easy to understand solution O(11200*n) | best-position-for-a-service-centre | 0 | 1 | # Intuition\nSorry for my english, I know it can be bad + this is the first solution I post\nI hope this helps someone understand the problem\n\n\n# Approach\nSo, I determine the best position first with an accuracy of integers then to tenths, to hundredths and thousandths\nI do it by brute force, over and over again a... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Python Gradient Descent With Weight Decay | best-position-for-a-service-centre | 0 | 1 | # Code\n```\nfrom math import sqrt\n\ndef f(xcenter: float, ycenter: float, positions: List[List[int]]) -> float:\n return sum(fdist(xcenter,ycenter,positions))\n\ndef fdist(xcenter: float, ycenter: float,positions: List[List[int]]) -> List[int]:\n return [sqrt((xcenter - x)**2 + (ycenter - y)**2) for x,y in posi... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Python Gradient Descent With Weight Decay | best-position-for-a-service-centre | 0 | 1 | # Code\n```\nfrom math import sqrt\n\ndef f(xcenter: float, ycenter: float, positions: List[List[int]]) -> float:\n return sum(fdist(xcenter,ycenter,positions))\n\ndef fdist(xcenter: float, ycenter: float,positions: List[List[int]]) -> List[int]:\n return [sqrt((xcenter - x)**2 + (ycenter - y)**2) for x,y in posi... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Linear Descend Technique - Python Solution | best-position-for-a-service-centre | 0 | 1 | \n# Code\n```\n\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n\n def total_distance(positions, x, y):\n res = 0\n for a, b in positions:\n res += math.sqrt((x - a)**2 + (y - b)**2)\n return res\n\n limit = 10**-5\n ... | 0 | A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.
Given an array `positions` where `positions[i... | Generate all Fibonacci numbers up to the limit (they are few). Use greedy solution, taking at every time the greatest Fibonacci number which is smaller than or equal to the current number. Subtract this Fibonacci number from the current number and repeat again the process. |
Linear Descend Technique - Python Solution | best-position-for-a-service-centre | 0 | 1 | \n# Code\n```\n\nclass Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n\n def total_distance(positions, x, y):\n res = 0\n for a, b in positions:\n res += math.sqrt((x - a)**2 + (y - b)**2)\n return res\n\n limit = 10**-5\n ... | 0 | Given two strings `s` and `t`, find the number of ways you can choose a non-empty substring of `s` and replace a **single character** by a different character such that the resulting substring is a substring of `t`. In other words, find the number of substrings in `s` that differ from some substring in `t` by **exactly... | The problem can be reworded as, giving a set of points on a 2d-plane, return the geometric median. Loop over each triplet of points (positions[i], positions[j], positions[k]) where i < j < k, get the centre of the circle which goes throw the 3 points, check if all other points lie in this circle. |
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅ | find-users-with-valid-e-mails | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n``` Python []\ndef valid_emails(users: pd.DataFrame) -> pd.DataFrame:\n return users[\n users[\'mail\'].str.match(r\'^[a-zA-Z][a-zA-Z\\d_.-]*@leetcode\\.com\')\n ]\n```\n```SQL []\nSELECT *\n FROM Users \n WHERE mail REGEXP... | 23 | You are given an integer array `nums`. You can choose **exactly one** index (**0-indexed**) and remove the element. Notice that the index of the elements may change after the removal.
For example, if `nums = [6,1,7,4,1]`:
* Choosing to remove index `1` results in `nums = [6,7,4,1]`.
* Choosing to remove index `2`... | null |
Easy to understand.....! | find-users-with-valid-e-mails | 0 | 1 | \n# Code\n```\nimport pandas as pd\n\ndef isValid(row):\n temp = row[\'mail\'].split(\'@\')\n \n if len(temp) <=1:\n return False\n if temp[1] !=\'leetcode.com\':\n return False\n prefix = temp[0]\n if not prefix[0].isalpha():\n return False\n t = [\'_\', \'.\', \'-\', \'/\']\n... | 5 | You are given an integer array `nums`. You can choose **exactly one** index (**0-indexed**) and remove the element. Notice that the index of the elements may change after the removal.
For example, if `nums = [6,1,7,4,1]`:
* Choosing to remove index `1` results in `nums = [6,7,4,1]`.
* Choosing to remove index `2`... | null |
Simple Logic | water-bottles | 0 | 1 | **Just keep track of** :\n1. How many bottles can we sell.\n2. How many bottles will remain after we sell.\n3. How many bottles we get back after we have made the sale.\n\n```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n drink_bottle = 0\n \n while Tr... | 1 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
Simple Logic | water-bottles | 0 | 1 | **Just keep track of** :\n1. How many bottles can we sell.\n2. How many bottles will remain after we sell.\n3. How many bottles we get back after we have made the sale.\n\n```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n drink_bottle = 0\n \n while Tr... | 1 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
Simple python solution | while loop | water-bottles | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nu... | 1 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
Simple python solution | while loop | water-bottles | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nu... | 1 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
[Python3 | C++] Two beautiful solutions | water-bottles | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are two ways to solve this problem and we will analyze both:\n1) The way of an honest programmer\n2) A tricky but mathematical way\n# Approach 1 (Honest Programmer)\n<!-- Describe your approach to solving the problem. -->\nIterative... | 10 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
[Python3 | C++] Two beautiful solutions | water-bottles | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are two ways to solve this problem and we will analyze both:\n1) The way of an honest programmer\n2) A tricky but mathematical way\n# Approach 1 (Honest Programmer)\n<!-- Describe your approach to solving the problem. -->\nIterative... | 10 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
One-liner in Python | water-bottles | 0 | 1 | ```\ndef numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n return int(numBottles + (numBottles - 1) / (numExchange - 1))\n```\nPlease upvote if you like it | 20 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
One-liner in Python | water-bottles | 0 | 1 | ```\ndef numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n return int(numBottles + (numBottles - 1) / (numExchange - 1))\n```\nPlease upvote if you like it | 20 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
O(1) solution 3 line | water-bottles | 1 | 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)$$ --... | 1 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
O(1) solution 3 line | water-bottles | 1 | 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)$$ --... | 1 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
Python3 easy | while-loop | Comments - added | water-bottles | 0 | 1 | **PLease Upvote,** if it helped !\nit motivates me :)\n```\n#just keep in mind that when you exhange empty bottles for filled ones they will also get empty after drinking \n#don\'t miss counting them\n\ndef numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n if numBottles<numExchange:\n ... | 7 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
Python3 easy | while-loop | Comments - added | water-bottles | 0 | 1 | **PLease Upvote,** if it helped !\nit motivates me :)\n```\n#just keep in mind that when you exhange empty bottles for filled ones they will also get empty after drinking \n#don\'t miss counting them\n\ndef numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n if numBottles<numExchange:\n ... | 7 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
[Python3] Simple Solution | water-bottles | 0 | 1 | ```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n drank , left = [numBottles] * 2\n \n while left >= numExchange:\n left -= numExchange - 1\n drank += 1\n \n return drank\n``` | 5 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
[Python3] Simple Solution | water-bottles | 0 | 1 | ```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n drank , left = [numBottles] * 2\n \n while left >= numExchange:\n left -= numExchange - 1\n drank += 1\n \n return drank\n``` | 5 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
[Python3] 5-line iterative | water-bottles | 0 | 1 | \n```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n ans = r = 0\n while numBottles:\n ans += numBottles\n numBottles, r = divmod(numBottles + r, numExchange)\n return ans \n``` | 9 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
[Python3] 5-line iterative | water-bottles | 0 | 1 | \n```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n ans = r = 0\n while numBottles:\n ans += numBottles\n numBottles, r = divmod(numBottles + r, numExchange)\n return ans \n``` | 9 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
Python Beats 93.2% | water-bottles | 0 | 1 | \n# Code\n```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n ans = 0\n cant = 0\n while numBottles>0:\n take = (numBottles+cant)//numExchange\n cant = (numBottles+cant)%numExchange\n ans += numBottles\n\n numB... | 2 | There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers `numBottles` and `numExchange`, return _the **maximu... | null |
Python Beats 93.2% | water-bottles | 0 | 1 | \n# Code\n```\nclass Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n ans = 0\n cant = 0\n while numBottles>0:\n take = (numBottles+cant)//numExchange\n cant = (numBottles+cant)%numExchange\n ans += numBottles\n\n numB... | 2 | You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`.
You start your journey from building `0` and move to the next building by possibly using bricks or ladders.
While moving from building `i` to building `i+1` (**0-indexed**),
* If the current building'... | Simulate the process until there are not enough empty bottles for even one full bottle of water. |
Python | O(1) Space | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\n\n**Disclaimer**: first, we talk about "additional" space here, so output parameters like `ans` do not count. Second, I do not consider the graph to take additional space, since it\'s a result of a poor input format choice.\n\n# Approach\n\nLet\'s imagine that we run a timed depth first search on our tree.... | 11 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
Python | O(1) Space | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\n\n**Disclaimer**: first, we talk about "additional" space here, so output parameters like `ans` do not count. Second, I do not consider the graph to take additional space, since it\'s a result of a poor input format choice.\n\n# Approach\n\nLet\'s imagine that we run a timed depth first search on our tree.... | 11 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
MOST OPTIMIZED PYTHON SOLUTION || DFS TRAVERSAL | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(V+E)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V*E)$$\n<!-- Add your space complexity ... | 3 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
MOST OPTIMIZED PYTHON SOLUTION || DFS TRAVERSAL | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(V+E)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V*E)$$\n<!-- Add your space complexity ... | 3 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
Python3 DFS with quick explanation | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\n\nTraverse the tree and each node should return a vector to its parent node. The vector should have the count of all the labels in the sub-tree of this node.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we make a graph of the tree so we can traverse it. Then we use a dfs alg... | 3 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
Python3 DFS with quick explanation | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\n\nTraverse the tree and each node should return a vector to its parent node. The vector should have the count of all the labels in the sub-tree of this node.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we make a graph of the tree so we can traverse it. Then we use a dfs alg... | 3 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
C# & Python 3 Solutions | Dictionary | DFS | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Approach\nIn this approach, we traverse from the root nodes to the leaf node and count the number of characters using DFS. \nWe don\u2019t need to create counts array and iterate over it in every call. Instead, we can store single array for all calls, which has counts of visited labels for all time. Then, the answer ... | 2 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
C# & Python 3 Solutions | Dictionary | DFS | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Approach\nIn this approach, we traverse from the root nodes to the leaf node and count the number of characters using DFS. \nWe don\u2019t need to create counts array and iterate over it in every call. Instead, we can store single array for all calls, which has counts of visited labels for all time. Then, the answer ... | 2 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
Python solution beats 99.38% | number-of-nodes-in-the-sub-tree-with-the-same-label | 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)$$ --... | 2 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
Python solution beats 99.38% | number-of-nodes-in-the-sub-tree-with-the-same-label | 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)$$ --... | 2 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
🧑💻Python3 Simple Solution | DFS + Dictionary | Great explanation | 97% optimal | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | Note: Skip to "**How to Solve**" section if you have basic understanding of DFS.\nAlso the **code has proper comments**, skips to the code directly if you prefer :)\n\n# Approach\nSo heres the deal, first of all the questions asks us to consider about undirected trees, by that what they are implying is to consider your... | 2 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
🧑💻Python3 Simple Solution | DFS + Dictionary | Great explanation | 97% optimal | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | Note: Skip to "**How to Solve**" section if you have basic understanding of DFS.\nAlso the **code has proper comments**, skips to the code directly if you prefer :)\n\n# Approach\nSo heres the deal, first of all the questions asks us to consider about undirected trees, by that what they are implying is to consider your... | 2 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
✅Python3 solution. Beats 100% in time and memory | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\nMy idea was that you need to know only two things when building the final array - the count when the node was first visited and the current count.\nThe code is higly optimized for memory efficiency and not for readability. I\'m sorry for that, but I tried to add comments on the parts where weird things are... | 1 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
✅Python3 solution. Beats 100% in time and memory | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\nMy idea was that you need to know only two things when building the final array - the count when the node was first visited and the current count.\nThe code is higly optimized for memory efficiency and not for readability. I\'m sorry for that, but I tried to add comments on the parts where weird things are... | 1 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
PYTHON || EASY TO UNDERSTAND || WELL EXPLAINED | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\nThe intuition behind this solution is to use a depth-first search (dfs) to traverse the tree and keep track of the counts of each label in the subtree of each node.\n\n# Approach\nThe approach is as follows:\n\n1. Create an adjacency list representation of the tree using the edges array.\n2. Initialize an ... | 1 | You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node w... | Sort elements and take each element from the largest until accomplish the conditions. |
PYTHON || EASY TO UNDERSTAND || WELL EXPLAINED | number-of-nodes-in-the-sub-tree-with-the-same-label | 0 | 1 | # Intuition\nThe intuition behind this solution is to use a depth-first search (dfs) to traverse the tree and keep track of the counts of each label in the subtree of each node.\n\n# Approach\nThe approach is as follows:\n\n1. Create an adjacency list representation of the tree using the edges array.\n2. Initialize an ... | 1 | Bob is standing at cell `(0, 0)`, and he wants to reach `destination`: `(row, column)`. He can only travel **right** and **down**. You are going to help Bob by providing **instructions** for him to reach `destination`.
The **instructions** are represented as a string, where each character is either:
* `'H'`, meanin... | Start traversing the tree and each node should return a vector to its parent node. The vector should be of length 26 and have the count of all the labels in the sub-tree of this node. |
Python Easy to Read solution with explanation | maximum-number-of-non-overlapping-substrings | 0 | 1 | This is a slightly modified version based on the discussion here\nhttps://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/743402/21-lines-Python-greedy-solution\n\n[Explanation]\n1. Get the first and last occurance of each characters\n2. For the range of each letter, we need to update the ran... | 31 | Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions:
1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true.
2. A substring that contains a certain chara... | Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd. Simulate the steps described in the binary string. |
Python Easy to Read solution with explanation | maximum-number-of-non-overlapping-substrings | 0 | 1 | This is a slightly modified version based on the discussion here\nhttps://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/743402/21-lines-Python-greedy-solution\n\n[Explanation]\n1. Get the first and last occurance of each characters\n2. For the range of each letter, we need to update the ran... | 31 | Given the `root` of a binary tree, return _the lowest common ancestor (LCA) of two given nodes,_ `p` _and_ `q`. If either node `p` or `q` **does not exist** in the tree, return `null`. All values of the nodes in the tree are **unique**.
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/... | Notice that it's impossible for any two valid substrings to overlap unless one is inside another. We can start by finding the starting and ending index for each character. From these indices, we can form the substrings by expanding each character's range if necessary (if another character exists in the range with small... |
python solution | maximum-number-of-non-overlapping-substrings | 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)$$ -->\nnear about O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity her... | 0 | Given a string `s` of lowercase letters, you need to find the maximum number of **non-empty** substrings of `s` that meet the following conditions:
1. The substrings do not overlap, that is for any two substrings `s[i..j]` and `s[x..y]`, either `j < x` or `i > y` is true.
2. A substring that contains a certain chara... | Read the string from right to left, if the string ends in '0' then the number is even otherwise it is odd. Simulate the steps described in the binary string. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.