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
Easiest Solution
masking-personal-information
1
1
\n\n# Code\n```java []\nclass Solution {\n public String maskPII(String s) {\n StringBuilder sb = new StringBuilder();\n\t\t //email handeling\n if((s.charAt(0) >= 97 && s.charAt(0) <= 122) || (s.charAt(0) >= 65 && s.charAt(0) <= 90)){\n\n s = s.toLowerCase();\n int indexo...
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 `'@'` ...
null
Easiest Solution
masking-personal-information
1
1
\n\n# Code\n```java []\nclass Solution {\n public String maskPII(String s) {\n StringBuilder sb = new StringBuilder();\n\t\t //email handeling\n if((s.charAt(0) >= 97 && s.charAt(0) <= 122) || (s.charAt(0) >= 65 && s.charAt(0) <= 90)){\n\n s = s.toLowerCase();\n int indexo...
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
python simple solution beginner friendly 100%
masking-personal-information
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
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 `'@'` ...
null
python simple solution beginner friendly 100%
masking-personal-information
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
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
[Python3] Good enough
masking-personal-information
0
1
``` Python3 []\nclass Solution:\n def maskPII(self, s: str) -> str:\n if \'@\' in s:\n s = s.lower()\n return f\'{s[0]}*****{s[s.index("@")-1:]}\'\n else:\n s = [x for x in s if x.isdigit()]\n return f\'{"+"+("*"*(len(s)-10))+"-" if len(s) > 10 else ""}***-**...
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 `'@'` ...
null
[Python3] Good enough
masking-personal-information
0
1
``` Python3 []\nclass Solution:\n def maskPII(self, s: str) -> str:\n if \'@\' in s:\n s = s.lower()\n return f\'{s[0]}*****{s[s.index("@")-1:]}\'\n else:\n s = [x for x in s if x.isdigit()]\n return f\'{"+"+("*"*(len(s)-10))+"-" if len(s) > 10 else ""}***-**...
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
[LC-831-M | Python3] A Plain Solution
masking-personal-information
0
1
Just write the process as requested.\n\n```Python3 []\nclass Solution:\n def maskPII(self, s: str) -> str:\n if \'@\' in s:\n s = s.lower()\n ss = s.split(\'@\')\n return ss[0][0] + \'*****\' + ss[0][-1] + \'@\' + ss[1]\n \n k = len([int(x) for x in s if x.isdigi...
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 `'@'` ...
null
[LC-831-M | Python3] A Plain Solution
masking-personal-information
0
1
Just write the process as requested.\n\n```Python3 []\nclass Solution:\n def maskPII(self, s: str) -> str:\n if \'@\' in s:\n s = s.lower()\n ss = s.split(\'@\')\n return ss[0][0] + \'*****\' + ss[0][-1] + \'@\' + ss[1]\n \n k = len([int(x) for x in s if x.isdigi...
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
pyhon3 easy solution it`s just if and else
masking-personal-information
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
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 `'@'` ...
null
pyhon3 easy solution it`s just if and else
masking-personal-information
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
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
</>
masking-personal-information
0
1
# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n def email(s):\n UserName, Domine = s.split("@")\n part1, part2 = Domine.split(".")\n ans = UserName[0].lower() + "*" * 5 + UserName[-1].lower()\n ans += "@"\n ans += part1.lower() + "." + ...
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 `'@'` ...
null
</>
masking-personal-information
0
1
# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n def email(s):\n UserName, Domine = s.split("@")\n part1, part2 = Domine.split(".")\n ans = UserName[0].lower() + "*" * 5 + UserName[-1].lower()\n ans += "@"\n ans += part1.lower() + "." + ...
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
Python Solution
masking-personal-information
0
1
\n\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n arr = s.split(\'@\')\n if len(arr)==2:\n arr[0] = arr[0].lower()\n arr[1] = arr[1].lower()\n return arr[0][0]+\'*****\'+arr[0][-1] + \'@\' + arr[1]\n ph = []\n for ch in s:\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 `'@'` ...
null
Python Solution
masking-personal-information
0
1
\n\n# Code\n```\nclass Solution:\n def maskPII(self, s: str) -> str:\n arr = s.split(\'@\')\n if len(arr)==2:\n arr[0] = arr[0].lower()\n arr[1] = arr[1].lower()\n return arr[0][0]+\'*****\'+arr[0][-1] + \'@\' + arr[1]\n ph = []\n for ch in s:\n ...
0
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
[Python] SIMPLE Forward O(N) Solution (32ms / 97%)
find-and-replace-in-string
0
1
First, create a dictionary that maps the index in `indexes` to its pair of strings in `sources` and `targets`.\n\nIterate through `S`, looking up the current index `i` to see if we can perform a replacement. Take a slice of `S` at our current index to see if it `.startswith()` the source string. If so, we perform a "...
60
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]` oc...
null
[Python] SIMPLE Forward O(N) Solution (32ms / 97%)
find-and-replace-in-string
0
1
First, create a dictionary that maps the index in `indexes` to its pair of strings in `sources` and `targets`.\n\nIterate through `S`, looking up the current index `i` to see if we can perform a replacement. Take a slice of `S` at our current index to see if it `.startswith()` the source string. If so, we perform a "...
60
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Solution
find-and-replace-in-string
1
1
```C++ []\nclass Solution {\npublic:\n string findReplaceString(string s, vector<int>& indices, vector<string>& sources, vector<string>& targets) {\n int num_queries = indices.size();\n map<pair<int,int>, int> interval_set;\n for(int i = 0; i < num_queries; i++){\n\n int current_idx =...
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]` oc...
null
Solution
find-and-replace-in-string
1
1
```C++ []\nclass Solution {\npublic:\n string findReplaceString(string s, vector<int>& indices, vector<string>& sources, vector<string>& targets) {\n int num_queries = indices.size();\n map<pair<int,int>, int> interval_set;\n for(int i = 0; i < num_queries; i++){\n\n int current_idx =...
2
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Python 3 | simple | 3 lines of code w/ explanation
find-and-replace-in-string
0
1
```\nclass Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n # iterate from the greater index to the smallest\n for i, src, tg in sorted(list(zip(indices, sources, targets)), reverse=True): \n # if found the pattern match...
3
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]` oc...
null
Python 3 | simple | 3 lines of code w/ explanation
find-and-replace-in-string
0
1
```\nclass Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n # iterate from the greater index to the smallest\n for i, src, tg in sorted(list(zip(indices, sources, targets)), reverse=True): \n # if found the pattern match...
3
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Two DFS | O(N) | Python Solution | Explained
sum-of-distances-in-tree
0
1
Hello **Tenno Leetcoders**,\n\nFor this problem we have a `bidirectional graph`, and we want to return the sum of the distances from the root node and all other nodes. \n\nOne simple way to do this is to build a graph with each given edges and choosing `0 to n-1` as the `root` and for each root, we will perform `DFS` t...
2
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 s...
null
Two DFS | O(N) | Python Solution | Explained
sum-of-distances-in-tree
0
1
Hello **Tenno Leetcoders**,\n\nFor this problem we have a `bidirectional graph`, and we want to return the sum of the distances from the root node and all other nodes. \n\nOne simple way to do this is to build a graph with each given edges and choosing `0 to n-1` as the `root` and for each root, we will perform `DFS` t...
2
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Solution
sum-of-distances-in-tree
1
1
```C++ []\nclass Solution {\n int head[30010], end[60010], next[60010], idx;\n int siz[30010], n;\n vector<int> ans;\n void add (int a, int b) {\n end[idx] = b, next[idx] = head[a], head[a] = idx++;\n }\npublic:\n vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {\n me...
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 s...
null
Solution
sum-of-distances-in-tree
1
1
```C++ []\nclass Solution {\n int head[30010], end[60010], next[60010], idx;\n int siz[30010], n;\n vector<int> ans;\n void add (int a, int b) {\n end[idx] = b, next[idx] = head[a], head[a] = idx++;\n }\npublic:\n vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {\n me...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
One DFS O(N)
sum-of-distances-in-tree
0
1
# Intuition\nSuppose we have a tree A---B---C---D.\n\nTo calculate the sum of all paths for B we need to know the total sum of all paths and the number of paths for A and C but without, edges that connect them to B, we can just start a DFS from B.\nTo reduce the complexity we can use memorization.\n\ndfs(node, parent) ...
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 s...
null
One DFS O(N)
sum-of-distances-in-tree
0
1
# Intuition\nSuppose we have a tree A---B---C---D.\n\nTo calculate the sum of all paths for B we need to know the total sum of all paths and the number of paths for A and C but without, edges that connect them to B, we can just start a DFS from B.\nTo reduce the complexity we can use memorization.\n\ndfs(node, parent) ...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Updated: faster and less memory than 100%
sum-of-distances-in-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy initial approach was based on recursion. It was wrong, since it exceeded the time limit (it took $O(n^2)$ time).\nIt turns out that the problem can be solved in linear time, traversing the tree exactly 3 times.\n\nEdit: After optimizin...
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 s...
null
Updated: faster and less memory than 100%
sum-of-distances-in-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy initial approach was based on recursion. It was wrong, since it exceeded the time limit (it took $O(n^2)$ time).\nIt turns out that the problem can be solved in linear time, traversing the tree exactly 3 times.\n\nEdit: After optimizin...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Python 3 || Beats 82.22% Memory 67.3 MB
sum-of-distances-in-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncount -> count list takes parent i\'th number of child\nans -> ans of ith positions\ndo comment out print(count) and print(ans) in order to Understand.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\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 s...
null
Python 3 || Beats 82.22% Memory 67.3 MB
sum-of-distances-in-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncount -> count list takes parent i\'th number of child\nans -> ans of ith positions\ndo comment out print(count) and print(ans) in order to Understand.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Python3 | DFS, BFS, Math | Time beats 98.33% & Space beats 80.56% | Code and Explanation
sum-of-distances-in-tree
0
1
# Approach\nWe can calculate one node as root, and use this result to get other nodes\' result.\n\nYou can simply observe that the path calculation between one node and its parent node has a rule:\n\nLet\'s say that $$A$$ is the parent of $$B$$.\nWe can group nodes as: $$A$$ side and $$B$$ side.\nSo the path calculatio...
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 s...
null
Python3 | DFS, BFS, Math | Time beats 98.33% & Space beats 80.56% | Code and Explanation
sum-of-distances-in-tree
0
1
# Approach\nWe can calculate one node as root, and use this result to get other nodes\' result.\n\nYou can simply observe that the path calculation between one node and its parent node has a rule:\n\nLet\'s say that $$A$$ is the parent of $$B$$.\nWe can group nodes as: $$A$$ side and $$B$$ side.\nSo the path calculatio...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Memoize partial trees for each node, simple and concise Python
sum-of-distances-in-tree
0
1
# Intuition\nSince this is a tree (acyclic) graph, there are only 2*(N-1) subtree possibilities, one subtree for either side of each edge. So we can define our memo as `dp[i][j]` where i is the root of the subtree and j is the connected node that should be considered the "parent" for the purposes of the query.\n\nThe ...
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 s...
null
Memoize partial trees for each node, simple and concise Python
sum-of-distances-in-tree
0
1
# Intuition\nSince this is a tree (acyclic) graph, there are only 2*(N-1) subtree possibilities, one subtree for either side of each edge. So we can define our memo as `dp[i][j]` where i is the root of the subtree and j is the connected node that should be considered the "parent" for the purposes of the query.\n\nThe ...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
[Python] Super Simple O(N) DP Solution
sum-of-distances-in-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe graph has no cycles, since it is tree. Hence, the graph is divided by each edges. \nGiven an edge consisting of A and B, Let\'s assumed we can be calculated that the sum of distances from all nodes which exist in A side.\nIn terms o...
2
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 s...
null
[Python] Super Simple O(N) DP Solution
sum-of-distances-in-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe graph has no cycles, since it is tree. Hence, the graph is divided by each edges. \nGiven an edge consisting of A and B, Let\'s assumed we can be calculated that the sum of distances from all nodes which exist in A side.\nIn terms o...
2
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Python3 || 1067 ms, faster than 83.89% of Python3 || Clean and Easy to Understand
sum-of-distances-in-tree
0
1
```\ndef sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n g = collections.defaultdict(list)\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n d = {i:[1, 0] for i in range(n)}\n def dfs(root, prev):\n for x in g[root]:\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 s...
null
Python3 || 1067 ms, faster than 83.89% of Python3 || Clean and Easy to Understand
sum-of-distances-in-tree
0
1
```\ndef sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n g = collections.defaultdict(list)\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n d = {i:[1, 0] for i in range(n)}\n def dfs(root, prev):\n for x in g[root]:\n ...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Python
sum-of-distances-in-tree
0
1
\n```\nclass Solution:\n def sumOfDistancesInTree(self, n,edges):\n result=[0]*n\n self.dist =0\n hashmap = self.create_map(edges)\n hashmap[0].append(0)\n base = {}\n self.r(0,hashmap,base,set(),0)\n result[0]=self.dist\n self.U...
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 s...
null
Python
sum-of-distances-in-tree
0
1
\n```\nclass Solution:\n def sumOfDistancesInTree(self, n,edges):\n result=[0]*n\n self.dist =0\n hashmap = self.create_map(edges)\n hashmap[0].append(0)\n base = {}\n self.r(0,hashmap,base,set(),0)\n result[0]=self.dist\n self.U...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Python DFS with cache
sum-of-distances-in-tree
0
1
# I think this one approach is the only answer doable for a normal person during the interview \n\n# Code\n```\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n for x, y in edges:\n graph[x].append(y)\n gr...
2
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 s...
null
Python DFS with cache
sum-of-distances-in-tree
0
1
# I think this one approach is the only answer doable for a normal person during the interview \n\n# Code\n```\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n graph = defaultdict(list)\n for x, y in edges:\n graph[x].append(y)\n gr...
2
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Python easy to read and understand | graph
sum-of-distances-in-tree
0
1
**BRUTE(BFS)**\n```\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n g = collections.defaultdict(list)\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n \n res = [0]*n\n for i in range(n):\n q ...
3
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 s...
null
Python easy to read and understand | graph
sum-of-distances-in-tree
0
1
**BRUTE(BFS)**\n```\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n g = collections.defaultdict(list)\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n \n res = [0]*n\n for i in range(n):\n q ...
3
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
BFS + Bitmask -- runtime beats 94%
image-overlap
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf two cells, $$c_1$$ and $$c_2$$ overlap one of the following happens:\n 1. If $c_1 = 0$ and $c_2 = 0$, we **don\'t count** the overlap.\n 2. If $c_1 = 1$ and $c_2 = 0$, we **don\'t count** the overlap.\n 3. If $c_1 = 0$ and $c_...
10
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. W...
null
BFS + Bitmask -- runtime beats 94%
image-overlap
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf two cells, $$c_1$$ and $$c_2$$ overlap one of the following happens:\n 1. If $c_1 = 0$ and $c_2 = 0$, we **don\'t count** the overlap.\n 2. If $c_1 = 1$ and $c_2 = 0$, we **don\'t count** the overlap.\n 3. If $c_1 = 0$ and $c_...
10
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. ...
null
Solution
image-overlap
1
1
```C++ []\nclass Solution {\npublic:\n int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {\n int n = img1.size();\n vector<unsigned int> small1(n, 0);\n vector<unsigned int> small2(n, 0);\n for(int row = 0; row < n; ++row) {\n for(int col = 0; col < n; ++...
1
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. W...
null
Solution
image-overlap
1
1
```C++ []\nclass Solution {\npublic:\n int largestOverlap(vector<vector<int>>& img1, vector<vector<int>>& img2) {\n int n = img1.size();\n vector<unsigned int> small1(n, 0);\n vector<unsigned int> small2(n, 0);\n for(int row = 0; row < n; ++row) {\n for(int col = 0; col < n; ++...
1
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. ...
null
Solution
rectangle-overlap
1
1
```C++ []\nclass Solution {\npublic:\n bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {\n return rec1[0]<rec2[2] && rec1[1] < rec2[3] && rec2[0]<rec1[2] && rec2[1]< rec1[3];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bo...
2
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
Solution
rectangle-overlap
1
1
```C++ []\nclass Solution {\npublic:\n bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {\n return rec1[0]<rec2[2] && rec1[1] < rec2[3] && rec2[0]<rec1[2] && rec2[1]< rec1[3];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bo...
2
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Python 3: Readable solution with comments
rectangle-overlap
0
1
```\nclass Solution(object):\n def isRectangleOverlap(self, rec1, rec2):\n # TIME and SPACE Complexity: O(1)\n\t\t\n #Funtion checking if coordinate of Rec2 overlapped Rec1;\n def checkOverlapping(rec1_left, rec1_right, rec2_left, rec2_right):\n \n rec2_StartingCoordinate =...
1
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
Python 3: Readable solution with comments
rectangle-overlap
0
1
```\nclass Solution(object):\n def isRectangleOverlap(self, rec1, rec2):\n # TIME and SPACE Complexity: O(1)\n\t\t\n #Funtion checking if coordinate of Rec2 overlapped Rec1;\n def checkOverlapping(rec1_left, rec1_right, rec2_left, rec2_right):\n \n rec2_StartingCoordinate =...
1
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Single Line solution, beats 98.2%, Simple logic
rectangle-overlap
0
1
# Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can simplify the conditions by directly checking if rec1 is to the right, left, above, or below rec2. \n * If any of these conditions is true, it means the rectangles do not overlap. \n- If none of these conditions is met, the rectangle...
0
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
Single Line solution, beats 98.2%, Simple logic
rectangle-overlap
0
1
# Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can simplify the conditions by directly checking if rec1 is to the right, left, above, or below rec2. \n * If any of these conditions is true, it means the rectangles do not overlap. \n- If none of these conditions is met, the rectangle...
0
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
simple python code using hashmap
new-21-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)$$ --...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
simple python code using hashmap
new-21-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)$$ --...
1
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Python3 Solution
new-21-game
0
1
\n```\nclass Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n if k==0 or n>=k+maxPts:\n return 1\n\n dp=[1.0]+[0.0]*n\n maxPts_sum=1.0\n for i in range(1,n+1):\n dp[i]=maxPts_sum/maxPts\n if i<k:\n maxPts_sum+=dp[i]\n...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Python3 Solution
new-21-game
0
1
\n```\nclass Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n if k==0 or n>=k+maxPts:\n return 1\n\n dp=[1.0]+[0.0]*n\n maxPts_sum=1.0\n for i in range(1,n+1):\n dp[i]=maxPts_sum/maxPts\n if i<k:\n maxPts_sum+=dp[i]\n...
1
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Solution
new-21-game
1
1
```C++ []\nclass Solution {\npublic:\n double new21Game(int n, int k, int mx) {\n if (k == 0 || n >= k + mx) return 1.0;\n vector<double> dp(n+1);\n dp[0] = 1.0;\n double pref = 1.0;\n double res = 0.0; \n for (int i = 1; i <= n; i++){\n dp[i] = pref / mx;\n ...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Solution
new-21-game
1
1
```C++ []\nclass Solution {\npublic:\n double new21Game(int n, int k, int mx) {\n if (k == 0 || n >= k + mx) return 1.0;\n vector<double> dp(n+1);\n dp[0] = 1.0;\n double pref = 1.0;\n double res = 0.0; \n for (int i = 1; i <= n; i++){\n dp[i] = pref / mx;\n ...
1
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Image Explanation🏆- [Complete Intuition - Maths, Probability, DP, Sliding Window] - C++/Java/Python
new-21-game
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`New 21 Game` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/ce5147fe-97f0-487f-8037-acee7774c4cc_1684988558.8669872.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/86ee1163-deca-4b59-9703-2e16443...
70
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Image Explanation🏆- [Complete Intuition - Maths, Probability, DP, Sliding Window] - C++/Java/Python
new-21-game
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`New 21 Game` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/ce5147fe-97f0-487f-8037-acee7774c4cc_1684988558.8669872.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/86ee1163-deca-4b59-9703-2e16443...
70
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Python Easy Solution
new-21-game
0
1
# Code\n```\nclass Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n dp = [1.0] + [0] * n\n Wsum = 1.0\n if k == 0 or n >= k + maxPts:\n return 1\n for i in range(1, n+1):\n dp[i] = Wsum/maxPts\n if i < k:\n Wsum += dp...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Python Easy Solution
new-21-game
0
1
# Code\n```\nclass Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n dp = [1.0] + [0] * n\n Wsum = 1.0\n if k == 0 or n >= k + maxPts:\n return 1\n for i in range(1, n+1):\n dp[i] = Wsum/maxPts\n if i < k:\n Wsum += dp...
1
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Diagram & Image Explaination🥇 C++ Full Optimized🔥 DP | Well Explained
new-21-game
1
1
# Diagram\n<!-- Describe your first thoughts on how to solve this problem. -->\n![code2flow_4fd67K (4).png](https://assets.leetcode.com/users/images/81ac4f36-2325-4a84-94df-525c356d3781_1684973082.8253682.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if Alice can always get k or mor...
7
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Diagram & Image Explaination🥇 C++ Full Optimized🔥 DP | Well Explained
new-21-game
1
1
# Diagram\n<!-- Describe your first thoughts on how to solve this problem. -->\n![code2flow_4fd67K (4).png](https://assets.leetcode.com/users/images/81ac4f36-2325-4a84-94df-525c356d3781_1684973082.8253682.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if Alice can always get k or mor...
7
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
new-21-game
1
1
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u...
16
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
new-21-game
1
1
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u...
16
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Give it 2 hours . TRY it yourself for logic building from scratch ! ✔🐱‍🏍🙌
new-21-game
0
1
# Intuition\n##### Build-up for the game :-\n\nIn this game, Alice starts with 0 points and draws numbers randomly. She wants to know the chance of having `n` or fewer points at the end.\n\nTo figure this out, we can use a trick called "counting." We start counting from 0 and keep track of the chance of having each num...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Give it 2 hours . TRY it yourself for logic building from scratch ! ✔🐱‍🏍🙌
new-21-game
0
1
# Intuition\n##### Build-up for the game :-\n\nIn this game, Alice starts with 0 points and draws numbers randomly. She wants to know the chance of having `n` or fewer points at the end.\n\nTo figure this out, we can use a trick called "counting." We start counting from 0 and keep track of the chance of having each num...
1
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Solution
push-dominoes
1
1
```C++ []\nclass Solution {\npublic:\n string pushDominoes(string s) {\n string ans=s;\n int n=ans.size(),r=-1;\n for(int i=0; i<n; i++) {\n if(s[i]==\'L\' && r==-1) {\n for(int l=i-1; l>=0 && s[l]==\'.\'; l--) {\n ans[l]=\'L\';\n }\n ...
1
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ...
null
Solution
push-dominoes
1
1
```C++ []\nclass Solution {\npublic:\n string pushDominoes(string s) {\n string ans=s;\n int n=ans.size(),r=-1;\n for(int i=0; i<n; i++) {\n if(s[i]==\'L\' && r==-1) {\n for(int l=i-1; l>=0 && s[l]==\'.\'; l--) {\n ans[l]=\'L\';\n }\n ...
1
Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._ Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `...
null
[Python3] Multi-source BFS
push-dominoes
0
1
I know that a lot of great solutions have been discussed in the discussion, but I want to share mine as well -- a multi-source BFS solution.\n\nThe idea is pretty straightforward, we first add all position where the initial forces happen (i.e. add all "L" and "R"), and then does BFS.\n\nNotice that we need to take spec...
2
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ...
null
[Python3] Multi-source BFS
push-dominoes
0
1
I know that a lot of great solutions have been discussed in the discussion, but I want to share mine as well -- a multi-source BFS solution.\n\nThe idea is pretty straightforward, we first add all position where the initial forces happen (i.e. add all "L" and "R"), and then does BFS.\n\nNotice that we need to take spec...
2
Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._ Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `...
null
Simple python solution
push-dominoes
0
1
```\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n n = len(dominoes)\n \n right_force = [0] * n\n \n for i in range(n):\n if dominoes[i] == \'R\':\n right_force[i] = n\n elif dominoes[i] == \'L\':\n right_force...
1
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ...
null
Simple python solution
push-dominoes
0
1
```\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n n = len(dominoes)\n \n right_force = [0] * n\n \n for i in range(n):\n if dominoes[i] == \'R\':\n right_force[i] = n\n elif dominoes[i] == \'L\':\n right_force...
1
Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._ Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `...
null
Python | Neetcode | Queue Traversal
push-dominoes
0
1
```\nfrom collections import deque\n\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n \n q=deque()\n dominoes=list(dominoes)\n for a,i in enumerate(dominoes):\n if i=="L"or i=="R":\n q.append((i,a))\n \n # print(q)\n ...
1
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ...
null
Python | Neetcode | Queue Traversal
push-dominoes
0
1
```\nfrom collections import deque\n\nclass Solution:\n def pushDominoes(self, dominoes: str) -> str:\n \n q=deque()\n dominoes=list(dominoes)\n for a,i in enumerate(dominoes):\n if i=="L"or i=="R":\n q.append((i,a))\n \n # print(q)\n ...
1
Given a positive integer `n`, find and return _the **longest distance** between any two **adjacent**_ `1`_'s in the binary representation of_ `n`_. If there are no two adjacent_ `1`_'s, return_ `0`_._ Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `...
null
python 3 - dsu + union by rank + path compression
similar-string-groups
0
1
# Intuition\nThe word "group" in description -> think about DSU is good intuition.\n\nOptimize:\n- skip checking if you know 2 strings are already in the same group\n- if >2 letter differences are found between 2 strings, stop checking because they are not the same group\n\n(When I first saw this question, I thought my...
3
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
python 3 - dsu + union by rank + path compression
similar-string-groups
0
1
# Intuition\nThe word "group" in description -> think about DSU is good intuition.\n\nOptimize:\n- skip checking if you know 2 strings are already in the same group\n- if >2 letter differences are found between 2 strings, stop checking because they are not the same group\n\n(When I first saw this question, I thought my...
3
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
[Python] Graph solution
similar-string-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can think this problem as calculating the number of connected graph.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a function that check 2 strings is similar.\nIf similiar connect them.\nUse BFS(or DFS...
2
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
[Python] Graph solution
similar-string-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou can think this problem as calculating the number of connected graph.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a function that check 2 strings is similar.\nIf similiar connect them.\nUse BFS(or DFS...
2
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
Python3 beats 95.41% 🚀🚀 with explanation || quibler7
similar-string-groups
0
1
![Screenshot 2023-04-28 at 9.23.24 AM.png](https://assets.leetcode.com/users/images/3a9ceb0b-65d4-4e97-be5e-fa69317327bb_1682654049.5216508.png)\n\n\n\n# Code\n```\nclass Solution:\n def numSimilarGroups(self, strs: List[str]) -> int:\n def similar(a: str, b: str):\n diff1 = -1\n diff2 =...
2
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Python3 beats 95.41% 🚀🚀 with explanation || quibler7
similar-string-groups
0
1
![Screenshot 2023-04-28 at 9.23.24 AM.png](https://assets.leetcode.com/users/images/3a9ceb0b-65d4-4e97-be5e-fa69317327bb_1682654049.5216508.png)\n\n\n\n# Code\n```\nclass Solution:\n def numSimilarGroups(self, strs: List[str]) -> int:\n def similar(a: str, b: str):\n diff1 = -1\n diff2 =...
2
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
Solution
similar-string-groups
1
1
```C++ []\nclass Solution {\npublic:\n bool isNeighbor(string &a, string &b) {\n int diff = 0;\n for (int i = 0; i < a.size(); i++) {\n if (a[i] != b[i])\n if (++diff > 2) return false;\n }\n return true;\n }\n int numSimilarGroups(vector<string>& strs) {\n...
1
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Solution
similar-string-groups
1
1
```C++ []\nclass Solution {\npublic:\n bool isNeighbor(string &a, string &b) {\n int diff = 0;\n for (int i = 0; i < a.size(); i++) {\n if (a[i] != b[i])\n if (++diff > 2) return false;\n }\n return true;\n }\n int numSimilarGroups(vector<string>& strs) {\n...
1
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
python 🐍
similar-string-groups
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
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
python 🐍
similar-string-groups
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 integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
not easy to undrstand
similar-string-groups
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
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
not easy to undrstand
similar-string-groups
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 integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
Python easy working solution
similar-string-groups
0
1
\n\n# Code\n```\nclass UnionFindSet:\n def __init__(self, n):\n self.parents = list(range(n))\n \n def find(self, x):\n if self.parents[x] != x:\n return self.find(self.parents[x])\n return x\n \n def union(self, u, v):\n self.parents[self.find(u)] = self.find(v...
1
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Python easy working solution
similar-string-groups
0
1
\n\n# Code\n```\nclass UnionFindSet:\n def __init__(self, n):\n self.parents = list(range(n))\n \n def find(self, x):\n if self.parents[x] != x:\n return self.find(self.parents[x])\n return x\n \n def union(self, u, v):\n self.parents[self.find(u)] = self.find(v...
1
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
Simple Solution that Actually Works! (Union Find Python3)
similar-string-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe gotta use union find\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUnion find\n\n# Complexity\nnot complex\n\n# Code\n```\nclass UnionFindSet:\n def __init__(self, n):\n self.parents = list(range(n))...
1
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Simple Solution that Actually Works! (Union Find Python3)
similar-string-groups
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe gotta use union find\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUnion find\n\n# Complexity\nnot complex\n\n# Code\n```\nclass UnionFindSet:\n def __init__(self, n):\n self.parents = list(range(n))...
1
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
Python Beats 96% Easy Solution Only Arrays Explained
similar-string-groups
0
1
# Intuition\nAt a high level, the algorithm needs to be able to:\n1. Compare strings to each other for similarity\n2. Go through the strings and assign them to groups\n3. Combine groups if necessary, when we process a new string with similarities to multiple groups\n\n\n# Approach\n1. Create helper function to check if...
1
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Python Beats 96% Easy Solution Only Arrays Explained
similar-string-groups
0
1
# Intuition\nAt a high level, the algorithm needs to be able to:\n1. Compare strings to each other for similarity\n2. Go through the strings and assign them to groups\n3. Combine groups if necessary, when we process a new string with similarities to multiple groups\n\n\n# Approach\n1. Create helper function to check if...
1
You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. Return `true` _if and only if we can do this so that the resulting number is a power of two_. **Example 1:** **Input:** n = 1 **Output:** true **Example 2:** **Input:** n = 10 **...
null
Solution
magic-squares-in-grid
1
1
```C++ []\n#define DO(...) { __VA_ARGS__ do\n#define WHILE(...) while(__VA_ARGS__); }\n\nclass Solution {\n typedef unsigned int uInt;\n typedef const uInt c_uInt;\n static constexpr uInt\n magicSize = 3, magicSizeM1 = magicSize - 1;\n bool contained[10];\n bool isMagicSqr (const vector<vector<int...
1
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Solution
magic-squares-in-grid
1
1
```C++ []\n#define DO(...) { __VA_ARGS__ do\n#define WHILE(...) while(__VA_ARGS__); }\n\nclass Solution {\n typedef unsigned int uInt;\n typedef const uInt c_uInt;\n static constexpr uInt\n magicSize = 3, magicSizeM1 = magicSize - 1;\n bool contained[10];\n bool isMagicSqr (const vector<vector<int...
1
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Beats 100%, approach explained.
magic-squares-in-grid
1
1
![image.png](https://assets.leetcode.com/users/images/17751782-1ede-492f-9035-e884d804ac83_1701879295.690145.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA 3x3 magic square is a square grid of numbers arranged in such a way that the sum of the numbers in each row, each colum...
2
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Beats 100%, approach explained.
magic-squares-in-grid
1
1
![image.png](https://assets.leetcode.com/users/images/17751782-1ede-492f-9035-e884d804ac83_1701879295.690145.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA 3x3 magic square is a square grid of numbers arranged in such a way that the sum of the numbers in each row, each colum...
2
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null