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 |
|---|---|---|---|---|---|---|---|
Clean Codes🔥|| Dynamic Programming ✅|| C++|| Java || Python3 | flip-string-to-monotone-increasing | 1 | 1 | # Request \uD83D\uDE0A :\n- If you find this solution easy to understand and helpful, then Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n# Code [C++| Java| Python3] :\n```C++ []\nclass Solution {\n public:\n int minFlipsMonoIncr(string S) {\n vector<int> dp(2);\n\n for (int i = 0; i < S.length(); ++i) {\n int temp... | 10 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,... | null |
Solution | flip-string-to-monotone-increasing | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minFlipsMonoIncr(string s) {\n int ans = 0, ones = 0;\n for (char c : s) {\n if (c == \'0\')\n ans = min(ones, ans + 1);\n else\n ones++;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nfrom... | 1 | A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increa... | null |
Solution | flip-string-to-monotone-increasing | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minFlipsMonoIncr(string s) {\n int ans = 0, ones = 0;\n for (char c : s) {\n if (c == \'0\')\n ans = min(ones, ans + 1);\n else\n ones++;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nfrom... | 1 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,... | null |
Full Solution Recursion --> Memoization --> Tabulation -->SpaceOptimization | flip-string-to-monotone-increasing | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def memo(self,s,ind,prev,dp):\n if ind>=len(s):\n return 0\n \n if dp[ind][prev]!=-1:\n return dp[ind][prev]\n flip=1000000\n notflip = 10000000\n ans=10000000\n if (s[ind]==\'0\'):\n if (prev==0):\n ... | 1 | A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increa... | null |
Full Solution Recursion --> Memoization --> Tabulation -->SpaceOptimization | flip-string-to-monotone-increasing | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def memo(self,s,ind,prev,dp):\n if ind>=len(s):\n return 0\n \n if dp[ind][prev]!=-1:\n return dp[ind][prev]\n flip=1000000\n notflip = 10000000\n ans=10000000\n if (s[ind]==\'0\'):\n if (prev==0):\n ... | 1 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,... | null |
Flip String to Monotone Increasing | flip-string-to-monotone-increasing | 0 | 1 | # Intuition\nFlip string to monotonic increasing that all 0\'s and all 1\'s comes together \n# Approach\nfirst we iterate through the string and check the 1\'s present in string if we come across any 1\'s then we increase the countOne otherwise we take min of (ans+1,countOne) ans return the answer\n# Complexity\n- Time... | 1 | A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none).
You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`.
Return _the minimum number of flips to make_ `s` _monotone increa... | null |
Flip String to Monotone Increasing | flip-string-to-monotone-increasing | 0 | 1 | # Intuition\nFlip string to monotonic increasing that all 0\'s and all 1\'s comes together \n# Approach\nfirst we iterate through the string and check the 1\'s present in string if we come across any 1\'s then we increase the countOne otherwise we take min of (ans+1,countOne) ans return the answer\n# Complexity\n- Time... | 1 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,... | null |
Solution | three-equal-parts | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> threeEqualParts(vector<int>& arr) {\n \n int countone=count(arr.begin(),arr.end(),1);\n int n=arr.size();\n if(countone%3)\n {\n return {-1,-1};\n }\n if(countone==0)\n {\n return {0,n-1};\n ... | 1 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Solution | three-equal-parts | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> threeEqualParts(vector<int>& arr) {\n \n int countone=count(arr.begin(),arr.end(),1);\n int n=arr.size();\n if(countone%3)\n {\n return {-1,-1};\n }\n if(countone==0)\n {\n return {0,n-1};\n ... | 1 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Simple Python Solution with explanation 🔥 | three-equal-parts | 0 | 1 | # Approach\n\n> *divide the array into three non-empty parts such that all of these parts represent the same binary value*\n\nSame binary value means \n\n* each part has to have **<ins>equal number of ones<ins>** and zeroes\n* order of ones and zeroes should be same\n\n\n### Part 1: Equal number of ones and ending zero... | 1 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Simple Python Solution with explanation 🔥 | three-equal-parts | 0 | 1 | # Approach\n\n> *divide the array into three non-empty parts such that all of these parts represent the same binary value*\n\nSame binary value means \n\n* each part has to have **<ins>equal number of ones<ins>** and zeroes\n* order of ones and zeroes should be same\n\n\n### Part 1: Equal number of ones and ending zero... | 1 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
2 clean Python linear solutions | three-equal-parts | 0 | 1 | ```\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n # count number of ones\n ones = sum(arr)\n if ones % 3 != 0:\n return [-1, -1]\n elif ones == 0: # special case: all zeros\n return [0, 2]\n \n # find the start index of e... | 7 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
2 clean Python linear solutions | three-equal-parts | 0 | 1 | ```\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n # count number of ones\n ones = sum(arr)\n if ones % 3 != 0:\n return [-1, -1]\n elif ones == 0: # special case: all zeros\n return [0, 2]\n \n # find the start index of e... | 7 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Easiest Solution | three-equal-parts | 1 | 1 | \n\n# Code\n```java []\nclass Solution {\n public int[] threeEqualParts(int[] arr) {\n int[] ans=new int[] {-1,-1};\n int ones=0;\n for(int x:arr) ones+=x;\n if(ones==0) return new int[] {0,2};\n if(ones%3!=0) return ans;\n int onesInEachPart=ones/3;\n int firstOneInd... | 0 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Easiest Solution | three-equal-parts | 1 | 1 | \n\n# Code\n```java []\nclass Solution {\n public int[] threeEqualParts(int[] arr) {\n int[] ans=new int[] {-1,-1};\n int ones=0;\n for(int x:arr) ones+=x;\n if(ones==0) return new int[] {0,2};\n if(ones%3!=0) return ans;\n int onesInEachPart=ones/3;\n int firstOneInd... | 0 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Solution based on substrings rather than subarrays. | three-equal-parts | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter my first couple of attempts to solve this problem, I realized that because of the limits of the inputs, it was possible to end up with three numbers of 10,000 digits each, which requires the use of expensive unlimited-precision inte... | 0 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Solution based on substrings rather than subarrays. | three-equal-parts | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter my first couple of attempts to solve this problem, I realized that because of the limits of the inputs, it was possible to end up with three numbers of 10,000 digits each, which requires the use of expensive unlimited-precision inte... | 0 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
[Python] 96% Straightforward Solution | three-equal-parts | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n n = sum(arr)\n if n % 3: return [-1, -1]\n if n == 0: return [0, 2]\n k, indices = n // 3, []\n for i, num in enumerate(arr):\n if num: indices.append(i)\n i1, i2, i3, i, ... | 0 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
[Python] 96% Straightforward Solution | three-equal-parts | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n n = sum(arr)\n if n % 3: return [-1, -1]\n if n == 0: return [0, 2]\n k, indices = n // 3, []\n for i, num in enumerate(arr):\n if num: indices.append(i)\n i1, i2, i3, i, ... | 0 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Python (Simple Maths) | three-equal-parts | 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 `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Python (Simple Maths) | three-equal-parts | 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 points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Extremely simple explanation. (Solution included) | three-equal-parts | 0 | 1 | So the idea is pretty simple, and yes, like most of them, you have to count the number of ones first.\n1. Count the number of ones (let\'s call it `ones`). If it\'s zero, return (0,size-1). If it isn\'t a multiple of 3, return [-1,-1], and if it is a factor of 3, let\'s proceed. *\n\n* Think about the array this way: \... | 0 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Extremely simple explanation. (Solution included) | three-equal-parts | 0 | 1 | So the idea is pretty simple, and yes, like most of them, you have to count the number of ones first.\n1. Count the number of ones (let\'s call it `ones`). If it\'s zero, return (0,size-1). If it isn\'t a multiple of 3, return [-1,-1], and if it is a factor of 3, let\'s proceed. *\n\n* Think about the array this way: \... | 0 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Python O(n) O(1) | pure logic deduction | three-equal-parts | 0 | 1 | # Intuition\r\nIf their are three equal parts, they must contain same amount of ones, and ends with same amount of zeros\r\nThe heading zeros is irrelevant\r\n\r\n# Approach\r\n- count ones, divide it by 3 to get ones count of each part\r\n- count tailing zeros, these zeros must contains in each part\r\n- hance we can ... | 0 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
Python O(n) O(1) | pure logic deduction | three-equal-parts | 0 | 1 | # Intuition\r\nIf their are three equal parts, they must contain same amount of ones, and ends with same amount of zeros\r\nThe heading zeros is irrelevant\r\n\r\n# Approach\r\n- count ones, divide it by 3 to get ones count of each part\r\n- count tailing zeros, these zeros must contains in each part\r\n- hance we can ... | 0 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
100% TC easy python solution | three-equal-parts | 0 | 1 | Hint\nCount the num of ones, and think how they will be split between the 3 segments :)\n```\ndef threeEqualParts(self, arr: List[int]) -> List[int]:\n\tn = len(arr)\n\tpos = [i for i in range(n) if(arr[i])]\n\tl = len(pos)\n\tif(l == 0):\n\t\treturn [0, 2]\n\tif(l % 3):\n\t\treturn [-1, -1]\n\tones = l//3\n\tc = 0\n\t... | 3 | You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value.
If it is possible, return any `[i, j]` with `i + 1 < j`, such that:
* `arr[0], arr[1], ..., arr[i]` is the first part,
* `arr[i + 1], ar... | null |
100% TC easy python solution | three-equal-parts | 0 | 1 | Hint\nCount the num of ones, and think how they will be split between the 3 segments :)\n```\ndef threeEqualParts(self, arr: List[int]) -> List[int]:\n\tn = len(arr)\n\tpos = [i for i in range(n) if(arr[i])]\n\tl = len(pos)\n\tif(l == 0):\n\t\treturn [0, 2]\n\tif(l % 3):\n\t\treturn [-1, -1]\n\tones = l//3\n\tc = 0\n\t... | 3 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will... | null |
Python 9 lines O(kn^2) BFS | minimize-malware-spread-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n # the key observation for me is the fact that we don\'t need to\n # really delete the initial in the graph. We can simply ignore\n # the deleted initial while we are doing BFS. So basically we\n # do BFS with each deleted value on initial, and we get the\n # minimal count... | 1 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Solution | minimize-malware-spread-ii | 1 | 1 | ```C++ []\nclass Solution {\n bool vis[300];\npublic:\n void dfs(const vector<vector<int>>&v,int node,const int nhi_dekhna,int &ans)\n {\n vis[node] = true;\n ++ans;\n for(auto &x : v[node])\n if(!vis[x] and x != nhi_dekhna)\n dfs(v,x,nhi_dekhna,ans);\n } \n ... | 1 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
[Python] DFS Solution- O(n ^ 2) => The cost of adjacency matrix | minimize-malware-spread-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to count the nodes which are infected by **only one** initial node.\nSo traversal from the initial nodes and stop until it encounter another initial nodes or already visited nodes.\n<br>\nDFS would pass each node once, so the comp... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Python3 FT 90%, O(V+E) time and space: Union-Find and Cut/Articulation Point Detection | minimize-malware-spread-ii | 0 | 1 | # The Idea\n\nWe can use union-find to find infected clusters.\n* if a cluster has one infected node, deleting it saves the whole cluster. So the reduction is size(component)\n* if a cluster has 2+ infected nodes, then we can still save some nodes if some of them are cut points (articulation points), and the new cluste... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Strongly connected components | minimize-malware-spread-ii | 0 | 1 | \n# Complexity\n- Time complexity:$$O(V+E)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(V)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n adj=col... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Union Find Algorithm || Graph || Python3 | minimize-malware-spread-ii | 0 | 1 | # Complexity\n- Time complexity: O(N * N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: Lis... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Minimize Malware Spread II (Python) | minimize-malware-spread-ii | 0 | 1 | Intuition:\nThe intuition behind the solution is to identify the initially infected node that, when removed, would minimize the spread of malware in the graph. To do this, the code first identifies the connected components in the graph using the Union-Find data structure. It then calculates the number of nodes in each ... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Solved by using Disjoint set | minimize-malware-spread-ii | 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 network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Brute-force DFS in Python, faster than 70% | minimize-malware-spread-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry all elements in `initial` and find the best one. This brute-force solution employs depth-first search (DFS) to explore all the inflected nodes in the network where one element from `initial` is removed. \n\n# Approach\n<!-- Describe y... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
O(N) Time and Space Union Find Approach | minimize-malware-spread-ii | 0 | 1 | # Intuition\nThe key intuition to this problem besides the realization of Union Find is that we are working with a special type of instance in this problem, namely that \n\nif a node has no infection, we don\'t have to care about it \nif a node has more than one infection, we also don\'t have to care about it \nonly if... | 0 | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected... | null |
Python3 solution | unique-email-addresses | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n myDict = set()\n for e in ema... | 1 | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add pe... | null |
Python3 solution | unique-email-addresses | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n myDict = set()\n for e in ema... | 1 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Outpu... | null |
📌📌 Easy & Simple || Well-Defined Code || For Beginners 🐍 | unique-email-addresses | 0 | 1 | \'\'\'\n\n\tclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n \n res = set()\n for email in emails:\n local,domain = email.split(\'@\')\n tmp = ""\n for c in local:\n if c==".": continue\n elif c=="+": break\n ... | 20 | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add pe... | null |
📌📌 Easy & Simple || Well-Defined Code || For Beginners 🐍 | unique-email-addresses | 0 | 1 | \'\'\'\n\n\tclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n \n res = set()\n for email in emails:\n local,domain = email.split(\'@\')\n tmp = ""\n for c in local:\n if c==".": continue\n elif c=="+": break\n ... | 20 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Outpu... | null |
Easy-understanding python solution (44ms, faster than 99.3%) | unique-email-addresses | 0 | 1 | ```\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n def parse(email):\n local, domain = email.split(\'@\')\n local = local.split(\'+\')[0].replace(\'.\',"")\n return f"{local}@{domain}"\n \n return len(set(map(parse, emails)))\n``` | 34 | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add pe... | null |
Easy-understanding python solution (44ms, faster than 99.3%) | unique-email-addresses | 0 | 1 | ```\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n def parse(email):\n local, domain = email.split(\'@\')\n local = local.split(\'+\')[0].replace(\'.\',"")\n return f"{local}@{domain}"\n \n return len(set(map(parse, emails)))\n``` | 34 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Outpu... | null |
simple solution | unique-email-addresses | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n arr=[]\n for i in emails:\n if \'@\' in i:\n at = i.index(\'@\')\n temp=i[:at]\n temp=temp.replace(".","")\n \n if \'+\' in tem... | 1 | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add pe... | null |
simple solution | unique-email-addresses | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n arr=[]\n for i in emails:\n if \'@\' in i:\n at = i.index(\'@\')\n temp=i[:at]\n temp=temp.replace(".","")\n \n if \'+\' in tem... | 1 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Outpu... | null |
Solution | unique-email-addresses | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int numUniqueEmails(vector<string>& emails) {\n unordered_set<string> uniqEmails;\n for(string& email: emails) {\n bool inDomain = false;\n string actEmail;\n int i = 0;\n for(int i = 0; i < email.size(); ) {\n ... | 2 | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add pe... | null |
Solution | unique-email-addresses | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int numUniqueEmails(vector<string>& emails) {\n unordered_set<string> uniqEmails;\n for(string& email: emails) {\n bool inDomain = false;\n string actEmail;\n int i = 0;\n for(int i = 0; i < email.size(); ) {\n ... | 2 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Outpu... | null |
Python 3 with explanations | unique-email-addresses | 0 | 1 | ```Python 3\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n\t\t# Create set which may contain only unique values\n\t\ts = set()\n\t\t# For every entry in the list\n for e in emails:\n\t\t\t# If entry is not empty\n if len(e) > 0:\n\t\t\t\t# Split entry into two parts - bef... | 17 | Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`.
* For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**.
If you add pe... | null |
Python 3 with explanations | unique-email-addresses | 0 | 1 | ```Python 3\nclass Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n\t\t# Create set which may contain only unique values\n\t\ts = set()\n\t\t# For every entry in the list\n for e in emails:\n\t\t\t# If entry is not empty\n if len(e) > 0:\n\t\t\t\t# Split entry into two parts - bef... | 17 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Outpu... | null |
Easy python solution beginners friendly. 🔥🔥 | binary-subarrays-with-sum | 0 | 1 | \n# Code\n```\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n //atmost(sum=goal) - atmost(sum=goal-1)\n return self.countSubarrays(nums,goal)-self.countSubarrays(nums,goal-1)\n\n def countSubarrays(self,nums,target):\n l=0\n count=0\n preSu... | 4 | Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0... | null |
Easy python solution beginners friendly. 🔥🔥 | binary-subarrays-with-sum | 0 | 1 | \n# Code\n```\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n //atmost(sum=goal) - atmost(sum=goal-1)\n return self.countSubarrays(nums,goal)-self.countSubarrays(nums,goal-1)\n\n def countSubarrays(self,nums,target):\n l=0\n count=0\n preSu... | 4 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with ... | null |
Sliding Window Approach | binary-subarrays-with-sum | 0 | 1 | ```\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n res=defaultdict(int)\n res[0]=1\n ans=0\n prefixsum=0\n for i in nums:\n prefixsum+=i\n ans+=res[prefixsum-goal]\n res[prefixsum]+=1\n return ans\n```\... | 5 | Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0... | null |
Sliding Window Approach | binary-subarrays-with-sum | 0 | 1 | ```\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n res=defaultdict(int)\n res[0]=1\n ans=0\n prefixsum=0\n for i in nums:\n prefixsum+=i\n ans+=res[prefixsum-goal]\n res[prefixsum]+=1\n return ans\n```\... | 5 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with ... | null |
python3 Sloution | binary-subarrays-with-sum | 0 | 1 | \n```\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n sumsMap,s,cnt={0:1},0,0\n for a in nums:\n s+=a\n if s-goal in sumsMap:\n cnt+=sumsMap[s-goal]\n sumsMap[s]=sumsMap.get(s,0)+1\n \n return cnt ... | 1 | Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0... | null |
python3 Sloution | binary-subarrays-with-sum | 0 | 1 | \n```\nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n sumsMap,s,cnt={0:1},0,0\n for a in nums:\n s+=a\n if s-goal in sumsMap:\n cnt+=sumsMap[s-goal]\n sumsMap[s]=sumsMap.get(s,0)+1\n \n return cnt ... | 1 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with ... | null |
EASY python sliding window O(1) space EXPLAINED THOROUGHLY | binary-subarrays-with-sum | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\nWe want to use a sliding window approach that keeps sliding the right pointer forward until we have counted the appropriate number of zeros. But it can\'t be solved like a usual sliding window problem because in some cases the rig... | 1 | Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0... | null |
EASY python sliding window O(1) space EXPLAINED THOROUGHLY | binary-subarrays-with-sum | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\n\r\nWe want to use a sliding window approach that keeps sliding the right pointer forward until we have counted the appropriate number of zeros. But it can\'t be solved like a usual sliding window problem because in some cases the rig... | 1 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with ... | null |
Easy Python Solution | binary-subarrays-with-sum | 0 | 1 | # Intuition\nCounting the subarrays where the sum equals some number is kind of hard and we have to find another way to solve this, may be use some tricks.\nWhat we can do is, we can count number of subarrays with sum greater than goal and also count nuumber of subarrays with sum less than goal, and then substract thes... | 1 | Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0... | null |
Easy Python Solution | binary-subarrays-with-sum | 0 | 1 | # Intuition\nCounting the subarrays where the sum equals some number is kind of hard and we have to find another way to solve this, may be use some tricks.\nWhat we can do is, we can count number of subarrays with sum greater than goal and also count nuumber of subarrays with sum less than goal, and then substract thes... | 1 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with ... | null |
[Handle edge cases by appending maximum at start and end]: Very short & clean python code. | minimum-falling-path-sum | 0 | 1 | # Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n \n maxi = float(\'inf\')\n ... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
[Handle edge cases by appending maximum at start and end]: Very short & clean python code. | minimum-falling-path-sum | 0 | 1 | # Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n \n maxi = float(\'inf\')\n ... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
Python Simple 4 Line Solution | minimum-falling-path-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor the first row, we already have the path sum if we pick each column (the value in that one cell).\n\nFor the second row and onward, notice we will just pick the minimum of the three above (above left, abve, and above right, if possible... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
Python Simple 4 Line Solution | minimum-falling-path-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor the first row, we already have the path sum if we pick each column (the value in that one cell).\n\nFor the second row and onward, notice we will just pick the minimum of the three above (above left, abve, and above right, if possible... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
[Python] Minimum Falling Path Sum | minimum-falling-path-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
[Python] Minimum Falling Path Sum | minimum-falling-path-sum | 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 two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
Easy for understand Python | minimum-falling-path-sum | 0 | 1 | \n# Complexity\n- Time complexity: O(n * n)\n\n- Space complexity: O(n * n)\n\n# Code\n```\nclass Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n n = len(matrix)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[0][i] = matrix[0][i]\n \n ... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
Easy for understand Python | minimum-falling-path-sum | 0 | 1 | \n# Complexity\n- Time complexity: O(n * n)\n\n- Space complexity: O(n * n)\n\n# Code\n```\nclass Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n n = len(matrix)\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[0][i] = matrix[0][i]\n \n ... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
90% Faster || O(n) Time complexity || Dynamic Programming | minimum-falling-path-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculating minimum upto a cell.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space comple... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
90% Faster || O(n) Time complexity || Dynamic Programming | minimum-falling-path-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculating minimum upto a cell.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space comple... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
beats 96.9 % | CodeDominar Solution | DP Bottom-up approach | minimum-falling-path-sum | 0 | 1 | \n# Code\n```\nclass Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n rows,cols = len(matrix),len(matrix[0])\n dp = [[float(\'inf\') for c in range(cols+2)] for r in range(rows+1)]\n \n for c in range(1,cols+1):\n dp[rows][c] = 0\n \n for... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
beats 96.9 % | CodeDominar Solution | DP Bottom-up approach | minimum-falling-path-sum | 0 | 1 | \n# Code\n```\nclass Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n rows,cols = len(matrix),len(matrix[0])\n dp = [[float(\'inf\') for c in range(cols+2)] for r in range(rows+1)]\n \n for c in range(1,cols+1):\n dp[rows][c] = 0\n \n for... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
Python DP | minimum-falling-path-sum | 0 | 1 | # Intuition\nIt\'s a simple DP problem. We need to start with the first row and check row-by-row, and maintaining minimal falling path.\n\n# Approach\nAt each iteration we maintain minimal falling pathes for each item in the row. For a given item it\'s sum will be minimal among pathes from the previous row plus current... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
Python DP | minimum-falling-path-sum | 0 | 1 | # Intuition\nIt\'s a simple DP problem. We need to start with the first row and check row-by-row, and maintaining minimal falling path.\n\n# Approach\nAt each iteration we maintain minimal falling pathes for each item in the row. For a given item it\'s sum will be minimal among pathes from the previous row plus current... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
Solution | minimum-falling-path-sum | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minFallingPathSum(vector<vector<int>>& matrix)\n {\n int ans=matrix[0][0];\n for(int i=1 ; i<matrix.size() ; i++)\n {\n for(int j=0 ; j<matrix.size() ; j++)\n {\n if(j==0)\n {\n m... | 1 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
Solution | minimum-falling-path-sum | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minFallingPathSum(vector<vector<int>>& matrix)\n {\n int ans=matrix[0][0];\n for(int i=1 ; i<matrix.size() ; i++)\n {\n for(int j=0 ; j<matrix.size() ; j++)\n {\n if(j==0)\n {\n m... | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
Simple python solution with memoization | minimum-falling-path-sum | 0 | 1 | # Intuition\nFirst thing that comes to mind is Depth First Search but you can quickly realiza that DFS will lead to Time Limit Exceeded. Becasue we are solving a summation problem at each level again and again that leads to memoization, we can save the computation by only calculating once the minimum sum possible if we... | 2 | Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`.
A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro... | null |
Simple python solution with memoization | minimum-falling-path-sum | 0 | 1 | # Intuition\nFirst thing that comes to mind is Depth First Search but you can quickly realiza that DFS will lead to Time Limit Exceeded. Becasue we are solving a summation problem at each level again and again that leads to memoization, we can save the computation by only calculating once the minimum sum possible if we... | 2 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n... | null |
Solution | beautiful-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> beautifulArray(int n) {\n vector<int> res = {1};\n while(res.size() != n){\n vector<int> temp;\n for(auto &ele : res) if(ele*2-1<=n) temp.push_back(ele*2-1);\n for(auto &ele : res) if(ele*2<=n) temp.push_back(ele*2);\n ... | 1 | An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w... | null |
Solution | beautiful-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> beautifulArray(int n) {\n vector<int> res = {1};\n while(res.size() != n){\n vector<int> temp;\n for(auto &ele : res) if(ele*2-1<=n) temp.push_back(ele*2-1);\n for(auto &ele : res) if(ele*2<=n) temp.push_back(ele*2);\n ... | 1 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Exp... | null |
easy code for beginner with one line | beautiful-array | 0 | 1 | # Intuition\nfirst i done it on 20 lines but now it is one line\n\n# Approach\ndone through simple reccurrsion\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n de... | 2 | An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w... | null |
easy code for beginner with one line | beautiful-array | 0 | 1 | # Intuition\nfirst i done it on 20 lines but now it is one line\n\n# Approach\ndone through simple reccurrsion\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n de... | 2 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Exp... | null |
Detailed Explanation with Diagrams. A Collection of Ideas from Multiple Posts. [Python3] | beautiful-array | 0 | 1 | ## 0. Introduction\nThis post is a collection of all the posts, comments and discussions of the LeetCode community. References mentioned at the bottom! I\'ve attempted to explain things in detail, with diagrams to help understand the intuitions as well.\n\n## 1. Naive Solution\nThe first thing anyone can think of is us... | 50 | An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w... | null |
Detailed Explanation with Diagrams. A Collection of Ideas from Multiple Posts. [Python3] | beautiful-array | 0 | 1 | ## 0. Introduction\nThis post is a collection of all the posts, comments and discussions of the LeetCode community. References mentioned at the bottom! I\'ve attempted to explain things in detail, with diagrams to help understand the intuitions as well.\n\n## 1. Naive Solution\nThe first thing anyone can think of is us... | 50 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Exp... | null |
Python3 solution with detailed explanation - Beautiful Array | beautiful-array | 0 | 1 | First, divide the array into even numbers and odd numbers so that we only need to further arrange numbers within even or odd numbers themselves because nums[i] and nums[j] must be both even or odd and can\'t be one even and one old. \n\nThen, further divide each division into numbers at even indices and odd indices til... | 13 | An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w... | null |
Python3 solution with detailed explanation - Beautiful Array | beautiful-array | 0 | 1 | First, divide the array into even numbers and odd numbers so that we only need to further arrange numbers within even or odd numbers themselves because nums[i] and nums[j] must be both even or odd and can\'t be one even and one old. \n\nThen, further divide each division into numbers at even indices and odd indices til... | 13 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Exp... | null |
Python easy solution | beautiful-array | 0 | 1 | ```\ndef beautifulArray(self, n: int) -> List[int]:\n\tans = [1]\n\twhile len(ans) < n:\n\t\tres = []\n\t\tfor el in ans:\n\t\t\tif 2 * el - 1 <= n:\n\t\t\t\tres.append(el * 2 - 1)\n\n\t\tfor el in ans: \n\t\t\tif 2 * el <= n:\n\t\t\t\tres.append(el * 2)\n\n\t\tans = res\n\treturn ans\n\n# odd ele -> 2 * el - 1\n# even... | 3 | An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w... | null |
Python easy solution | beautiful-array | 0 | 1 | ```\ndef beautifulArray(self, n: int) -> List[int]:\n\tans = [1]\n\twhile len(ans) < n:\n\t\tres = []\n\t\tfor el in ans:\n\t\t\tif 2 * el - 1 <= n:\n\t\t\t\tres.append(el * 2 - 1)\n\n\t\tfor el in ans: \n\t\t\tif 2 * el <= n:\n\t\t\t\tres.append(el * 2)\n\n\t\tans = res\n\treturn ans\n\n# odd ele -> 2 * el - 1\n# even... | 3 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Exp... | null |
Python O(n) solution | beautiful-array | 0 | 1 | In this problem we have n = 1000, which is too big to use dfs/backtracking, so we need to find some pattern. We need to avoid structures like i < k < j with nums[i] + nums[j] = 2 * nums[k], which means that nums[i] and nums[j] has the same parity: they are both odd or even. This lead us to the following idea: let us sp... | 0 | An array `nums` of length `n` is **beautiful** if:
* `nums` is a permutation of the integers in the range `[1, n]`.
* For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`.
Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w... | null |
Python O(n) solution | beautiful-array | 0 | 1 | In this problem we have n = 1000, which is too big to use dfs/backtracking, so we need to find some pattern. We need to avoid structures like i < k < j with nums[i] + nums[j] = 2 * nums[k], which means that nums[i] and nums[j] has the same parity: they are both odd or even. This lead us to the following idea: let us sp... | 0 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Exp... | null |
Easy - 3000 milliseconds | number-of-recent-calls | 0 | 1 | # Intuition\nThe task requires us to count the number of recent requests within a certain time frame. The first intuition is to keep track of the requests as they come in. However, we only care about the requests that happened in the last 3000 milliseconds. This suggests that we should remove old requests that are no l... | 9 | You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a... | null |
Easy - 3000 milliseconds | number-of-recent-calls | 0 | 1 | # Intuition\nThe task requires us to count the number of recent requests within a certain time frame. The first intuition is to keep track of the requests as they come in. However, we only care about the requests that happened in the last 3000 milliseconds. This suggests that we should remove old requests that are no l... | 9 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake f... | null |
Beating 99.34% Python Easiest Solution | number-of-recent-calls | 0 | 1 | \n\n\n# Code\n```\nfrom collections import deque\nclass RecentCounter:\n\n def __init__(self):\n self.q = deque()\n \n def ping(self, t: int) -> int:\n self.q.append(t)\n \n... | 10 | You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a... | null |
Beating 99.34% Python Easiest Solution | number-of-recent-calls | 0 | 1 | \n\n\n# Code\n```\nfrom collections import deque\nclass RecentCounter:\n\n def __init__(self):\n self.q = deque()\n \n def ping(self, t: int) -> int:\n self.q.append(t)\n \n... | 10 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake f... | null |
Solution | number-of-recent-calls | 1 | 1 | ```C++ []\nclass RecentCounter {\npublic:\nqueue<int>q;\n RecentCounter() { \n }\n int ping(int t) {\n q.push(t);\n while(q.front()<t-3000){\n q.pop();\n }\n return q.size(); \n }\n};\n```\n\n```Python3 []\nfrom collections import deque\n\nclass RecentCounter:\n\n def ... | 2 | You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a... | null |
Solution | number-of-recent-calls | 1 | 1 | ```C++ []\nclass RecentCounter {\npublic:\nqueue<int>q;\n RecentCounter() { \n }\n int ping(int t) {\n q.push(t);\n while(q.front()<t-3000){\n q.pop();\n }\n return q.size(); \n }\n};\n```\n\n```Python3 []\nfrom collections import deque\n\nclass RecentCounter:\n\n def ... | 2 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake f... | null |
Simple Solution But logical, Beats 99.70% | number-of-recent-calls | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen I saw this problem for the first time, I thought problems related to queue in leetcode need to be solved by Node, but it is easier than Nodes here.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn while statem... | 1 | You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a... | null |
Simple Solution But logical, Beats 99.70% | number-of-recent-calls | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen I saw this problem for the first time, I thought problems related to queue in leetcode need to be solved by Node, but it is easier than Nodes here.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn while statem... | 1 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake f... | null |
Python simple queue solution – beats 97% | number-of-recent-calls | 0 | 1 | # Code\n```\nclass RecentCounter:\n\n def __init__(self):\n self.s = []\n\n def ping(self, t: int) -> int:\n while self.s and t - self.s[0] > 3000:\n self.s.pop(0) # remove 1st el if it\'s 3000+ away from t\n self.s.append(t)\n return len(self.s) \n\n```\n\nupdate:\n![\u042... | 4 | You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a... | null |
Python simple queue solution – beats 97% | number-of-recent-calls | 0 | 1 | # Code\n```\nclass RecentCounter:\n\n def __init__(self):\n self.s = []\n\n def ping(self, t: int) -> int:\n while self.s and t - self.s[0] > 3000:\n self.s.pop(0) # remove 1st el if it\'s 3000+ away from t\n self.s.append(t)\n return len(self.s) \n\n```\n\nupdate:\n![\u042... | 4 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake f... | null |
Python solution - queue | number-of-recent-calls | 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:0(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n\n# Code\n```\nclass RecentCounter:\n\n de... | 2 | You have a `RecentCounter` class which counts the number of recent requests within a certain time frame.
Implement the `RecentCounter` class:
* `RecentCounter()` Initializes the counter with zero recent requests.
* `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.