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
Sliding Window,PrefixSum Approach
count-number-of-nice-subarrays
0
1
```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n prefixsum=0\n dic=defaultdict(int)\n dic[0]=1\n ans=0\n for i in nums:\n if i%2==1:\n prefixsum+=1\n ans+=dic[prefixsum-k]\n dic[prefixsum]+=1\n ...
6
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an...
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
Sliding Window,PrefixSum Approach
count-number-of-nice-subarrays
0
1
```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n prefixsum=0\n dic=defaultdict(int)\n dic[0]=1\n ans=0\n for i in nums:\n if i%2==1:\n prefixsum+=1\n ans+=dic[prefixsum-k]\n dic[prefixsum]+=1\n ...
6
You are given a string `s`. Reorder the string using the following algorithm: 1. Pick the **smallest** character from `s` and **append** it to the result. 2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. 3. Repeat step 2 until you cannot ...
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
USING QUEUE || python Explained
count-number-of-nice-subarrays
0
1
# Intuition\r\nIn your queue store the index of all odd elements.\r\nNow acc to question each subarray must have only k odd elements so we have to design our window limits such that there are only k odd\r\n**So what must be the boundaries?**\r\n`window start = curr Index`\r\n`atleast window End = min k odd from window ...
1
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an...
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
USING QUEUE || python Explained
count-number-of-nice-subarrays
0
1
# Intuition\r\nIn your queue store the index of all odd elements.\r\nNow acc to question each subarray must have only k odd elements so we have to design our window limits such that there are only k odd\r\n**So what must be the boundaries?**\r\n`window start = curr Index`\r\n`atleast window End = min k odd from window ...
1
You are given a string `s`. Reorder the string using the following algorithm: 1. Pick the **smallest** character from `s` and **append** it to the result. 2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. 3. Repeat step 2 until you cannot ...
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
Python - Two pointer
count-number-of-nice-subarrays
0
1
```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n right ,left = 0,0\n ans = 0 \n odd_cnt = 0\n ans = 0\n cur_sub_cnt = 0\n for right in range(len(nums)):\n \n if nums[right]%2 == 1:\n odd_cnt += 1\n ...
36
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an...
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
Python - Two pointer
count-number-of-nice-subarrays
0
1
```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n right ,left = 0,0\n ans = 0 \n odd_cnt = 0\n ans = 0\n cur_sub_cnt = 0\n for right in range(len(nums)):\n \n if nums[right]%2 == 1:\n odd_cnt += 1\n ...
36
You are given a string `s`. Reorder the string using the following algorithm: 1. Pick the **smallest** character from `s` and **append** it to the result. 2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. 3. Repeat step 2 until you cannot ...
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
Easy sliding widow | Beats 100 %
count-number-of-nice-subarrays
0
1
\r\n# Code\r\n```\r\nclass Solution:\r\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\r\n odd_count = 0\r\n res = 0\r\n i = 0\r\n count = 0\r\n for ele in nums:\r\n if ele % 2 == 1:\r\n odd_count += 1\r\n count = 0\r\n\r\n ...
1
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an...
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
Easy sliding widow | Beats 100 %
count-number-of-nice-subarrays
0
1
\r\n# Code\r\n```\r\nclass Solution:\r\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\r\n odd_count = 0\r\n res = 0\r\n i = 0\r\n count = 0\r\n for ele in nums:\r\n if ele % 2 == 1:\r\n odd_count += 1\r\n count = 0\r\n\r\n ...
1
You are given a string `s`. Reorder the string using the following algorithm: 1. Pick the **smallest** character from `s` and **append** it to the result. 2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. 3. Repeat step 2 until you cannot ...
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
easy peasy python solution with explanation
count-number-of-nice-subarrays
0
1
\t# Just keep count of the current odd number.\n\t# Look in the dictionary if we can find (currendOds - k), \n\t# if it exisits that means I can get an subarray with k odds.\n\t# Also keep count of number of different types of odds too,\n\t# because for K =1 , [2,2,1] is a valid list, so does, [2,1] and [1].\n\t\n ...
31
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an...
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
easy peasy python solution with explanation
count-number-of-nice-subarrays
0
1
\t# Just keep count of the current odd number.\n\t# Look in the dictionary if we can find (currendOds - k), \n\t# if it exisits that means I can get an subarray with k odds.\n\t# Also keep count of number of different types of odds too,\n\t# because for K =1 , [2,2,1] is a valid list, so does, [2,1] and [1].\n\t\n ...
31
You are given a string `s`. Reorder the string using the following algorithm: 1. Pick the **smallest** character from `s` and **append** it to the result. 2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. 3. Repeat step 2 until you cannot ...
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
Python | Sliding window with comments for explanation
count-number-of-nice-subarrays
0
1
```python\nclass Solution:\n\tdef numberOfSubarrays(self, arr, k):\n\t\t# the difference gives the exact K elements count\n\t\treturn self.atMostKElements(arr, k) - self.atMostKElements(arr, k-1)\n\n\tdef atMostKElements(self, arr, k):\n\t\ti, j = 0, 0\n\t\tres, curr_window_count = 0, 0\n\t\tfor j in range(len(arr)):\n...
1
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an...
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
Python | Sliding window with comments for explanation
count-number-of-nice-subarrays
0
1
```python\nclass Solution:\n\tdef numberOfSubarrays(self, arr, k):\n\t\t# the difference gives the exact K elements count\n\t\treturn self.atMostKElements(arr, k) - self.atMostKElements(arr, k-1)\n\n\tdef atMostKElements(self, arr, k):\n\t\ti, j = 0, 0\n\t\tres, curr_window_count = 0, 0\n\t\tfor j in range(len(arr)):\n...
1
You are given a string `s`. Reorder the string using the following algorithm: 1. Pick the **smallest** character from `s` and **append** it to the result. 2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it. 3. Repeat step 2 until you cannot ...
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
Simple solution with Stack in Python3 / TypeScript
minimum-remove-to-make-valid-parentheses
0
1
# Intuition\nHere we have:\n- a string `s`\n- our goal is to **remove** minimum count of parentheses to make string **valid**\n\nAccording to the description a string is **valid**, if it meets conditions such that for **each open par** exists **closed par**.\n\nTo be short: for each par we need to store an index into `...
1
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which c...
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
Simple solution with Stack in Python3 / TypeScript
minimum-remove-to-make-valid-parentheses
0
1
# Intuition\nHere we have:\n- a string `s`\n- our goal is to **remove** minimum count of parentheses to make string **valid**\n\nAccording to the description a string is **valid**, if it meets conditions such that for **each open par** exists **closed par**.\n\nTo be short: for each par we need to store an index into `...
1
Implement a SnapshotArray that supports the following interface:
Use a list of lists, adding both the element and the snap_id to each index.
Super simple Python solution with explanation. Faster than 100%, Memory Usage less than 100%
minimum-remove-to-make-valid-parentheses
0
1
1. Convert string to list, because String is an immutable data structure in Python and it\'s much easier and memory-efficient to deal with a list for this task.\n2. Iterate through list\n3. Keep track of indices with open parentheses in the stack. In other words, when we come across open parenthesis we add an index to ...
483
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which c...
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
Super simple Python solution with explanation. Faster than 100%, Memory Usage less than 100%
minimum-remove-to-make-valid-parentheses
0
1
1. Convert string to list, because String is an immutable data structure in Python and it\'s much easier and memory-efficient to deal with a list for this task.\n2. Iterate through list\n3. Keep track of indices with open parentheses in the stack. In other words, when we come across open parenthesis we add an index to ...
483
Implement a SnapshotArray that supports the following interface:
Use a list of lists, adding both the element and the snap_id to each index.
Python || 95.62% Faster || Stack || Easy
minimum-remove-to-make-valid-parentheses
0
1
```\nclass Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n s=list(s)\n st=[]\n for i in range(len(s)):\n if s[i]==\'(\':\n st.append(i)\n elif s[i]==\')\':\n if st:\n st.pop()\n else:\n ...
1
Given the string `s`, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times. **Example 1:** **Input:** s = "eleetminicoworoep " **Output:** 13 **Explanation:** The longest substring is "leetminicowor " which c...
Each prefix of a balanced parentheses has a number of open parentheses greater or equal than closed parentheses, similar idea with each suffix. Check the array from left to right, remove characters that do not meet the property mentioned above, same idea in backward way.
Python || 95.62% Faster || Stack || Easy
minimum-remove-to-make-valid-parentheses
0
1
```\nclass Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n s=list(s)\n st=[]\n for i in range(len(s)):\n if s[i]==\'(\':\n st.append(i)\n elif s[i]==\')\':\n if st:\n st.pop()\n else:\n ...
1
Implement a SnapshotArray that supports the following interface:
Use a list of lists, adding both the element and the snap_id to each index.
Hand Written Easy Explanation with Bézout's Lemma
check-if-it-is-a-good-array
0
1
\n![image.png](https://assets.leetcode.com/users/images/71d340ad-c7ae-4256-940b-799a2ffd6ae5_1681532564.9413595.png)\n![image.png](https://assets.leetcode.com/users/images/4a52e4c5-59ed-4bed-9e2d-557a9669e1ae_1681532580.7018669.png)\n\n# Code\n```\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n ...
2
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwi...
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
Hand Written Easy Explanation with Bézout's Lemma
check-if-it-is-a-good-array
0
1
\n![image.png](https://assets.leetcode.com/users/images/71d340ad-c7ae-4256-940b-799a2ffd6ae5_1681532564.9413595.png)\n![image.png](https://assets.leetcode.com/users/images/4a52e4c5-59ed-4bed-9e2d-557a9669e1ae_1681532580.7018669.png)\n\n# Code\n```\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n ...
2
You are given the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction f...
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
Simple setwise coprimality check
check-if-it-is-a-good-array
0
1
# Intuition\nWe need to determine if the numbers are setwise coprime.\n\n# Code\n```\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n return functools.reduce(math.gcd, nums) == 1\n```
0
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwi...
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
Simple setwise coprimality check
check-if-it-is-a-good-array
0
1
# Intuition\nWe need to determine if the numbers are setwise coprime.\n\n# Code\n```\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n return functools.reduce(math.gcd, nums) == 1\n```
0
You are given the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction f...
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
0 Line Solution
check-if-it-is-a-good-array
0
1
# Description\nThe entire code is ran inline for the Solution\'s Function leading to a 2 line solution (0 added lines).\n\n# Code\n```\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool: return bool(functools.reduce(math.gcd, nums) == 1)\n```
0
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwi...
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
0 Line Solution
check-if-it-is-a-good-array
0
1
# Description\nThe entire code is ran inline for the Solution\'s Function leading to a 2 line solution (0 added lines).\n\n# Code\n```\nclass Solution:\n def isGoodArray(self, nums: List[int]) -> bool: return bool(functools.reduce(math.gcd, nums) == 1)\n```
0
You are given the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction f...
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
my own solution
check-if-it-is-a-good-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwi...
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
my own solution
check-if-it-is-a-good-array
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 the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction f...
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
1250. Check If It Is a Good Array
check-if-it-is-a-good-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwi...
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
1250. Check If It Is a Good Array
check-if-it-is-a-good-array
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 the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction f...
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
Simple Approach Using GCD property
check-if-it-is-a-good-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom gcd property we know , ax + by = gcd(a,b) , if a and b are coprime then gcd(a,b) == 1.\nNow in this arry we need to find a subset whose gcd is equal to 1 , and it is always optimal to check the gcd of whole array , if we have the gc...
0
Given an array `nums` of positive integers. Your task is to select some subset of `nums`, multiply each element by an integer and add all these numbers. The array is said to be **good** if you can obtain a sum of `1` from the array by any possible subset and multiplicand. Return `True` if the array is **good** otherwi...
Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise
Simple Approach Using GCD property
check-if-it-is-a-good-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom gcd property we know , ax + by = gcd(a,b) , if a and b are coprime then gcd(a,b) == 1.\nNow in this arry we need to find a subset whose gcd is equal to 1 , and it is always optimal to check the gcd of whole array , if we have the gc...
0
You are given the `root` of a binary tree. A ZigZag path for a binary tree is defined as follow: * Choose **any** node in the binary tree and a direction (right or left). * If the current direction is right, move to the right child of the current node; otherwise, move to the left child. * Change the direction f...
Eq. ax+by=1 has solution x, y if gcd(a,b) = 1. Can you generalize the formula?. Check Bézout's lemma.
97% Runtime 80% Memory The simpliest solution
cells-with-odd-values-in-a-matrix
0
1
![image.png](https://assets.leetcode.com/users/images/8abde018-70dc-4abe-a84f-e361a35c51bb_1696240509.7567608.png)\n\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m+n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ncla...
0
There is an `m x n` matrix that is initialized to all `0`'s. There is also a 2D array `indices` where each `indices[i] = [ri, ci]` represents a **0-indexed location** to perform some increment operations on the matrix. For each location `indices[i]`, do **both** of the following: 1. Increment **all** the cells on ro...
How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.
Python | O(n*m+indices) | Easy | Hashing
cells-with-odd-values-in-a-matrix
0
1
```\nclass Solution:\n def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:\n dict_ = {} #List to keep track of total increase row and column wise\n dict_[\'col\'] = [0]*n\n dict_[\'row\'] = [0]*m\n for idx in range(len(indices)):\n dict_[\'row\'][indices[idx][0...
0
There is an `m x n` matrix that is initialized to all `0`'s. There is also a 2D array `indices` where each `indices[i] = [ri, ci]` represents a **0-indexed location** to perform some increment operations on the matrix. For each location `indices[i]`, do **both** of the following: 1. Increment **all** the cells on ro...
How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.
Simple Python Greedy O(n) Solution
reconstruct-a-2-row-binary-matrix
0
1
# Code\n```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n \n n = len(colsum)\n matrix = [[0] * n for _ in range(2)]\n if upper + lower != sum(colsum): return []\n\n for i in range(n):\n if colsum[i] == 2:\...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Simple Python Greedy O(n) Solution
reconstruct-a-2-row-binary-matrix
0
1
# Code\n```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n \n n = len(colsum)\n matrix = [[0] * n for _ in range(2)]\n if upper + lower != sum(colsum): return []\n\n for i in range(n):\n if colsum[i] == 2:\...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Simple and clear python3 solutions | 524 ms - faster than 94.4% solutions
reconstruct-a-2-row-binary-matrix
0
1
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ (only for answer)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Simple and clear python3 solutions | 524 ms - faster than 94.4% solutions
reconstruct-a-2-row-binary-matrix
0
1
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ (only for answer)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Python Solution
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSome tricky edge cases should to be considered carefully.\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 complexit...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Python Solution
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSome tricky edge cases should to be considered carefully.\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 complexit...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Solution
reconstruct-a-2-row-binary-matrix
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& c) {\n vector<vector<int>> res(2,vector<int>(c.size(),0));\n int count=0;\n for(auto &el:c) count+=el==2;\n for(int i=0;i<c.size();i++){\n if(c[i]==2){\n ...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Solution
reconstruct-a-2-row-binary-matrix
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& c) {\n vector<vector<int>> res(2,vector<int>(c.size(),0));\n int count=0;\n for(auto &el:c) count+=el==2;\n for(int i=0;i<c.size();i++){\n if(c[i]==2){\n ...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Runtime 667 ms Beats 83.48% Memory 26.7 MB Beats 20.87%
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Runtime 667 ms Beats 83.48% Memory 26.7 MB Beats 20.87%
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Clean | Concise | Fast | 4 Lines | Python Solution
reconstruct-a-2-row-binary-matrix
0
1
# Code\n```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n n = len(colsum)\n upper_list = [0 for _ in range(n)]\n lower_list = [0 for _ in range(n)]\n \n for i, v in enumerate(colsum):\n if v == 1:\n ...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Clean | Concise | Fast | 4 Lines | Python Solution
reconstruct-a-2-row-binary-matrix
0
1
# Code\n```\nclass Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n n = len(colsum)\n upper_list = [0 for _ in range(n)]\n lower_list = [0 for _ in range(n)]\n \n for i, v in enumerate(colsum):\n if v == 1:\n ...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Simple 3 Case Iterator on Columns
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\nThe fact that this is binary helps us.\n\n# Approach\nHandle each column, and split it into the 0, 1, 2 bucket.\n## Case: 0\nFor 0, it\'s easy. Neither row has an entry, we can proceed.\n\n## Case: 2 (we\'ll come back to 1)\nFor 2, we simply check if we have already reached our limits, and exit with the "n...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Simple 3 Case Iterator on Columns
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\nThe fact that this is binary helps us.\n\n# Approach\nHandle each column, and split it into the 0, 1, 2 bucket.\n## Case: 0\nFor 0, it\'s easy. Neither row has an entry, we can proceed.\n\n## Case: 2 (we\'ll come back to 1)\nFor 2, we simply check if we have already reached our limits, and exit with the "n...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Python easy solution with explanation O(n)
reconstruct-a-2-row-binary-matrix
0
1
# Approach\n\n1. Create required 2D matrix filled with 0\'s\n2. \'top\' and \'bot\' are counts of 1\'s in top and bottom rows. They are initialised as a number of 2\'s in colsum.\n3. Go over colsum: If val == 2: make top and bottom values 1. If val == 1 make either top or bottom value 1 (checking if limit is not excee...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Python easy solution with explanation O(n)
reconstruct-a-2-row-binary-matrix
0
1
# Approach\n\n1. Create required 2D matrix filled with 0\'s\n2. \'top\' and \'bot\' are counts of 1\'s in top and bottom rows. They are initialised as a number of 2\'s in colsum.\n3. Go over colsum: If val == 2: make top and bottom values 1. If val == 1 make either top or bottom value 1 (checking if limit is not excee...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
O(n) python solution
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem statement is to reconstruct a matrix given the upper and lower row sums and the sum of each column. The idea is to start with the columns that have a sum of 2 and place one 1 in the upper row and one 1 in the lower row. Then, ...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
O(n) python solution
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem statement is to reconstruct a matrix given the upper and lower row sums and the sum of each column. The idea is to start with the columns that have a sum of 2 and place one 1 in the upper row and one 1 in the lower row. Then, ...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Simple to understand Python O(n) Solution
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\nFirst I place all the "forced entries" into the solution array. These "forced entries" are when the colsum is either 0 or 2. If the colsum is 0, then clearly both the upper and lower values must be 0. If colsum is 2, then cleary both the upper and lower values must be 1. As such, these values are forced. I...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Simple to understand Python O(n) Solution
reconstruct-a-2-row-binary-matrix
0
1
# Intuition\nFirst I place all the "forced entries" into the solution array. These "forced entries" are when the colsum is either 0 or 2. If the colsum is 0, then clearly both the upper and lower values must be 0. If colsum is 2, then cleary both the upper and lower values must be 1. As such, these values are forced. I...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Easy to Understand
reconstruct-a-2-row-binary-matrix
0
1
\tclass Solution:\n\t\tdef reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n\t\t\tbm = [[0 for _ in range(len(colsum))] for i in range(2)]\n\t\t\tfor i in range(len(colsum)):\n\t\t\t\tif colsum[i]==2:\n\t\t\t\t\tcolsum[i]=0\n\t\t\t\t\tupper-=1\n\t\t\t\t\tlower-=1\n\t\t\t\t\tbm[0][...
0
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of ele...
Use a data structure to store all values of each diagonal. How to index the data structure with the id of the diagonal? All cells in the same diagonal (i,j) have the same difference so we can get the diagonal of a cell using the difference i-j.
Easy to Understand
reconstruct-a-2-row-binary-matrix
0
1
\tclass Solution:\n\t\tdef reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n\t\t\tbm = [[0 for _ in range(len(colsum))] for i in range(2)]\n\t\t\tfor i in range(len(colsum)):\n\t\t\t\tif colsum[i]==2:\n\t\t\t\t\tcolsum[i]=0\n\t\t\t\t\tupper-=1\n\t\t\t\t\tlower-=1\n\t\t\t\t\tbm[0][...
0
Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree. The `cloned` tree is a **copy of** the `original` tree. Return _a reference to the same node_ in the `cloned` tree. **Note** that you are **not allowed** to change any of the two trees or the `target` node a...
You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row.
Simple dfs solution!!
number-of-closed-islands
0
1
# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n vis=defaultdict(lambda:False)\n n=len(grid)\n m=len(grid[0])\n \'\'\'\n \'\'\'\n def dfs(x,y):\n vis[(x,y)]=True\n isedge=True\n for i,j in ((x+1,y),(x-1,y...
2
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Simple dfs solution!!
number-of-closed-islands
0
1
# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n vis=defaultdict(lambda:False)\n n=len(grid)\n m=len(grid[0])\n \'\'\'\n \'\'\'\n def dfs(x,y):\n vis[(x,y)]=True\n isedge=True\n for i,j in ((x+1,y),(x-1,y...
2
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Easy & Clear Solution Python 3 DFS
number-of-closed-islands
0
1
\n# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def dfs(i,j,newval):\n if grid[i][j]==0:\n grid[i][j]=2\n if i<len(grid)-1 : dfs(i+1,j,newval)\n if i >0 : dfs(i-1,j,newval)\n if j<len(grid[0])-1 : d...
5
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Easy & Clear Solution Python 3 DFS
number-of-closed-islands
0
1
\n# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def dfs(i,j,newval):\n if grid[i][j]==0:\n grid[i][j]=2\n if i<len(grid)-1 : dfs(i+1,j,newval)\n if i >0 : dfs(i-1,j,newval)\n if j<len(grid[0])-1 : d...
5
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Super easy edge-in dfs // Beats 97%
number-of-closed-islands
0
1
# Intuition\nIf the island touches the edge of the board, it will not be a closed island. So, if we find all those islands by starting from the outside-in, the number of remaining islands will be the answer!\n\n# Approach\nGo around the outside and perform dfs for all the 0s found and replace with 2. Then go through th...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Super easy edge-in dfs // Beats 97%
number-of-closed-islands
0
1
# Intuition\nIf the island touches the edge of the board, it will not be a closed island. So, if we find all those islands by starting from the outside-in, the number of remaining islands will be the answer!\n\n# Approach\nGo around the outside and perform dfs for all the 0s found and replace with 2. Then go through th...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Beats 100% runtime. Easy to understand
number-of-closed-islands
0
1
![\u0417\u043D\u0456\u043C\u043E\u043A \u0435\u043A\u0440\u0430\u043D\u0430 2023-09-18 231531.png](https://assets.leetcode.com/users/images/06b3c647-36ae-4f77-ae84-4ab4ad956e05_1695071754.0780966.png)\n\nhttps://leetcode.com/problems/number-of-closed-islands/submissions/1052991341/\n\n# Intuition\nAt first we need to e...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Beats 100% runtime. Easy to understand
number-of-closed-islands
0
1
![\u0417\u043D\u0456\u043C\u043E\u043A \u0435\u043A\u0440\u0430\u043D\u0430 2023-09-18 231531.png](https://assets.leetcode.com/users/images/06b3c647-36ae-4f77-ae84-4ab4ad956e05_1695071754.0780966.png)\n\nhttps://leetcode.com/problems/number-of-closed-islands/submissions/1052991341/\n\n# Intuition\nAt first we need to e...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Python DFS O(n) code for reference
number-of-closed-islands
0
1
```\n1. Mark all the connected 0\'s as 1\'s, and see if we can reach out of bounds. \n if we can then return False, since we shouldn\'t count it. \n2. If A is True , then in (A or B or C ) B and C will not be checked\n3. If A is False , then in (A and B and C ) B and C will not be checked \n\n```\n\n```\nclass Soluti...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Python DFS O(n) code for reference
number-of-closed-islands
0
1
```\n1. Mark all the connected 0\'s as 1\'s, and see if we can reach out of bounds. \n if we can then return False, since we shouldn\'t count it. \n2. If A is True , then in (A or B or C ) B and C will not be checked\n3. If A is False , then in (A and B and C ) B and C will not be checked \n\n```\n\n```\nclass Soluti...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Easy and Simple approach || Python|| Beginner
number-of-closed-islands
0
1
You can use vis and dic or instead make the element we are visiting 1 as we don\'t care about it any further.\n# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n dic={}\n vis=[]\n def fun(i,j):\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]):\n ...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Easy and Simple approach || Python|| Beginner
number-of-closed-islands
0
1
You can use vis and dic or instead make the element we are visiting 1 as we don\'t care about it any further.\n# Code\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n dic={}\n vis=[]\n def fun(i,j):\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]):\n ...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Python O(m * n) Time Solution - Line By Line Explanation and Comments - Thought Process Explained
number-of-closed-islands
0
1
# Intuition\nSince an island can only be enclosed if there are water along all the 4 sides. The reverse is also true - An island is not enclosed if any of the cells touches the boundary.\n\nGoing by this logic we need to find all the cells that are 4-directionally connected and if any of those cells touch the boundry, ...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Python O(m * n) Time Solution - Line By Line Explanation and Comments - Thought Process Explained
number-of-closed-islands
0
1
# Intuition\nSince an island can only be enclosed if there are water along all the 4 sides. The reverse is also true - An island is not enclosed if any of the cells touches the boundary.\n\nGoing by this logic we need to find all the cells that are 4-directionally connected and if any of those cells touch the boundry, ...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Python Elegant & Short | DFS
number-of-closed-islands
0
1
# Complexity\n- Time complexity: $$O(n*m)$$\n- Space complexity: $$O(n*m)$$\n\n# Code\n```\nclass Solution:\n LAND = 0\n WATER = 1\n\n def closedIsland(self, grid: List[List[int]]) -> int:\n n, m = len(grid), len(grid[0])\n\n for row in range(n):\n self.water_island(row, 0, grid)\n...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Python Elegant & Short | DFS
number-of-closed-islands
0
1
# Complexity\n- Time complexity: $$O(n*m)$$\n- Space complexity: $$O(n*m)$$\n\n# Code\n```\nclass Solution:\n LAND = 0\n WATER = 1\n\n def closedIsland(self, grid: List[List[int]]) -> int:\n n, m = len(grid), len(grid[0])\n\n for row in range(n):\n self.water_island(row, 0, grid)\n...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Python - BFS
number-of-closed-islands
0
1
\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def is_closed(pos):\n if grid[pos[0]][pos[1]]:\n return 0\n stack = [pos]\n is_closed_state = 1\n while stack:\n i, j = stack.pop()\n grid[i...
1
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.` Return the number of _closed islands_. **Example 1:** **Input:** grid = \[\[1,1,1,1,1,1,1,0\],...
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
Python - BFS
number-of-closed-islands
0
1
\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def is_closed(pos):\n if grid[pos[0]][pos[1]]:\n return 0\n stack = [pos]\n is_closed_state = 1\n while stack:\n i, j = stack.pop()\n grid[i...
1
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:*...
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Backtrack Code and 9 Liner Code Explained
maximum-score-words-formed-by-letters
0
1
# Explanation:\n```\n/*\n\nwe will check for all words (from 0 to n-1)\nfor every Index we have 2 choises\n --can we consider our current index\n --> if we consider to choose current index we need\n to update letters and check for next index\n --should we skip and check for next\n ...
1
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
Backtrack Code and 9 Liner Code Explained
maximum-score-words-formed-by-letters
0
1
# Explanation:\n```\n/*\n\nwe will check for all words (from 0 to n-1)\nfor every Index we have 2 choises\n --can we consider our current index\n --> if we consider to choose current index we need\n to update letters and check for next index\n --should we skip and check for next\n ...
1
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max...
Note that words.length is small. This means you can iterate over every subset of words (2^N).
Python | Short & Easy 6 lines | Counter
maximum-score-words-formed-by-letters
0
1
# Code\n```\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n \n def bckt(i, counts):\n if i == len(words): return 0\n word = Counter(words[i])\n if word == word & counts:\n curr = sum([score[ord(...
2
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
Python | Short & Easy 6 lines | Counter
maximum-score-words-formed-by-letters
0
1
# Code\n```\nclass Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n \n def bckt(i, counts):\n if i == len(words): return 0\n word = Counter(words[i])\n if word == word & counts:\n curr = sum([score[ord(...
2
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max...
Note that words.length is small. This means you can iterate over every subset of words (2^N).
Solved using Python Counters
maximum-score-words-formed-by-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the hint suggests, there are few enough ```words``` that we can exhaustively enumerate its possible subsets, scoring each and keeping track of the maximum score. This implies that we will calculate attributes of each one of the ```wor...
1
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
Solved using Python Counters
maximum-score-words-formed-by-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the hint suggests, there are few enough ```words``` that we can exhaustively enumerate its possible subsets, scoring each and keeping track of the maximum score. This implies that we will calculate attributes of each one of the ```wor...
1
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max...
Note that words.length is small. This means you can iterate over every subset of words (2^N).
Python solution Beats 98%. Commented code w/ explanation
maximum-score-words-formed-by-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is to use a backtracking approach to solve this problem. We can check all possible combinations of words and check if they can be made with the given letters and what the score would be.\n# Approach\n<!-- Describe your ap...
3
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
Python solution Beats 98%. Commented code w/ explanation
maximum-score-words-formed-by-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is to use a backtracking approach to solve this problem. We can check all possible combinations of words and check if they can be made with the given letters and what the score would be.\n# Approach\n<!-- Describe your ap...
3
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max...
Note that words.length is small. This means you can iterate over every subset of words (2^N).
✅ || easiest solution to understand ||100% runtime (32 ms)|| python || Explanation and comments ||
maximum-score-words-formed-by-letters
0
1
\n \n \n \n # This problem is quite similiar to classic dp problems\n # where we have two options \n # 1. = choose that word if possible ( if it is following all conditions ) and go forward \n # 2. = If not possible to choose just go forward\n \n # return maximum...
9
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
✅ || easiest solution to understand ||100% runtime (32 ms)|| python || Explanation and comments ||
maximum-score-words-formed-by-letters
0
1
\n \n \n \n # This problem is quite similiar to classic dp problems\n # where we have two options \n # 1. = choose that word if possible ( if it is following all conditions ) and go forward \n # 2. = If not possible to choose just go forward\n \n # return maximum...
9
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max...
Note that words.length is small. This means you can iterate over every subset of words (2^N).
75% Tc and 78% Sc easy python solution
maximum-score-words-formed-by-letters
0
1
```\ndef maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n\tdef solve(i, d):\n\t\tif(i == len(words)): return 0\n\t\tt = solve(i+1, d)\n\t\tcurr_count = Counter(words[i])\n\t\tfor c in curr_count:\n\t\t\tif(c not in d or curr_count[c] > d[c]):\n\t\t\t\treturn t\n\t\tnew_d = d.copy()\...
1
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only...
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[...
75% Tc and 78% Sc easy python solution
maximum-score-words-formed-by-letters
0
1
```\ndef maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n\tdef solve(i, d):\n\t\tif(i == len(words)): return 0\n\t\tt = solve(i+1, d)\n\t\tcurr_count = Counter(words[i])\n\t\tfor c in curr_count:\n\t\t\tif(c not in d or curr_count[c] > d[c]):\n\t\t\t\treturn t\n\t\tnew_d = d.copy()\...
1
Design a stack that supports increment operations on its elements. Implement the `CustomStack` class: * `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack. * `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max...
Note that words.length is small. This means you can iterate over every subset of words (2^N).
Very Simple Solution
shift-2d-grid
1
1
```\n// Please upvote if you like my solution :)\nvoid reverse(vector<int> &nums,int start,int end){\n for(int i=start,j=end;i<j;i++,j--){\n swap(nums[i],nums[j]);\n }\n }\n vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {\n int ro = grid.size();\n int col =...
14
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after...
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Very Simple Solution
shift-2d-grid
1
1
```\n// Please upvote if you like my solution :)\nvoid reverse(vector<int> &nums,int start,int end){\n for(int i=start,j=end;i<j;i++,j--){\n swap(nums[i],nums[j]);\n }\n }\n vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {\n int ro = grid.size();\n int col =...
14
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with...
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
Python3: 2 simple approaches with explanations (by creating a vector)
shift-2d-grid
0
1
# **Algorithm:**\n1) put the matrix row by row to a vector.\n2) rotate the vector k times.\n3) put the vector to the matrix back the same way.\n\nThe **second step** is the same as problem [#189 (Rotate an Array)](https://leetcode.com/problems/rotate-array/), and can be solved in many ways, but here we consider **tw...
28
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after...
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Python3: 2 simple approaches with explanations (by creating a vector)
shift-2d-grid
0
1
# **Algorithm:**\n1) put the matrix row by row to a vector.\n2) rotate the vector k times.\n3) put the vector to the matrix back the same way.\n\nThe **second step** is the same as problem [#189 (Rotate an Array)](https://leetcode.com/problems/rotate-array/), and can be solved in many ways, but here we consider **tw...
28
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with...
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
Beats 99.43% #python3
shift-2d-grid
0
1
# Approach\nFirst of all accessing each list of grid through index, popping the last element and inserting it to the starting of next list. \n\nFinally, accessing the last list popping the last element and inserting it to the first list. \n\n\n# Code\n```\nclass Solution:\n def shiftGrid(self, grid: List[List[int]],...
1
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after...
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Beats 99.43% #python3
shift-2d-grid
0
1
# Approach\nFirst of all accessing each list of grid through index, popping the last element and inserting it to the starting of next list. \n\nFinally, accessing the last list popping the last element and inserting it to the first list. \n\n\n# Code\n```\nclass Solution:\n def shiftGrid(self, grid: List[List[int]],...
1
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with...
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
⭐ Just Flatten and Rotate the Array
shift-2d-grid
0
1
**OBSERVATION:**\nIf we trace the path of any number/index as we do the operation multiple times we find that the number is merely traversing the matrix row-wise. Take 1 for example and look at its path.\n\n1. This gives us an idea to flatten out the array and rotate it k times to get the final matrix in Row Major Orde...
7
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after...
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
⭐ Just Flatten and Rotate the Array
shift-2d-grid
0
1
**OBSERVATION:**\nIf we trace the path of any number/index as we do the operation multiple times we find that the number is merely traversing the matrix row-wise. Take 1 for example and look at its path.\n\n1. This gives us an idea to flatten out the array and rotate it k times to get the final matrix in Row Major Orde...
7
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with...
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
✅✅✅ python solution using simple methods | just 8 lines
shift-2d-grid
0
1
# Code\n```\nclass Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n n, m = len(grid), len(grid[0])\n k%=n*m\n new_grid = [[False for j in range(m)] for i in range(n)]\n for i in range(n):\n for j in range(m):\n i0, j0 = ((i*m+j...
4
Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times. In one shift operation: * Element at `grid[i][j]` moves to `grid[i][j + 1]`. * Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`. * Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`. Return the _2D grid_ after...
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
✅✅✅ python solution using simple methods | just 8 lines
shift-2d-grid
0
1
# Code\n```\nclass Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n n, m = len(grid), len(grid[0])\n k%=n*m\n new_grid = [[False for j in range(m)] for i in range(n)]\n for i in range(n):\n for j in range(m):\n i0, j0 = ((i*m+j...
4
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with...
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
Python Special Way for find() without HashSet O(1) Space O(logn) Time
find-elements-in-a-contaminated-binary-tree
0
1
It\'s obvious to use `BFS` for the initial part. However, a lot of people use HashSet(`set()` in python) to pre-store all the values in the initial part, which may cause MLE when the values are huge. There is a special way to implement `find()` that costs O(1) in space and O(logn) in time. \n\nFirstly, let\'s see what...
131
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode...
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
Simple solution with Depth-First Search + HashSet in Python3
find-elements-in-a-contaminated-binary-tree
0
1
# Intuition\nThe problem description is the following:\n- there\'s a **Binary Tree**, all of its values equal to `-1`\n- our goal is to **recover** all nodes by changing values according to the schema\n\n```py\n# Example\ntree = TreeNode(-1, None, TreeNode(-1, TreeNode(-1)))\n\n# The original values in left parentheses...
1
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode...
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
Easy Python Solution | Faster than 99% (76 ms) | Comments
find-elements-in-a-contaminated-binary-tree
0
1
# Easy Python Solution | Faster than 99% (76 ms) | With Comments\n\n**Runtime: 76 ms, faster than 99.13% of Python3 online submissions for Find Elements in a Contaminated Binary Tree.\nMemory Usage: 17.9 MB**\n\n```\nclass FindElements:\n \n def dfs(self, node, val):\n if node:\n self.store[val]...
2
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode...
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
Easy to understand python BFS solution
find-elements-in-a-contaminated-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTraverse the tree using BFS, and store all the values of the nodes in a set. Then find whether the \'target\' exists in the set or not.\n# Complexity\n- Time complexit...
0
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode...
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
Python3 O(N) solution with preorder traversal (100% Runtime)
find-elements-in-a-contaminated-binary-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/ba0d3963-de8a-4c8b-9daa-c5975c4d669d_1702291691.6985152.png)\nUse preorder to assign values & use a dictionary for constant time existence check\n\n# Approach\n<!-- Describe your appro...
0
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode...
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
Extremely short solution in Python 3, using generator and set
find-elements-in-a-contaminated-binary-tree
0
1
```python\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass FindElements:\n\n def __init__(self, root: Optional[TreeNode]):\n \n def gen(n: TreeNode...
0
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode...
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.