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
JAVA | Kadane's | O(N) O(1)
maximum-sum-circular-subarray
1
1
# Intuition\n1. Find max sum subarray\n2. Find min sum subarray\n3. answer is max of (max sum subarray) && (totalSum - min sum subarray)\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int maxSubarraySumCircular(int[] nums) {\n boolean hasZeros ...
1
Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` ...
null
JAVA | Kadane's | O(N) O(1)
maximum-sum-circular-subarray
1
1
# Intuition\n1. Find max sum subarray\n2. Find min sum subarray\n3. answer is max of (max sum subarray) && (totalSum - min sum subarray)\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int maxSubarraySumCircular(int[] nums) {\n boolean hasZeros ...
1
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 ...
Python3 🔥🔥🔥 | Very Easy Solution | Kadane's Algorithem | O(n) complexity
maximum-sum-circular-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Using Kadane\'s Algorithem with small tweek we can solve this**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- So at start from simple kadane\'s algo from **maxi1** we can get maxsum without circular array co...
2
Given a **circular integer array** `nums` of length `n`, return _the maximum possible sum of a non-empty **subarray** of_ `nums`. A **circular array** means the end of the array connects to the beginning of the array. Formally, the next element of `nums[i]` is `nums[(i + 1) % n]` and the previous element of `nums[i]` ...
null
Python3 🔥🔥🔥 | Very Easy Solution | Kadane's Algorithem | O(n) complexity
maximum-sum-circular-subarray
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Using Kadane\'s Algorithem with small tweek we can solve this**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- So at start from simple kadane\'s algo from **maxi1** we can get maxsum without circular array co...
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
complete-binary-tree-inserter
1
1
```C++ []\nclass CBTInserter {\n TreeNode* root;\n int nodeCnt;\n int count(TreeNode* root) {\n if (!root) return 0;\n if (!root->left) root->right = NULL;\n return 1 + count(root->left) + count(root->right);\n }\npublic:\n CBTInserter(TreeNode* root) {\n this->root = root;\n ...
1
A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the `CBTInserter` class: * `CBTInserter(...
null
90% Tc easy python solution
complete-binary-tree-inserter
0
1
```\nclass CBTInserter:\n def __init__(self, root: Optional[TreeNode]):\n self.d = dict()\n def dfs(node, i):\n if not(node): return 0\n self.d[i] = node\n return 1 + dfs(node.left, 2*i) + dfs(node.right, 2*i+1)\n self.root = root\n self.l = dfs(root, 1)\n...
1
A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the `CBTInserter` class: * `CBTInserter(...
null
Python O(n) init O(1) insert by queue. 80%+ [w/ Diagram]
complete-binary-tree-inserter
0
1
Python O(n) init O(1) insert by queue.\n\n---\n\n**Hint**:\n\nUtilize the nature of **numbering** in complete binary tree\nNumber each node, start from root as 1, 2, 3, ..., and so on.\n\nFor each node with of number *k*,\nnode with ( 2*k* ) is left child\nnode with ( 2*k* + 1 ) is right child\n\nMaintin a **queue** (i...
14
A **complete binary tree** is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement the `CBTInserter` class: * `CBTInserter(...
null
🔥 Rust, Go & Combinatorics
number-of-music-playlists
0
1
# Introduction\nIn this video, we\'re going to dive deep into a fascinating problem that combines dynamic programming, combinatorics, and music playlists! Imagine you\'re going on a trip and you want to create a playlist with a specific number of songs. However, you don\'t want to hear the same song again until `k` oth...
5
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
🔥 Rust, Go & Combinatorics
number-of-music-playlists
0
1
# Introduction\nIn this video, we\'re going to dive deep into a fascinating problem that combines dynamic programming, combinatorics, and music playlists! Imagine you\'re going on a trip and you want to create a playlist with a specific number of songs. However, you don\'t want to hear the same song again until `k` oth...
5
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
✅ 100% Dynamic Programming [VIDEO] Creating Unique Music Playlists
number-of-music-playlists
1
1
# Intuition\nThe task is to create a music playlist with `n` different songs and a total of `goal` songs, where each song must be played at least once, and a song can only be played again if `k` other songs have been played. The challenge is to calculate the total number of possible playlists.\n\nAt first glance, this ...
70
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
✅ 100% Dynamic Programming [VIDEO] Creating Unique Music Playlists
number-of-music-playlists
1
1
# Intuition\nThe task is to create a music playlist with `n` different songs and a total of `goal` songs, where each song must be played at least once, and a song can only be played again if `k` other songs have been played. The challenge is to calculate the total number of possible playlists.\n\nAt first glance, this ...
70
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 short and clean. 4 solutions. DP and Combinatorics. Functional programming.
number-of-music-playlists
0
1
# Approach 1: Top-Down DP\nTL;DR, Similar to [Editorial solution Approach 2](https://leetcode.com/problems/number-of-music-playlists/editorial/) but shorter and cleaner.\n\n# Complexity\n- Time complexity: $$O(n * goal)$$\n\n- Space complexity: $$O(n * goal)$$\n\n# Code\n```python\nclass Solution:\n def numMusicPlay...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Python short and clean. 4 solutions. DP and Combinatorics. Functional programming.
number-of-music-playlists
0
1
# Approach 1: Top-Down DP\nTL;DR, Similar to [Editorial solution Approach 2](https://leetcode.com/problems/number-of-music-playlists/editorial/) but shorter and cleaner.\n\n# Complexity\n- Time complexity: $$O(n * goal)$$\n\n- Space complexity: $$O(n * goal)$$\n\n# Code\n```python\nclass Solution:\n def numMusicPlay...
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
5 line Python solution, beats 100%
number-of-music-playlists
0
1
\nThis follows the exact same logic as the combinatorics solution in the editorial, so I won\'t try to shittily re-explain it here. I think that editorial is a great reference, but they made the actual implementation wayyyy more complicated than it needed to be, so here\'s a simpler one:\n\n# Code\n```\n# combinatorics...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
5 line Python solution, beats 100%
number-of-music-playlists
0
1
\nThis follows the exact same logic as the combinatorics solution in the editorial, so I won\'t try to shittily re-explain it here. I think that editorial is a great reference, but they made the actual implementation wayyyy more complicated than it needed to be, so here\'s a simpler one:\n\n# Code\n```\n# combinatorics...
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 THE BEST UZBEKISTAN
number-of-music-playlists
0
1
# Intuition\n![Screenshot from 2023-08-06 18-21-25.png](https://assets.leetcode.com/users/images/b0d7c0b3-063c-4dad-b046-cc0abb0bb39b_1691328142.8254735.png)\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- Tim...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
PYTHON3 THE BEST UZBEKISTAN
number-of-music-playlists
0
1
# Intuition\n![Screenshot from 2023-08-06 18-21-25.png](https://assets.leetcode.com/users/images/b0d7c0b3-063c-4dad-b046-cc0abb0bb39b_1691328142.8254735.png)\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- Tim...
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
Recursion with memorization : Python with example
number-of-music-playlists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a hard problem to grasp.\nAt first it looks like we can easily solve it using permutaitons but no.\n\nAlso the conditions are not explained correctly.\n\nThe condition for k , is actually saying that if k = 2 and n = 3\nand we hav...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Recursion with memorization : Python with example
number-of-music-playlists
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a hard problem to grasp.\nAt first it looks like we can easily solve it using permutaitons but no.\n\nAlso the conditions are not explained correctly.\n\nThe condition for k , is actually saying that if k = 2 and n = 3\nand we hav...
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
Easy Explanation ever || Step-by-step Process || Python || Memoization
number-of-music-playlists
0
1
# Explanation\n1)We have to play goal No. of songs from n songs given that\n--->1.1)All n songs should be played atleast once and\n--->1.2)Replay of a song is only possible if there are k different songs played in between.\n2)So, at each song we can eighter play_new_song or replay_old_song\n--->2.1)if we play_new_song ...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Easy Explanation ever || Step-by-step Process || Python || Memoization
number-of-music-playlists
0
1
# Explanation\n1)We have to play goal No. of songs from n songs given that\n--->1.1)All n songs should be played atleast once and\n--->1.2)Replay of a song is only possible if there are k different songs played in between.\n2)So, at each song we can eighter play_new_song or replay_old_song\n--->2.1)if we play_new_song ...
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 Solution
number-of-music-playlists
0
1
\n```\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n mod=10**9+7\n @cache\n def fn(i,x):\n if i==goal:\n return x==n\n\n ans=0\n if x<n:\n ans+=(n-x)*fn(i+1,x+1)\n\n if k<x:\n ...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Python3 Solution
number-of-music-playlists
0
1
\n```\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n mod=10**9+7\n @cache\n def fn(i,x):\n if i==goal:\n return x==n\n\n ans=0\n if x<n:\n ans+=(n-x)*fn(i+1,x+1)\n\n if k<x:\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
Solution
number-of-music-playlists
1
1
```C++ []\nclass Solution {\npublic:\n int numMusicPlaylists(int n, int goal, int k) {\n \n const unsigned MOD = 1\'000\'000\'007;\n long dp[1+goal][1+n];\n memset( dp, 0, sizeof(dp) );\n dp[0][0] = 1;\n \n for( int i = 1; i <= goal; ++i )\n for( int j = 1; j <...
1
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Solution
number-of-music-playlists
1
1
```C++ []\nclass Solution {\npublic:\n int numMusicPlaylists(int n, int goal, int k) {\n \n const unsigned MOD = 1\'000\'000\'007;\n long dp[1+goal][1+n];\n memset( dp, 0, sizeof(dp) );\n dp[0][0] = 1;\n \n for( int i = 1; i <= goal; ++i )\n for( int j = 1; j <...
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 - Dead Simple DP - Beats 99%
number-of-music-playlists
0
1
\n```\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n @lru_cache(None)\n def dp(uniques, repeats, rem, songsTilNewRepeat):\n if songsTilNewRepeat == 0:\n repeats += 1\n songsTilNewRepeat = 1\n if uniques > rem:\n ...
10
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Python3 - Dead Simple DP - Beats 99%
number-of-music-playlists
0
1
\n```\nclass Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n @lru_cache(None)\n def dp(uniques, repeats, rem, songsTilNewRepeat):\n if songsTilNewRepeat == 0:\n repeats += 1\n songsTilNewRepeat = 1\n if uniques > rem:\n ...
10
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
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
number-of-music-playlists
1
1
# Intuition\nUsing dynamic programming to keep values that represent the number of valid playlists for different combinations of playlist length and unique songs.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\nhttps://youtu.be/6M7QoVTRgSE\n\n# Subscribe to my channel from here. I have 241 vi...
16
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `g...
null
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
number-of-music-playlists
1
1
# Intuition\nUsing dynamic programming to keep values that represent the number of valid playlists for different combinations of playlist length and unique songs.\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\nhttps://youtu.be/6M7QoVTRgSE\n\n# Subscribe to my channel from here. I have 241 vi...
16
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 solution beats 95% using stack O(N) SPACE
minimum-add-to-make-parentheses-valid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have the general way to find the validness of paranthesis we can use that and modify it a bit to solve this\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* if \'(\' is there append it\n* if \')\' is there then...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
python3 solution beats 95% using stack O(N) SPACE
minimum-add-to-make-parentheses-valid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe have the general way to find the validness of paranthesis we can use that and modify it a bit to solve this\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* if \'(\' is there append it\n* if \')\' is there then...
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
Simple solution with using Stack DS, beats 72%/64%
minimum-add-to-make-parentheses-valid
0
1
# Intuition\nThe problem is the common as [Stack DS](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)).\n\n# Approach\n1. initialize an empty `stack`\n2. iterate over all token in `s`\n3. check if token is `(` or if `stack` is empty, if last token in `stack` is a `)`\n4. return a length of a `stack` \n\n# Compl...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Simple solution with using Stack DS, beats 72%/64%
minimum-add-to-make-parentheses-valid
0
1
# Intuition\nThe problem is the common as [Stack DS](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)).\n\n# Approach\n1. initialize an empty `stack`\n2. iterate over all token in `s`\n3. check if token is `(` or if `stack` is empty, if last token in `stack` is a `)`\n4. return a length of a `stack` \n\n# Compl...
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
Python || 96.41% Faster || Space - O(1) and O(n)
minimum-add-to-make-parentheses-valid
0
1
**Without Stack Soltuion:**\n```\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n o=c=0\n for i in s:\n if i==\'(\':\n o+=1\n else:\n if o:\n o-=1\n else:\n c+=1\n return o+c\...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Python || 96.41% Faster || Space - O(1) and O(n)
minimum-add-to-make-parentheses-valid
0
1
**Without Stack Soltuion:**\n```\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n o=c=0\n for i in s:\n if i==\'(\':\n o+=1\n else:\n if o:\n o-=1\n else:\n c+=1\n return o+c\...
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
Minimum add to make parentheses valid
minimum-add-to-make-parentheses-valid
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
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Minimum add to make parentheses valid
minimum-add-to-make-parentheses-valid
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
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
minimum-add-to-make-parentheses-valid
1
1
```C++ []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<char> st;\n int ans=0;\n for(auto x:s)\n {\n if(x==\'(\')\n st.push(x);\n else\n {\n if(!st.empty())\n st.pop();\n ...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Solution
minimum-add-to-make-parentheses-valid
1
1
```C++ []\nclass Solution {\npublic:\n int minAddToMakeValid(string s) {\n stack<char> st;\n int ans=0;\n for(auto x:s)\n {\n if(x==\'(\')\n st.push(x);\n else\n {\n if(!st.empty())\n st.pop();\n ...
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
stack
minimum-add-to-make-parentheses-valid
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
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
stack
minimum-add-to-make-parentheses-valid
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
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 Java & Python3 Solution | Beats 100 % in java and Python3| Explained | O(n)
minimum-add-to-make-parentheses-valid
1
1
The provided code takes a string s as input and calculates the minimum number of parentheses needed to make the string balanced. It does this by iterating over the string and keeping track of an integer variable total that represents the difference between the number of opening and closing parentheses encountered so fa...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Simple Java & Python3 Solution | Beats 100 % in java and Python3| Explained | O(n)
minimum-add-to-make-parentheses-valid
1
1
The provided code takes a string s as input and calculates the minimum number of parentheses needed to make the string balanced. It does this by iterating over the string and keeping track of an integer variable total that represents the difference between the number of opening and closing parentheses encountered so fa...
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
🧠[C++/Java/Python]: One Pass Easy Solution
minimum-add-to-make-parentheses-valid
1
1
## Approach\n> 1. Initialize an empty stack st to keep track of unmatched opening parentheses.\n> 2. Iterate through each character i in the input string s.\n\n> 3. For each character i:\n> * If the stack is empty, push the character onto the stack because there\'s nothing to match it with.\n> * If the stack is not emp...
3
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
🧠[C++/Java/Python]: One Pass Easy Solution
minimum-add-to-make-parentheses-valid
1
1
## Approach\n> 1. Initialize an empty stack st to keep track of unmatched opening parentheses.\n> 2. Iterate through each character i in the input string s.\n\n> 3. For each character i:\n> * If the stack is empty, push the character onto the stack because there\'s nothing to match it with.\n> * If the stack is not emp...
3
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 Solution | O(N) Time and Space Complexity | Stack
minimum-add-to-make-parentheses-valid
0
1
Approach:\nwe can use stack to solve this problem:\nThe problem is the same as checking the given set of parentheses are whether valid or not. if the given string parentheses are valid, then our stack will be empty. but if the string input is not a valid parentheses, then there will be some parentheses left in the stac...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Python3 Solution | O(N) Time and Space Complexity | Stack
minimum-add-to-make-parentheses-valid
0
1
Approach:\nwe can use stack to solve this problem:\nThe problem is the same as checking the given set of parentheses are whether valid or not. if the given string parentheses are valid, then our stack will be empty. but if the string input is not a valid parentheses, then there will be some parentheses left in the stac...
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
Using Stacks
minimum-add-to-make-parentheses-valid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Using Stacks
minimum-add-to-make-parentheses-valid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
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 | Stack | Greedy
minimum-add-to-make-parentheses-valid
0
1
# Code\n```\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n stack = []\n for i in s:\n if len(stack) == 0:\n stack.append(i)\n else:\n popp = stack.pop()\n if popp == "(" and i == ")":\n continue\n ...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Easy | Python Solution | Stack | Greedy
minimum-add-to-make-parentheses-valid
0
1
# Code\n```\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n stack = []\n for i in s:\n if len(stack) == 0:\n stack.append(i)\n else:\n popp = stack.pop()\n if popp == "(" and i == ")":\n continue\n ...
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 Intuition Python Single Pass Solution
minimum-add-to-make-parentheses-valid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe number of opening/ brackets to add to make it a valid parentheses will be equal to the number of unbalanced "(" or ")". We can easily determine those by the exact same method by which we validate a string to be valid parentheses or no...
1
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
Easy Intuition Python Single Pass Solution
minimum-add-to-make-parentheses-valid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe number of opening/ brackets to add to make it a valid parentheses will be equal to the number of unbalanced "(" or ")". We can easily determine those by the exact same method by which we validate a string to be valid parentheses or no...
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
simple solution in python using replace
minimum-add-to-make-parentheses-valid
0
1
\n```\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n while "()" in s:\n s=s.replace("()","",1)\n return len(s)\n```
2
A parentheses string is valid if and only if: * It is the empty string, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid strings, or * It can be written as `(A)`, where `A` is a valid string. You are given a parentheses string `s`. In one move, you can insert a parenthesis at...
null
simple solution in python using replace
minimum-add-to-make-parentheses-valid
0
1
\n```\nclass Solution:\n def minAddToMakeValid(self, s: str) -> int:\n while "()" in s:\n s=s.replace("()","",1)\n return len(s)\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
Python3|| Easy solution.
sort-array-by-parity-ii
0
1
# Code\n```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even = []\n odd = []\n lst=[]\n for i in range(len(nums)):\n if nums[i]%2 == 0:\n even.append(nums[i])\n else:\n odd.append(nums[i])\n f...
8
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums =...
null
Python3|| Easy solution.
sort-array-by-parity-ii
0
1
# Code\n```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even = []\n odd = []\n lst=[]\n for i in range(len(nums)):\n if nums[i]%2 == 0:\n even.append(nums[i])\n else:\n odd.append(nums[i])\n f...
8
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
Solution
sort-array-by-parity-ii
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n int i=0;\n int j=1;\n while(i<n && j<n){\n if(nums[i]%2==0)\n i=i+2;\n else if(nums[j]%2==1)\n j=j+2;\n else\n ...
4
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums =...
null
Solution
sort-array-by-parity-ii
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> sortArrayByParityII(vector<int>& nums) {\n int n=nums.size();\n int i=0;\n int j=1;\n while(i<n && j<n){\n if(nums[i]%2==0)\n i=i+2;\n else if(nums[j]%2==1)\n j=j+2;\n else\n ...
4
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
Python3 O(n) || O(1)
sort-array-by-parity-ii
0
1
```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even, odd = 0, 1\n \n while even < len(nums) and odd < len(nums):\n while even < len(nums) and nums[even] % 2 == 0:\n even += 2\n while odd < len(nums) and nums[odd] % 2 != ...
5
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums =...
null
Python3 O(n) || O(1)
sort-array-by-parity-ii
0
1
```\nclass Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n even, odd = 0, 1\n \n while even < len(nums) and odd < len(nums):\n while even < len(nums) and nums[even] % 2 == 0:\n even += 2\n while odd < len(nums) and nums[odd] % 2 != ...
5
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
Solution
3sum-with-multiplicity
1
1
```C++ []\nstatic const int M = 1e9 + 7, N = 101;\n\nclass Solution {\npublic:\n int threeSumMulti(vector<int>& a, int target) {\n long ans = 0, cnt[N]{};\n for (int &x : a) ++cnt[x];\n for (int i = 0; i < N; ++i)\n for (int j = i + 1; j < N; ++j) {\n int k = target - i...
1
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanatio...
null
Solution
3sum-with-multiplicity
1
1
```C++ []\nstatic const int M = 1e9 + 7, N = 101;\n\nclass Solution {\npublic:\n int threeSumMulti(vector<int>& a, int target) {\n long ans = 0, cnt[N]{};\n for (int &x : a) ++cnt[x];\n for (int i = 0; i < N; ++i)\n for (int j = i + 1; j < N; ++j) {\n int k = target - i...
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
[Python] 3Sum Approach with Explanation
3sum-with-multiplicity
0
1
### Introduction\n\nGiven an array of integers `arr`, determine how many tuples `(i, j, k)` exist such that `0 <= i < j < k < len(arr)` and `arr[i] + arr[j] + arr[k] == target`.\n\nThis problem is similar to [15. 3Sum](https://leetcode.com/problems/3sum/), except it differs in one major way: where the similar problem r...
98
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanatio...
null
[Python] 3Sum Approach with Explanation
3sum-with-multiplicity
0
1
### Introduction\n\nGiven an array of integers `arr`, determine how many tuples `(i, j, k)` exist such that `0 <= i < j < k < len(arr)` and `arr[i] + arr[j] + arr[k] == target`.\n\nThis problem is similar to [15. 3Sum](https://leetcode.com/problems/3sum/), except it differs in one major way: where the similar problem r...
98
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, 3 steps, O(N*W)
3sum-with-multiplicity
0
1
# Idea\nThe idea is to keep counting the number of elements we have seen so far and keep `ones` and `twos` counters, which correspond to the number of ways given values can be constructed (as a sum) using one and two array elements respectively. So, we iterate over an array and do the following three steps as a pipelin...
6
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanatio...
null
Python, 3 steps, O(N*W)
3sum-with-multiplicity
0
1
# Idea\nThe idea is to keep counting the number of elements we have seen so far and keep `ones` and `twos` counters, which correspond to the number of ways given values can be constructed (as a sum) using one and two array elements respectively. So, we iterate over an array and do the following three steps as a pipelin...
6
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
minimize-malware-spread
1
1
```C++ []\nclass Solution {\npublic:\n int find_p(vector<int>& ps, int i) {\n return ps[i] == i ? i : ps[i] = find_p(ps, ps[i]); \n }\n void union_p(vector<int>& ps, vector<int>& cs, int i, int j) {\n int pi = find_p(ps, i), pj = find_p(ps, j);\n if (pi != pj) {\n ps[pi] = pj;\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
Solution
minimize-malware-spread
1
1
```C++ []\nclass Solution {\npublic:\n int find_p(vector<int>& ps, int i) {\n return ps[i] == i ? i : ps[i] = find_p(ps, ps[i]); \n }\n void union_p(vector<int>& ps, vector<int>& cs, int i, int j) {\n int pi = find_p(ps, i), pj = find_p(ps, j);\n if (pi != pj) {\n ps[pi] = pj;\n...
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
Solved by using Disjoint Sets
minimize-malware-spread
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given 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 Sets
minimize-malware-spread
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an 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
Easy to understand with step wise explanation 😸😸
minimize-malware-spread
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing BFS/DFS was first thought as Adjacency matrix is given. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo we need to minimize the infection in the connected graph. Only way is to find a connected graph which ...
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
Easy to understand with step wise explanation 😸😸
minimize-malware-spread
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing BFS/DFS was first thought as Adjacency matrix is given. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo we need to minimize the infection in the connected graph. Only way is to find a connected graph 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
Python DFS solution
minimize-malware-spread
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst, some background: a set of connected nodes forms a component. Nodes can be connected either directly via an edge or through other connected nodes.\n\nNow, let\'s assume we can find a component and how many infected nodes it has. A f...
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
Python DFS solution
minimize-malware-spread
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst, some background: a set of connected nodes forms a component. Nodes can be connected either directly via an edge or through other connected nodes.\n\nNow, let\'s assume we can find a component and how many infected nodes it has. A f...
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
Union Find in Py3 beating 97% in time
minimize-malware-spread
0
1
\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n p = [i for i in range(n)]\n def find(i):\n if i!=p[i]:\n p[i] = find(p[i])\n return p[i]\n for i in range(n):\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
Union Find in Py3 beating 97% in time
minimize-malware-spread
0
1
\n# Code\n```\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n p = [i for i in range(n)]\n def find(i):\n if i!=p[i]:\n p[i] = find(p[i])\n return p[i]\n for i in range(n):\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
OMFG!! Beats 100 on both runtime and memory
minimize-malware-spread
0
1
# Intuition\n![WhatsApp Image 2023-07-04 at 22.04.55.jpg](https://assets.leetcode.com/users/images/d559f4fb-69c8-4bd8-a996-6df9009ec37f_1688488515.5098794.jpeg)\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- ...
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
OMFG!! Beats 100 on both runtime and memory
minimize-malware-spread
0
1
# Intuition\n![WhatsApp Image 2023-07-04 at 22.04.55.jpg](https://assets.leetcode.com/users/images/d559f4fb-69c8-4bd8-a996-6df9009ec37f_1688488515.5098794.jpeg)\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- ...
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
long-pressed-name
1
1
```C++ []\nclass Solution {\npublic:\n bool isLongPressedName(string name, string typed) {\n int i=0,j=0;\n while(i< name.length() && j< typed.length()){\n if(name[i]==typed[j]){\n i++;\n j++;\n }\n else{\n if(i>0 &&name[i-1]==typed[j])\n ...
3
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly ...
null
Solution
long-pressed-name
1
1
```C++ []\nclass Solution {\npublic:\n bool isLongPressedName(string name, string typed) {\n int i=0,j=0;\n while(i< name.length() && j< typed.length()){\n if(name[i]==typed[j]){\n i++;\n j++;\n }\n else{\n if(i>0 &&name[i-1]==typed[j])\n ...
3
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **...
null
Python Elegant & Short | One line | itertools.groupby
long-pressed-name
0
1
```\t\nfrom itertools import groupby, zip_longest\n\n\nclass Solution:\n\t"""\n\tTime: O(max(n, m))\n\tMemory: O(1)\n\t"""\n\n\tdef isLongPressedName(self, name: str, typed: str) -> bool:\n\t\tfor (a, a_gr), (b, b_gr) in zip_longest(groupby(name), groupby(typed), fillvalue=(None, None)):\n\t\t\tif a != b or sum(1 for...
4
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly ...
null
Python Elegant & Short | One line | itertools.groupby
long-pressed-name
0
1
```\t\nfrom itertools import groupby, zip_longest\n\n\nclass Solution:\n\t"""\n\tTime: O(max(n, m))\n\tMemory: O(1)\n\t"""\n\n\tdef isLongPressedName(self, name: str, typed: str) -> bool:\n\t\tfor (a, a_gr), (b, b_gr) in zip_longest(groupby(name), groupby(typed), fillvalue=(None, None)):\n\t\t\tif a != b or sum(1 for...
4
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **...
null
✅ [PYTHON] Compress strings then compare!
long-pressed-name
0
1
First I wrote a solution based on various conditions and it produced a good result. But I didn\'t like the way it looked. You can skip it, because the second solution is below and I like it much better.\n# My first solution (Beats 98.86% - skip it):\n```\nclass Solution:\n def isLongPressedName(self, name: str, type...
1
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly ...
null
✅ [PYTHON] Compress strings then compare!
long-pressed-name
0
1
First I wrote a solution based on various conditions and it produced a good result. But I didn\'t like the way it looked. You can skip it, because the second solution is below and I like it much better.\n# My first solution (Beats 98.86% - skip it):\n```\nclass Solution:\n def isLongPressedName(self, name: str, type...
1
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **...
null
Python3 wasy-peasy solution
long-pressed-name
0
1
# Intuition\ntwo pointers\n\n# Approach\nIn this implementation, we are using two pointers i and j to traverse the name and typed strings respectively. We compare the characters at these pointers and move the pointers accordingly.\n\nIf the characters at the current positions are equal, we increment both i and j, and m...
5
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly ...
null
Python3 wasy-peasy solution
long-pressed-name
0
1
# Intuition\ntwo pointers\n\n# Approach\nIn this implementation, we are using two pointers i and j to traverse the name and typed strings respectively. We compare the characters at these pointers and move the pointers accordingly.\n\nIf the characters at the current positions are equal, we increment both i and j, and m...
5
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **...
null
[Python3] 2 pointers
long-pressed-name
0
1
```\nclass Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n ni = 0 # index of name\n ti = 0 # index of typed\n while ni <= len(name) and ti < len(typed):\n if ni < len(name) and typed[ti] == name[ni]:\n ti += 1\n ni +=...
13
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly ...
null
[Python3] 2 pointers
long-pressed-name
0
1
```\nclass Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n ni = 0 # index of name\n ti = 0 # index of typed\n while ni <= len(name) and ti < len(typed):\n if ni < len(name) and typed[ti] == name[ni]:\n ti += 1\n ni +=...
13
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **...
null
Python3 10-line code using 2-pointers
long-pressed-name
0
1
```\nclass Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n i, j, m, n = 0, 0, len(name), len(typed)\n if n < m: return False\n while i < m and j < n:\n if name[i] == typed[j]:\n i += 1\n j += 1\n elif j == 0 or typed[j...
2
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly ...
null
Python3 10-line code using 2-pointers
long-pressed-name
0
1
```\nclass Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n i, j, m, n = 0, 0, len(name), len(typed)\n if n < m: return False\n while i < m and j < n:\n if name[i] == typed[j]:\n i += 1\n j += 1\n elif j == 0 or typed[j...
2
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **...
null
Python One Liner (Actually good, unexplained)
flip-string-to-monotone-increasing
0
1
```\nclass Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n return min(0,*accumulate([[-1,1][int(c)]for c in s]))+s.count(\'0\')\n```
6
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
Python One Liner (Actually good, unexplained)
flip-string-to-monotone-increasing
0
1
```\nclass Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n return min(0,*accumulate([[-1,1][int(c)]for c in s]))+s.count(\'0\')\n```
6
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
SIMPLE PYTHON SOLUTION
flip-string-to-monotone-increasing
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $...
5
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
SIMPLE PYTHON SOLUTION
flip-string-to-monotone-increasing
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $...
5
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
Explanation in laymens terms [Easy to understand]
flip-string-to-monotone-increasing
1
1
# Intuition\nBasically the idea is that once we reach a \'1\' we will start flipping \'0\'s to 1s until the count for zeros is less than ones but as an when the count for zero increases more than that of ones as we are logically supposed to flip the 1s instead of zeroes. \n\nThe way we will be able to acheive this is b...
2
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
Explanation in laymens terms [Easy to understand]
flip-string-to-monotone-increasing
1
1
# Intuition\nBasically the idea is that once we reach a \'1\' we will start flipping \'0\'s to 1s until the count for zeros is less than ones but as an when the count for zero increases more than that of ones as we are logically supposed to flip the 1s instead of zeroes. \n\nThe way we will be able to acheive this is b...
2
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
🐍 Python One Line 🏌️‍♂️
flip-string-to-monotone-increasing
0
1
# Code\n```\nfrom itertools import accumulate\nfrom functools import reduce\n\nclass Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n return reduce(lambda acc, curr: acc if int(curr[0]) else min(curr[1], acc + 1), zip(s, accumulate(map(int, s))), 0)\n```
2
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
🐍 Python One Line 🏌️‍♂️
flip-string-to-monotone-increasing
0
1
# Code\n```\nfrom itertools import accumulate\nfrom functools import reduce\n\nclass Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n return reduce(lambda acc, curr: acc if int(curr[0]) else min(curr[1], acc + 1), zip(s, accumulate(map(int, s))), 0)\n```
2
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
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 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