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
[Python3] union-find
largest-component-size-by-common-factor
0
1
\n`O(MlogM)` using sieve\n```\nclass UnionFind: \n \n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1]*n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def u...
4
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
[Python] Union Find - Nov., Day 22 Daily leetcode
largest-component-size-by-common-factor
0
1
# Intuition\n\ndescription:\n> There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n\nwe can see that what we really care is **common factor**.\ntransfrom nums[i] into a set of factors and union their factors together, because node\'s factor is the key an...
0
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _t...
null
[Python] Union Find - Nov., Day 22 Daily leetcode
largest-component-size-by-common-factor
0
1
# Intuition\n\ndescription:\n> There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n\nwe can see that what we really care is **common factor**.\ntransfrom nums[i] into a set of factors and union their factors together, because node\'s factor is the key an...
0
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Python 3 FT 90%: Link Numbers to Prime Factors, Sieve of Eratosthenes, Trial Divide by <= Sqrt(n)
largest-component-size-by-common-factor
0
1
# Intuition\n\nThis is basically the same solution as DBabichev\'s, just wanted to share the key insights needed to avoid TLE. There are lots of ways to get the right answer, but there are some nontrivial things you must do to avoid TLE. In my opinion the max runtime is bit too strict for this problem - this is more of...
0
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _t...
null
Python 3 FT 90%: Link Numbers to Prime Factors, Sieve of Eratosthenes, Trial Divide by <= Sqrt(n)
largest-component-size-by-common-factor
0
1
# Intuition\n\nThis is basically the same solution as DBabichev\'s, just wanted to share the key insights needed to avoid TLE. There are lots of ways to get the right answer, but there are some nontrivial things you must do to avoid TLE. In my opinion the max runtime is bit too strict for this problem - this is more of...
0
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Easy to understand Sieve and Union find
largest-component-size-by-common-factor
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Use sieve algorithm to find the smallest prime factor (spf) for each number in 1 to 10**5\n1. finding the spf of all numbers also gives us all the prime factors of the number, this is because by successively dividing by the spf we g...
0
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _t...
null
Easy to understand Sieve and Union find
largest-component-size-by-common-factor
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Use sieve algorithm to find the smallest prime factor (spf) for each number in 1 to 10**5\n1. finding the spf of all numbers also gives us all the prime factors of the number, this is because by successively dividing by the spf we g...
0
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Using sieve and dfs/union-find
largest-component-size-by-common-factor
0
1
**Using DFS and sieve** \n\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n n,prime,isPresent = max(nums) + 11,[],set(nums) \n g,ans,curr = [[] for _ in range(n)],0,0\n \n \n def sieve(n):\n primes = [True for _ in range(n)] \n for i in range(2,...
0
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _t...
null
Using sieve and dfs/union-find
largest-component-size-by-common-factor
0
1
**Using DFS and sieve** \n\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n n,prime,isPresent = max(nums) + 11,[],set(nums) \n g,ans,curr = [[] for _ in range(n)],0,0\n \n \n def sieve(n):\n primes = [True for _ in range(n)] \n for i in range(2,...
0
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num ...
null
Python solution: explained in detail
verifying-an-alien-dictionary
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- In lexicographically ordered dictionary we don\'t have any words less in value after greater.\n- So we don\'t need to traverse $$words$$ array $$n^2$$ times just check it for $$n$$ times.\n- if $$current word[i]$$ is greater in size of $$currentword...
3
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `wor...
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Python solution: explained in detail
verifying-an-alien-dictionary
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- In lexicographically ordered dictionary we don\'t have any words less in value after greater.\n- So we don\'t need to traverse $$words$$ array $$n^2$$ times just check it for $$n$$ times.\n- if $$current word[i]$$ is greater in size of $$currentword...
3
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. ...
null
Solution
array-of-doubled-pairs
1
1
```C++ []\nclass Solution {\npublic:\n bool canReorderDoubled(vector<int>& arr) {\n unordered_map<int,int> mp;\n for(int i: arr) mp[i]++;\n vector<int> k;\n for(auto x: mp) k.push_back(x.first);\n sort(k.begin(),k.end(),[](int a, int b){\n return abs(a) < abs(b);\n ...
2
Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[3,1,3,6\] **Output:** false **Example 2:** **Input:** arr = \[2,1,2,6\] **Out...
For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you ...
Solution
array-of-doubled-pairs
1
1
```C++ []\nclass Solution {\npublic:\n bool canReorderDoubled(vector<int>& arr) {\n unordered_map<int,int> mp;\n for(int i: arr) mp[i]++;\n vector<int> k;\n for(auto x: mp) k.push_back(x.first);\n sort(k.begin(),k.end(),[](int a, int b){\n return abs(a) < abs(b);\n ...
2
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ...
null
Python solution using Counter
array-of-doubled-pairs
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Keep a count of each number in the arr in counts.\n2. Sort the arr.\n3. For each number in arr:\n a. If count of number has become 0 then skip.\n b. If (number * 2) is present in counts then decrement number and (number * 2)\n4. At the end if...
2
Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[3,1,3,6\] **Output:** false **Example 2:** **Input:** arr = \[2,1,2,6\] **Out...
For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you ...
Python solution using Counter
array-of-doubled-pairs
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Keep a count of each number in the arr in counts.\n2. Sort the arr.\n3. For each number in arr:\n a. If count of number has become 0 then skip.\n b. If (number * 2) is present in counts then decrement number and (number * 2)\n4. At the end if...
2
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ...
null
From O(n*log n) to O(n) - 3 approaches summarized (updated)
array-of-doubled-pairs
0
1
### Approach # 1 - Match using a hashmap\nProcess numbers in sorted order of the absolute value. Use a hashmap to remember what numbers (`2*x`) you expect to see. If you see an expected number, decrement its count, otherwise increment the count of the expected number (`2*x`). At the end all values in the expected hashm...
10
Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[3,1,3,6\] **Output:** false **Example 2:** **Input:** arr = \[2,1,2,6\] **Out...
For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you ...
From O(n*log n) to O(n) - 3 approaches summarized (updated)
array-of-doubled-pairs
0
1
### Approach # 1 - Match using a hashmap\nProcess numbers in sorted order of the absolute value. Use a hashmap to remember what numbers (`2*x`) you expect to see. If you see an expected number, decrement its count, otherwise increment the count of the expected number (`2*x`). At the end all values in the expected hashm...
10
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ...
null
Simple Solution Using Dictionary
array-of-doubled-pairs
0
1
# Explanation\nFrom smallest to largest number (sort input array), check if we\'ve "seen" $$x/2$$ or $$2*x$$. Decrement the count at each encounter.\n\nAt the end of our count, the length of the input array should be twice the the number of pairs: $$count*2 == len(arr)$$\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$...
0
Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[3,1,3,6\] **Output:** false **Example 2:** **Input:** arr = \[2,1,2,6\] **Out...
For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you ...
Simple Solution Using Dictionary
array-of-doubled-pairs
0
1
# Explanation\nFrom smallest to largest number (sort input array), check if we\'ve "seen" $$x/2$$ or $$2*x$$. Decrement the count at each encounter.\n\nAt the end of our count, the length of the input array should be twice the the number of pairs: $$count*2 == len(arr)$$\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$...
0
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ...
null
Solution
delete-columns-to-make-sorted-ii
1
1
```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n auto strsLength = strs.size();\n auto strLength = strs[0].size();\n\n auto sortedStrs = vector<string>(strsLength, "");\n\n for (size_t i = 0u; i < strLength; ++i) {\n for (size_t j = 0u; j < s...
2
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Solution
delete-columns-to-make-sorted-ii
1
1
```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n auto strsLength = strs.size();\n auto strLength = strs[0].size();\n\n auto sortedStrs = vector<string>(strsLength, "");\n\n for (size_t i = 0u; i < strLength; ++i) {\n for (size_t j = 0u; j < s...
2
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** par...
null
Python 3 || 6 lines, w/ explanation || T/M: 81% / 87%
delete-columns-to-make-sorted-ii
0
1
Here\'s the plan:\n\nWe start with a blank slate and build each of the elements of `strs` uniformly, character by character, as long as`strs` remains lexographically correct.\n```\nclass Solution: \n def minDeletionSize(self, strs: List[str]) -> int:\n\n tpse, n, m = zip(*strs), len(strs), len(strs[0])\n ...
4
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python 3 || 6 lines, w/ explanation || T/M: 81% / 87%
delete-columns-to-make-sorted-ii
0
1
Here\'s the plan:\n\nWe start with a blank slate and build each of the elements of `strs` uniformly, character by character, as long as`strs` remains lexographically correct.\n```\nclass Solution: \n def minDeletionSize(self, strs: List[str]) -> int:\n\n tpse, n, m = zip(*strs), len(strs), len(strs[0])\n ...
4
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** par...
null
Python3 | Beats 100% | O(n * str_len)
delete-columns-to-make-sorted-ii
0
1
# Complexity\n- Time complexity:\n$$ O(n * len(strs[0])) $$\n\n\n# Code\n```\nfrom typing import List\n\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n ans = 0\n not_okay_set = set[int](range(len(strs)))\n i = 0\n while i < len(strs[0]):\n column_okay ...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python3 | Beats 100% | O(n * str_len)
delete-columns-to-make-sorted-ii
0
1
# Complexity\n- Time complexity:\n$$ O(n * len(strs[0])) $$\n\n\n# Code\n```\nfrom typing import List\n\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n ans = 0\n not_okay_set = set[int](range(len(strs)))\n i = 0\n while i < len(strs[0]):\n column_okay ...
0
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** par...
null
Python Greedy Solution
delete-columns-to-make-sorted-ii
0
1
```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m = len(strs)\n n = len(strs[0])\n\n cur = ["" for i in range(m)]\n res = 0\n\n for i in range(n):\n temp = [x for x in cur]\n valid = True\n \n temp[0] += strs[0...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python Greedy Solution
delete-columns-to-make-sorted-ii
0
1
```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m = len(strs)\n n = len(strs[0])\n\n cur = ["" for i in range(m)]\n res = 0\n\n for i in range(n):\n temp = [x for x in cur]\n valid = True\n \n temp[0] += strs[0...
0
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** par...
null
Python3 🐍 concise solution beats 99%
delete-columns-to-make-sorted-ii
0
1
# Code\n```\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and curre...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python3 🐍 concise solution beats 99%
delete-columns-to-make-sorted-ii
0
1
# Code\n```\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and curre...
0
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** par...
null
Python 3 | Greedy, DP (28 ms) | Explanation
delete-columns-to-make-sorted-ii
0
1
### Explanation\n- This idea is simple but there are some thing we need to be careful about\n- For each column, if we found any row pairs `(i, i+1)` not in order, then we need to remove this column\n\t- but we do this only if their previous column is not in order, e.g.\n\t- There is a tie in column 1, so we can\'t say ...
8
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python 3 | Greedy, DP (28 ms) | Explanation
delete-columns-to-make-sorted-ii
0
1
### Explanation\n- This idea is simple but there are some thing we need to be careful about\n- For each column, if we found any row pairs `(i, i+1)` not in order, then we need to remove this column\n\t- but we do this only if their previous column is not in order, e.g.\n\t- There is a tie in column 1, so we can\'t say ...
8
Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`. A **good array** is an array where the number of different integers in that array is exactly `k`. * For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`. A **subarray** is a **contiguous** par...
null
Solution
tallest-billboard
1
1
```C++ []\nclass Solution {\npublic:\n int tallestBillboard(vector<int>& rods) {\n int sum = 0;\n for (int rod : rods) {\n sum += rod;\n }\n int dp[sum + 1];\n dp[0] = 0;\n for (int i = 1; i <= sum; i++) {\n dp[i] = -1;\n }\n for (int rod : rods) {\n int dpCopy[sum + 1];\n c...
440
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld the...
null
Solution
tallest-billboard
1
1
```C++ []\nclass Solution {\npublic:\n int tallestBillboard(vector<int>& rods) {\n int sum = 0;\n for (int rod : rods) {\n sum += rod;\n }\n int dp[sum + 1];\n dp[0] = 0;\n for (int i = 1; i <= sum; i++) {\n dp[i] = -1;\n }\n for (int rod : rods) {\n int dpCopy[sum + 1];\n c...
440
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with d...
null
[Python3] Clean & Concise, DP Top-down Memoization with Cache
tallest-billboard
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can have `dp(i, left, right)`, and the recurrence relationship will be:\n1. adding to the left side `dp(i + 1, left + rods[i], right)`\n2. or, adding to the right `dp(i + 1, left, right + rods[i])`\n3. or, skip `dp(i + 1, left, right)`...
1
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld the...
null
[Python3] Clean & Concise, DP Top-down Memoization with Cache
tallest-billboard
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can have `dp(i, left, right)`, and the recurrence relationship will be:\n1. adding to the left side `dp(i + 1, left + rods[i], right)`\n2. or, adding to the right `dp(i + 1, left, right + rods[i])`\n3. or, skip `dp(i + 1, left, right)`...
1
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with d...
null
SIMPLE PYTHON SOLUTION USING DP
tallest-billboard
0
1
\n# Code\n```\nclass Solution:\n def dp(self,i,rods,sm,dct):\n if i<0:\n if sm==0:\n return 0\n return float("-infinity")\n if (i,sm) in dct:\n return dct[(i,sm)]\n x=self.dp(i-1,rods,sm-rods[i],dct)\n y=self.dp(i-1,rods,sm+rods[i],dct)+rods...
1
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld the...
null
SIMPLE PYTHON SOLUTION USING DP
tallest-billboard
0
1
\n# Code\n```\nclass Solution:\n def dp(self,i,rods,sm,dct):\n if i<0:\n if sm==0:\n return 0\n return float("-infinity")\n if (i,sm) in dct:\n return dct[(i,sm)]\n x=self.dp(i-1,rods,sm-rods[i],dct)\n y=self.dp(i-1,rods,sm+rods[i],dct)+rods...
1
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with d...
null
sort best solution in python code Plz🔥🧐👍 Upvoted👍👍👍
tallest-billboard
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 installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld the...
null
sort best solution in python code Plz🔥🧐👍 Upvoted👍👍👍
tallest-billboard
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 the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with d...
null
Clear Explanation with Dynamic Programming Solution
tallest-billboard
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we want the height of the left and right towers to be equal, we need to find a \n\n\n\n\n\n\n\nconfiguration of the rods such that the difference between the left tower and right tower is 0 and maximize that height. \n\n# Approach\n...
2
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld the...
null
Clear Explanation with Dynamic Programming Solution
tallest-billboard
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we want the height of the left and right towers to be equal, we need to find a \n\n\n\n\n\n\n\nconfiguration of the rods such that the difference between the left tower and right tower is 0 and maximize that height. \n\n# Approach\n...
2
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with d...
null
Python DP Easiest Solution
tallest-billboard
0
1
\n# Code\n```\nclass Solution(object):\n def tallestBillboard(self, rods):\n """\n :type rods: List[int]\n :rtype: int\n """\n ans={}\n return self.dfs(rods,0,0,ans)\n def dfs(self,nums,i,diff,ans):\n if (i,diff) in ans:\n return ans[(i,diff)]\n i...
1
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld the...
null
Python DP Easiest Solution
tallest-billboard
0
1
\n# Code\n```\nclass Solution(object):\n def tallestBillboard(self, rods):\n """\n :type rods: List[int]\n :rtype: int\n """\n ans={}\n return self.dfs(rods,0,0,ans)\n def dfs(self,nums,i,diff,ans):\n if (i,diff) in ans:\n return ans[(i,diff)]\n i...
1
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._ Two nodes of a binary tree are **cousins** if they have the same depth with d...
null
Solution
prison-cells-after-n-days
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> prisonAfterNDays(vector<int>& cells, int n) {\n if(n==0) return cells;\n int c = (n-1)%14 + 1;\n cout<<c;\n vector<int> newCell = cells;\n while(c--) {\n for(int i=1; i<7; i++) newCell[i] = !(cells[i-1]^cells[i+1]);\n ...
2
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
Solution
prison-cells-after-n-days
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> prisonAfterNDays(vector<int>& cells, int n) {\n if(n==0) return cells;\n int c = (n-1)%14 + 1;\n cout<<c;\n vector<int> newCell = cells;\n while(c--) {\n for(int i=1; i<7; i++) newCell[i] = !(cells[i-1]^cells[i+1]);\n ...
2
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
[Python3] Prison Cells After N days: dictionary to store pattern
prison-cells-after-n-days
0
1
* There must be a pattern in this problem. The length of the list is 8, and the first and last element of list will always be 0. So only 8-2= 6 items in the list will change. For each item, there are 2 possible values : 0 or 1. So the entile possible cell states will be less or equal to 2**6 = 64.\n\n* \uD83E\uDD89 t...
33
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
[Python3] Prison Cells After N days: dictionary to store pattern
prison-cells-after-n-days
0
1
* There must be a pattern in this problem. The length of the list is 8, and the first and last element of list will always be 0. So only 8-2= 6 items in the list will change. For each item, there are 2 possible values : 0 or 1. So the entile possible cell states will be less or equal to 2**6 = 64.\n\n* \uD83E\uDD89 t...
33
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
Simple Python Solution
prison-cells-after-n-days
0
1
The naive way is to compute the changes for N days (using the nextDay Function). But we can improve this because there will be a cycle and similar states will repeat. Since the first and last cell will become 0 after the the first day, the first day will eventually repeat if there is a cycle. So we keep a count of the ...
26
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
Simple Python Solution
prison-cells-after-n-days
0
1
The naive way is to compute the changes for N days (using the nextDay Function). But we can improve this because there will be a cycle and similar states will repeat. Since the first and last cell will become 0 after the the first day, the first day will eventually repeat if there is a cycle. So we keep a count of the ...
26
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
Very Intuitive Python Detailed Solution with Example
prison-cells-after-n-days
0
1
Lets just take an easier version of the question, **given the current state, find next state.**\n\nWe would write the following function, it just checks whether neighboring elements are same, if so, put a `1` else `0`\n\n```python\n def next(state):\n return tuple([1 if i>0 and i<len(state)-1 and stat...
11
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
Very Intuitive Python Detailed Solution with Example
prison-cells-after-n-days
0
1
Lets just take an easier version of the question, **given the current state, find next state.**\n\nWe would write the following function, it just checks whether neighboring elements are same, if so, put a `1` else `0`\n\n```python\n def next(state):\n return tuple([1 if i>0 and i<len(state)-1 and stat...
11
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
PYTHON SOL || FAST || MATHS || WELL EXPLAINED || PATTERN || LOGIC EXPLAINED ||
prison-cells-after-n-days
0
1
# EXPLANATION\n```\nThe size of our cells = 8 \nNow the first and last cell can never have two adjacent cells hence they will always be 1\n\nWe can make new cells array n number of times to solve this ques -> BRUTE FORCE\n\nBut when n is large like n = 10^9 we get TLE\n\nNow since we can\'t do brute force and the way o...
2
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
PYTHON SOL || FAST || MATHS || WELL EXPLAINED || PATTERN || LOGIC EXPLAINED ||
prison-cells-after-n-days
0
1
# EXPLANATION\n```\nThe size of our cells = 8 \nNow the first and last cell can never have two adjacent cells hence they will always be 1\n\nWe can make new cells array n number of times to solve this ques -> BRUTE FORCE\n\nBut when n is large like n = 10^9 we get TLE\n\nNow since we can\'t do brute force and the way o...
2
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
[Python] Easy O(1) Solution Explained
prison-cells-after-n-days
0
1
There is a pattern which repeats at every 14 steps. So we can simply take the modulo of N by 14 and calculate the pattern. Only there is a problem if the first and last cells are 1 at the beginning. In this case, the pattern will start after the first iteration. So take the modulo of N-1 by 14 and add 1 for the first i...
7
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
[Python] Easy O(1) Solution Explained
prison-cells-after-n-days
0
1
There is a pattern which repeats at every 14 steps. So we can simply take the modulo of N by 14 and calculate the pattern. Only there is a problem if the first and last cells are 1 at the beginning. In this case, the pattern will start after the first iteration. So take the modulo of N-1 by 14 and add 1 for the first i...
7
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
🚩 EXPLAINED by picture ^^
prison-cells-after-n-days
0
1
![image](https://assets.leetcode.com/users/images/075326f5-ca09-402b-a6ab-c5e37c1d0deb_1653839922.1718569.png)\n\n**Explanation:**\n\nThe state space consists of `256` 8-bit numbers.\nOn the picture we have all of `64` 8-bit `0...0` (starts and ends with `0`) numbers. The arrows show how they evolve under the rules of ...
4
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
🚩 EXPLAINED by picture ^^
prison-cells-after-n-days
0
1
![image](https://assets.leetcode.com/users/images/075326f5-ca09-402b-a6ab-c5e37c1d0deb_1653839922.1718569.png)\n\n**Explanation:**\n\nThe state space consists of `256` 8-bit numbers.\nOn the picture we have all of `64` 8-bit `0...0` (starts and ends with `0`) numbers. The arrows show how they evolve under the rules of ...
4
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
Easy Python Solution - Faster than 95% (36ms)
prison-cells-after-n-days
0
1
The cell patterns repeat after every 14 operations. This is the key logic in this question. Now that we have the upper cap of 14, take `n % 14` and solve the problem.\n\nHere, we also need to use the list.copy() method. This function ensures that the original list doesn\'t get altered once there are any changes in the...
1
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
Easy Python Solution - Faster than 95% (36ms)
prison-cells-after-n-days
0
1
The cell patterns repeat after every 14 operations. This is the key logic in this question. Now that we have the upper cap of 14, take `n % 14` and solve the problem.\n\nHere, we also need to use the list.copy() method. This function ensures that the original list doesn\'t get altered once there are any changes in the...
1
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
beats 95%
prison-cells-after-n-days
0
1
\n\n# Code\n```\nclass Solution(object):\n def nextDay(self, cells):\n res = [0] * len(cells)\n l = 0\n r = 2\n i = 1\n while i <= len(cells) - 2:\n if cells[l] == cells[r]:\n res[i] = 1\n else:\n res[i] = 0\n r += 1\n ...
0
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
beats 95%
prison-cells-after-n-days
0
1
\n\n# Code\n```\nclass Solution(object):\n def nextDay(self, cells):\n res = [0] * len(cells)\n l = 0\n r = 2\n i = 1\n while i <= len(cells) - 2:\n if cells[l] == cells[r]:\n res[i] = 1\n else:\n res[i] = 0\n r += 1\n ...
0
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
Simple Python Solution || No dict || Two For loops Beats 87%
prison-cells-after-n-days
0
1
# Code\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n vals = []\n prev = cells\n for _ in range(7) :\n new = [0]*8\n for i in range(1,len(cells)-1):\n if prev[i-1] == prev[i+1] : new[i] = 1\n prev = new...
0
There are `8` prison cells in a row and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: * If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. * Otherwise, it becomes vacant. ...
null
Simple Python Solution || No dict || Two For loops Beats 87%
prison-cells-after-n-days
0
1
# Code\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n vals = []\n prev = cells\n for _ in range(7) :\n new = [0]*8\n for i in range(1,len(cells)-1):\n if prev[i-1] == prev[i+1] : new[i] = 1\n prev = new...
0
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum nu...
null
SImple Pyhton3 Solution || Upto 90 % Faster || O(n) || Simple Explaination of DFS
check-completeness-of-a-binary-tree
0
1
# Intuition\n1. Start with a queue containing only the root node.\n\n2. While the first element in the queue is not None, remove the first element from the queue, and add its left and right children (if they exist) to the end of the queue.\n\n3. After the while loop, check if all remaining elements in the queue are Non...
2
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between ...
null
SImple Pyhton3 Solution || Upto 90 % Faster || O(n) || Simple Explaination of DFS
check-completeness-of-a-binary-tree
0
1
# Intuition\n1. Start with a queue containing only the root node.\n\n2. While the first element in the queue is not None, remove the first element from the queue, and add its left and right children (if they exist) to the end of the queue.\n\n3. After the while loop, check if all remaining elements in the queue are Non...
2
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. You are given the `root` of a maximum binary tree and an integer `val`. Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ...
null
Awesome Logic with BFS Python3
check-completeness-of-a-binary-tree
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:95%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:99%\n<!-- Add your space complexity here, e.g. $$O(n...
2
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between ...
null
Awesome Logic with BFS Python3
check-completeness-of-a-binary-tree
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:95%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:99%\n<!-- Add your space complexity here, e.g. $$O(n...
2
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. You are given the `root` of a maximum binary tree and an integer `val`. Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ...
null
BFS, df, easy 3-line solution in Python | Ruby | Go
check-completeness-of-a-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBFS, Queue\n# Approach\n<!-- Describe your approach to solving the problem. -->\nafter first `node == None` all elements of `q` should be `None`\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(n)$$\n\n# Code\n```Pyth...
1
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between ...
null
BFS, df, easy 3-line solution in Python | Ruby | Go
check-completeness-of-a-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBFS, Queue\n# Approach\n<!-- Describe your approach to solving the problem. -->\nafter first `node == None` all elements of `q` should be `None`\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(n)$$\n\n# Code\n```Pyth...
1
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. You are given the `root` of a maximum binary tree and an integer `val`. Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ...
null
Clean Code Python
check-completeness-of-a-binary-tree
0
1
**Please upvote the solution if u liked**\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isCompleteTree(self, root: Optional[TreeNode]) ->...
1
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between ...
null
Clean Code Python
check-completeness-of-a-binary-tree
0
1
**Please upvote the solution if u liked**\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def isCompleteTree(self, root: Optional[TreeNode]) ->...
1
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. You are given the `root` of a maximum binary tree and an integer `val`. Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ...
null
Python🐍 - Keeping track of the position of the last node seen (BFS)
check-completeness-of-a-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI keep track of the position of the last node I\'ve seen. The position in the binary tree is formed by the level of the tree and (at least what I called it) a column. In order for the tree to be complete, the current node always needs to ...
1
Given the `root` of a binary tree, determine if it is a _complete binary tree_. In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between ...
null
Python🐍 - Keeping track of the position of the last node seen (BFS)
check-completeness-of-a-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI keep track of the position of the last node I\'ve seen. The position in the binary tree is formed by the level of the tree and (at least what I called it) a column. In order for the tree to be complete, the current node always needs to ...
1
A **maximum tree** is a tree where every node has a value greater than any other value in its subtree. You are given the `root` of a maximum binary tree and an integer `val`. Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ...
null
Solution
regions-cut-by-slashes
1
1
```C++ []\nclass Solution {\npublic:\n class DisjointSet {\n public: \n vector<int> rank, parent, size;\n DisjointSet(int n) {\n rank.resize(n+1, 0); \n parent.resize(n+1);\n size.resize(n+1); \n for(int i = 0;i<=n;i++) {\n parent[i] = i; \n...
1
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return _the number of regions_. Note that backslash characters are escaped, so a `...
null
Solution
regions-cut-by-slashes
1
1
```C++ []\nclass Solution {\npublic:\n class DisjointSet {\n public: \n vector<int> rank, parent, size;\n DisjointSet(int n) {\n rank.resize(n+1, 0); \n parent.resize(n+1);\n size.resize(n+1); \n for(int i = 0;i<=n;i++) {\n parent[i] = i; \n...
1
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ...
null
DFS on upscaled grid
regions-cut-by-slashes
1
1
We can upscale the input grid to `[n * 3][n * 3]` grid and draw "lines" there. Then, we can paint empty regions using DFS and count them. Picture below says it all. Note that `[n * 2][n * 2]` grid does not work as "lines" are too thick to identify empty areas correctly.\n\n> This transform this problem into [200. Numb...
812
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return _the number of regions_. Note that backslash characters are escaped, so a `...
null
DFS on upscaled grid
regions-cut-by-slashes
1
1
We can upscale the input grid to `[n * 3][n * 3]` grid and draw "lines" there. Then, we can paint empty regions using DFS and count them. Picture below says it all. Note that `[n * 2][n * 2]` grid does not work as "lines" are too thick to identify empty areas correctly.\n\n> This transform this problem into [200. Numb...
812
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ...
null
Python Union Find solution with comments (easy to understand)
regions-cut-by-slashes
0
1
```\nclass UnionFind:\n def __init__(self, n):\n self.parent = [i for i in range(n)]\n \n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, a, b):\n self.parent[self.find(b)] = ...
13
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return _the number of regions_. Note that backslash characters are escaped, so a `...
null
Python Union Find solution with comments (easy to understand)
regions-cut-by-slashes
0
1
```\nclass UnionFind:\n def __init__(self, n):\n self.parent = [i for i in range(n)]\n \n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, a, b):\n self.parent[self.find(b)] = ...
13
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ...
null
Python Solution based on Transformation
regions-cut-by-slashes
0
1
# Intuition\nThe key takeaway here is to design graphs, not graph algorithms, which we get from Skiena. To this end, we "blow up" the original graph into a bigger graph, where the connections between cells are more obvious.\n\n# Approach\nWe transform each cell of the original graph into 4 cells on a new graph. The tra...
0
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return _the number of regions_. Note that backslash characters are escaped, so a `...
null
Python Solution based on Transformation
regions-cut-by-slashes
0
1
# Intuition\nThe key takeaway here is to design graphs, not graph algorithms, which we get from Skiena. To this end, we "blow up" the original graph into a bigger graph, where the connections between cells are more obvious.\n\n# Approach\nWe transform each cell of the original graph into 4 cells on a new graph. The tra...
0
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ...
null
Union find solution
regions-cut-by-slashes
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
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return _the number of regions_. Note that backslash characters are escaped, so a `...
null
Union find solution
regions-cut-by-slashes
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
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ...
null
Python 3 || 6 lines, dp || T/M: 64% / 64%
delete-columns-to-make-sorted-iii
0
1
```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n n = len(strs[0])\n\n isValid = lambda x: all(s[x] <= s[j] for s in strs)\n\n dp = [1] * n\n\n for j in range(1, n):\n\n dp[j] = max((dp[x] for x in \n filter(isValid,range(j)))...
3
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python 3 || 6 lines, dp || T/M: 64% / 64%
delete-columns-to-make-sorted-iii
0
1
```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n n = len(strs[0])\n\n isValid = lambda x: all(s[x] <= s[j] for s in strs)\n\n dp = [1] * n\n\n for j in range(1, n):\n\n dp[j] = max((dp[x] for x in \n filter(isValid,range(j)))...
3
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
Solution
delete-columns-to-make-sorted-iii
1
1
```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n \n int n = strs.size();\n int m = strs[0].length();\n\n vector<int> dp(m, 1);\n int res = 1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < i; j++) {\n for(int...
1
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Solution
delete-columns-to-make-sorted-iii
1
1
```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n \n int n = strs.size();\n int m = strs[0].length();\n\n vector<int> dp(m, 1);\n int res = 1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < i; j++) {\n for(int...
1
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
[Python3] O(mn^2) DP
delete-columns-to-make-sorted-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is similar to longest non-decrease subseqence, except we need to consider all strings at the same time.\n\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(...
1
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
[Python3] O(mn^2) DP
delete-columns-to-make-sorted-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is similar to longest non-decrease subseqence, except we need to consider all strings at the same time.\n\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(...
1
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
Solution to 960. Delete Columns to Make Sorted III
delete-columns-to-make-sorted-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem is to find the longest increasing subsequence of columns. This is because the columns in the longest increasing subsequence do not need to be deleted to make the rows sorted. The remaining columns, which ...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Solution to 960. Delete Columns to Make Sorted III
delete-columns-to-make-sorted-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem is to find the longest increasing subsequence of columns. This is because the columns in the longest increasing subsequence do not need to be deleted to make the rows sorted. The remaining columns, which ...
0
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
python super easy to understand (dp top down)
delete-columns-to-make-sorted-iii
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 an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
python super easy to understand (dp top down)
delete-columns-to-make-sorted-iii
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 are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
Python 3: LIS DP Solution with comments; TC - 99.37%
delete-columns-to-make-sorted-iii
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 an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
Python 3: LIS DP Solution with comments; TC - 99.37%
delete-columns-to-make-sorted-iii
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 are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
(Python) Delete Columns to Make Sorted III
delete-columns-to-make-sorted-iii
0
1
# Intuition\nThe intuition behind the approach is to use dynamic programming to find the length of the longest increasing subsequence (LIS) for each position in the strings. By keeping track of this information, we can determine the minimum number of deletions required to make all the strings lexicographically sorted.\...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
(Python) Delete Columns to Make Sorted III
delete-columns-to-make-sorted-iii
0
1
# Intuition\nThe intuition behind the approach is to use dynamic programming to find the length of the longest increasing subsequence (LIS) for each position in the strings. By keeping track of this information, we can determine the minimum number of deletions required to make all the strings lexicographically sorted.\...
0
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
NOT LIS intution
delete-columns-to-make-sorted-iii
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n strs=list(map(list,strs))\n n=len(strs[0])\n def check(i,last):\n if last==-1 or i>=n:\n return True\n for s in str...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null
NOT LIS intution
delete-columns-to-make-sorted-iii
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n strs=list(map(list,strs))\n n=len(strs[0])\n def check(i,last):\n if last==-1 or i>=n:\n return True\n for s in str...
0
There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones. A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles. Return _the minimum cost to merge all piles of stones into one pile...
null
Python solution in 5 lines
delete-columns-to-make-sorted-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is identical to the classic longest non-decreasing subsequence. \nThe problem can be efficiently solved in binary search. \nDue to the small input size, the solution based on the slower DP algorithm can also be accepted. \nTh...
0
You are given an array of `n` strings `strs`, all of the same length. We may choose any deletion indices, and we delete all the characters in those indices for each string. For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vy...
null