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 |
---|---|---|---|---|---|---|---|
Easy python solution | binary-string-with-substrings-representing-1-to-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nImplement integer to binary your own way. Avoid in build functions. Best will be if you implement the find function yourself too. \nProtip : there van be atmost len(s)^2 unique numbers generated from the string. So if the n is bigger than that answer automatically become false. \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)$$ -->\n\n# Code\n```\nclass Solution:\n def queryString(self, s: str, n: int) -> bool:\n \n if len(s)**2<n:\n return False\n for i in range(n,0,-1):\n j=i\n nst=\'\'\n while j:\n nst+= \'1\' if j%2 else \'0\'\n j=j//2\n nst=nst[::-1]\n if nst not in s:\n # print(nst,i)\n return False\n return True\n``` | 0 | Given a binary string `s` and a positive integer `n`, return `true` _if the binary representation of all the integers in the range_ `[1, n]` _are **substrings** of_ `s`_, or_ `false` _otherwise_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "0110", n = 3
**Output:** true
**Example 2:**
**Input:** s = "0110", n = 4
**Output:** false
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= n <= 109` | null |
Easy python solution | binary-string-with-substrings-representing-1-to-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nImplement integer to binary your own way. Avoid in build functions. Best will be if you implement the find function yourself too. \nProtip : there van be atmost len(s)^2 unique numbers generated from the string. So if the n is bigger than that answer automatically become false. \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)$$ -->\n\n# Code\n```\nclass Solution:\n def queryString(self, s: str, n: int) -> bool:\n \n if len(s)**2<n:\n return False\n for i in range(n,0,-1):\n j=i\n nst=\'\'\n while j:\n nst+= \'1\' if j%2 else \'0\'\n j=j//2\n nst=nst[::-1]\n if nst not in s:\n # print(nst,i)\n return False\n return True\n``` | 0 | Given a string `text` and an array of strings `words`, return _an array of all index pairs_ `[i, j]` _so that the substring_ `text[i...j]` _is in `words`_.
Return the pairs `[i, j]` in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate).
**Example 1:**
**Input:** text = "thestoryofleetcodeandme ", words = \[ "story ", "fleet ", "leetcode "\]
**Output:** \[\[3,7\],\[9,13\],\[10,17\]\]
**Example 2:**
**Input:** text = "ababa ", words = \[ "aba ", "ab "\]
**Output:** \[\[0,1\],\[0,2\],\[2,3\],\[2,4\]\]
**Explanation:** Notice that matches can overlap, see "aba " is found in \[0,2\] and \[2,4\].
**Constraints:**
* `1 <= text.length <= 100`
* `1 <= words.length <= 20`
* `1 <= words[i].length <= 50`
* `text` and `words[i]` consist of lowercase English letters.
* All the strings of `words` are **unique**. | We only need to check substrings of length at most 30, because 10^9 has 30 bits. |
We only need to test n < 1023 after analysis | binary-string-with-substrings-representing-1-to-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nActually, we don\'t need to test numbers more than 1023, so it could be much faster in theory.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, once we check `1 + X`, we don\'t need to check `X` since it\'s already included in `1 + X`. For example, `1110` includes `110` and `1101` includes `101`. This can reduce nearly half of works.\n\nMoreover, based on [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/), we can use the idea of Eular cycle to create a string with the minimal length to enumerate all possible values. It\'s `k + |E|` where `k` is the length of the string of a vertex and `|E|` is the number of edges.\n\nTake 1023 as an example, the length of its binary form is 10. We only need to consider all binary strings with length 10 since the other strings are just substrings of these strings with length 10. What\'s the minimal length to represent all binary strings with length 10? It\'s `9 + 2^9 * 2 > 1000`. Here `9` is the length of the binary string form of a vertex (the first vertex), `2^9` is the number of vertices, and `2` is the number of edges per vertex.\n\nSince the minimal length is larger than 1000, we know it\'s definitely `false` when `N >= 1023`.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nLet the length of s be `M`. Roughly speaking, it can include a binary string with length of `log2 M` and `2^ log2 M = M`, so the time complexity is bounded by `M`.\n\nTotal complexity is $$O(M^2)$$ since we only need to test at most `M` numbers and it requries $$O(M)$$ for each test.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def queryString(self, s: str, n: int) -> bool:\n if n >= 1023:\n return False\n for i in range(n, 0, -1):\n if s.find(format(i, \'b\')) < 0:\n return False\n return True\n``` | 0 | Given a binary string `s` and a positive integer `n`, return `true` _if the binary representation of all the integers in the range_ `[1, n]` _are **substrings** of_ `s`_, or_ `false` _otherwise_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "0110", n = 3
**Output:** true
**Example 2:**
**Input:** s = "0110", n = 4
**Output:** false
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= n <= 109` | null |
We only need to test n < 1023 after analysis | binary-string-with-substrings-representing-1-to-n | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nActually, we don\'t need to test numbers more than 1023, so it could be much faster in theory.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, once we check `1 + X`, we don\'t need to check `X` since it\'s already included in `1 + X`. For example, `1110` includes `110` and `1101` includes `101`. This can reduce nearly half of works.\n\nMoreover, based on [Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/), we can use the idea of Eular cycle to create a string with the minimal length to enumerate all possible values. It\'s `k + |E|` where `k` is the length of the string of a vertex and `|E|` is the number of edges.\n\nTake 1023 as an example, the length of its binary form is 10. We only need to consider all binary strings with length 10 since the other strings are just substrings of these strings with length 10. What\'s the minimal length to represent all binary strings with length 10? It\'s `9 + 2^9 * 2 > 1000`. Here `9` is the length of the binary string form of a vertex (the first vertex), `2^9` is the number of vertices, and `2` is the number of edges per vertex.\n\nSince the minimal length is larger than 1000, we know it\'s definitely `false` when `N >= 1023`.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nLet the length of s be `M`. Roughly speaking, it can include a binary string with length of `log2 M` and `2^ log2 M = M`, so the time complexity is bounded by `M`.\n\nTotal complexity is $$O(M^2)$$ since we only need to test at most `M` numbers and it requries $$O(M)$$ for each test.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def queryString(self, s: str, n: int) -> bool:\n if n >= 1023:\n return False\n for i in range(n, 0, -1):\n if s.find(format(i, \'b\')) < 0:\n return False\n return True\n``` | 0 | Given a string `text` and an array of strings `words`, return _an array of all index pairs_ `[i, j]` _so that the substring_ `text[i...j]` _is in `words`_.
Return the pairs `[i, j]` in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate).
**Example 1:**
**Input:** text = "thestoryofleetcodeandme ", words = \[ "story ", "fleet ", "leetcode "\]
**Output:** \[\[3,7\],\[9,13\],\[10,17\]\]
**Example 2:**
**Input:** text = "ababa ", words = \[ "aba ", "ab "\]
**Output:** \[\[0,1\],\[0,2\],\[2,3\],\[2,4\]\]
**Explanation:** Notice that matches can overlap, see "aba " is found in \[0,2\] and \[2,4\].
**Constraints:**
* `1 <= text.length <= 100`
* `1 <= words.length <= 20`
* `1 <= words[i].length <= 50`
* `text` and `words[i]` consist of lowercase English letters.
* All the strings of `words` are **unique**. | We only need to check substrings of length at most 30, because 10^9 has 30 bits. |
Solution | convert-to-base-2 | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n string baseNeg2(int n) {\n if (n == 0)\n return "0";\n string out = "";\n while (n) {\n out = ((n&1) ? "1" : "0") + out;\n n = -(n >> 1);\n }\n return out;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def baseNeg2(self, n: int) -> str:\n if n==0:\n return \'0\'\n\n ret = []\n while (n != 0):\n\n if n % 2 == 0:\n ret.append(\'0\')\n n //= -2\n else:\n ret.append(\'1\')\n n = (n - 1) // -2\n\n return \'\'.join(ret[::-1])\n```\n\n```Java []\nclass Solution {\n public String baseNeg2(int n) {\n StringBuilder sc = new StringBuilder();\n int rem;\n int b = -2;\n if(n == 0)\n sc.append(\'0\');\n while(n != 0){\n rem = n % b;\n n /= b;\n if(rem < 0){\n rem -= b;\n n++;\n }\n sc.append(rem);\n }\n return sc.reverse().toString();\n }\n}\n``` | 2 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:** "111 "
**Explantion:** (-2)2 + (-2)1 + (-2)0 = 3
**Example 3:**
**Input:** n = 4
**Output:** "100 "
**Explantion:** (-2)2 = 4
**Constraints:**
* `0 <= n <= 109` | null |
Python4 | convert-to-base-2 | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def baseNeg2(self, n: int) -> str:\n if n == 0:\n return \'0\'\n s = str()\n while n != 0:\n temp = n % -2\n n //= -2\n if temp < 0:\n temp += 2\n n += 1\n s = str(temp) + s\n return s\n``` | 0 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:** "111 "
**Explantion:** (-2)2 + (-2)1 + (-2)0 = 3
**Example 3:**
**Input:** n = 4
**Output:** "100 "
**Explantion:** (-2)2 = 4
**Constraints:**
* `0 <= n <= 109` | null |
convert to base -2 | convert-to-base-2 | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def baseNeg2(self, n: int) -> str:\n if n==0:\n return \'0\'\n s=\'\'\n while n!=0:\n remainder=n%-2\n n//=-2\n if remainder<0:\n remainder+=2\n n+=1\n s=str(remainder)+s\n return s\n``` | 0 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:** "111 "
**Explantion:** (-2)2 + (-2)1 + (-2)0 = 3
**Example 3:**
**Input:** n = 4
**Output:** "100 "
**Explantion:** (-2)2 = 4
**Constraints:**
* `0 <= n <= 109` | null |
C++ and Python simple solution | binary-prefix-divisible-by-5 | 0 | 1 | **C++ :**\n\n```\nclass Solution {\npublic:\n vector<bool> prefixesDivBy5(vector<int>& nums) {\n \n vector<bool> res;\n int num;\n \n for(int i = 0; i < nums.size(); ++i)\n {\n num = (num * 2 + nums[i]) % 5;\n res.push_back(num == 0);\n }\n \n return res;\n }\n};\n```\n\n**Python :**\n\n```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n res = []\n num = 0\n \n for n in nums:\n num = (num * 2 + n) % 5\n res.append(num == 0)\n \n return res\n```\n\n**Like it? please upvote** | 25 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
C++ and Python simple solution | binary-prefix-divisible-by-5 | 0 | 1 | **C++ :**\n\n```\nclass Solution {\npublic:\n vector<bool> prefixesDivBy5(vector<int>& nums) {\n \n vector<bool> res;\n int num;\n \n for(int i = 0; i < nums.size(); ++i)\n {\n num = (num * 2 + nums[i]) % 5;\n res.push_back(num == 0);\n }\n \n return res;\n }\n};\n```\n\n**Python :**\n\n```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n res = []\n num = 0\n \n for n in nums:\n num = (num * 2 + n) % 5\n res.append(num == 0)\n \n return res\n```\n\n**Like it? please upvote** | 25 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
Java and Python Solution | binary-prefix-divisible-by-5 | 1 | 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)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n int val = 0;\n List<Boolean> list = new ArrayList<>();\n for(int num : nums){\n // % 5 to prevent integer overflow, otherwsie will need to use BigInteger\n val = ((val * 2) + num) % 5;\n list.add(val == 0);\n }\n return list;\n }\n}\n```\n\n# Python\n\n```\ndef prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n result = list()\n res = str(nums[0])\n result.append(True) if int(res) == 0 else result.append(False)\n for j in range(1, len(nums)):\n res += str(nums[j])\n if int(res, 2) % 5 == 0:\n result.append(True)\n else:\n result.append(False)\n return result\n``` | 1 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
Java and Python Solution | binary-prefix-divisible-by-5 | 1 | 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)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n int val = 0;\n List<Boolean> list = new ArrayList<>();\n for(int num : nums){\n // % 5 to prevent integer overflow, otherwsie will need to use BigInteger\n val = ((val * 2) + num) % 5;\n list.add(val == 0);\n }\n return list;\n }\n}\n```\n\n# Python\n\n```\ndef prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n result = list()\n res = str(nums[0])\n result.append(True) if int(res) == 0 else result.append(False)\n for j in range(1, len(nums)):\n res += str(nums[j])\n if int(res, 2) % 5 == 0:\n result.append(True)\n else:\n result.append(False)\n return result\n``` | 1 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
Java, C++, Python | 🚀 A pinch of math in 7 lines explained | binary-prefix-divisible-by-5 | 1 | 1 | > \u26A0\uFE0F **Disclaimer**: The original solution was crafted in Java.\n\nDont forget to upvote if you like the content below. \uD83D\uDE43\n\n# Intuition\nThe task requires us to check whether the binary prefix of each number in an array is divisible by 5. We need to return a boolean array where each index corresponds to the result of the check for the binary prefix ending at the same index in the input array. \n\nThe key insight to solve this problem is to understand that we can keep a running count of the binary number as we iterate through the array and check for divisibility by $$5$$ at each step. As the binary number can be very large, we can take advantage of the fact that $$(a*b) \\mod n==((a \\bmod n)*(b \\mod n)) \\mod n$$.\n\n# Approach\nWe initialize a counter to keep track of the running binary number and an array list to store the results. For each number in the input array, we shift the current counter value to the left by one bit (equivalent to multiplying by $$2$$) and add the current number. We then take the modulus by $$5$$ and check if the result is $$0$$. If it is, we add `true` to the results array; otherwise, we add `false`.\n\n# Complexity Analysis\n- Time complexity: The time complexity is $$O(n)$$, where $$n$$ is the length of the input array, because we make a single pass through the array.\n- Space complexity: The space complexity is $$O(n)$$, where $$n$$ is the length of the input array, because we store a result for each element in the array.\n\n# Code\n```java []\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n var result = new ArrayList<Boolean>(nums.length);\n long counter = 0;\n for (int num : nums) {\n counter = ((counter << 1) + num) % 5;\n result.add(counter == 0);\n }\n return result;\n }\n}\n```\n``` cpp []\nclass Solution {\npublic:\n vector<bool> prefixesDivBy5(vector<int>& nums) {\n vector<bool> result;\n int counter = 0;\n for (int num : nums) {\n counter = ((counter << 1) + num) % 5;\n result.push_back(counter == 0);\n }\n return result;\n }\n};\n\n```\n``` python3 []\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n result = []\n counter = 0\n for num in nums:\n counter = ((counter << 1) + num) % 5\n result.append(counter == 0)\n return result\n\n``` | 2 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
Java, C++, Python | 🚀 A pinch of math in 7 lines explained | binary-prefix-divisible-by-5 | 1 | 1 | > \u26A0\uFE0F **Disclaimer**: The original solution was crafted in Java.\n\nDont forget to upvote if you like the content below. \uD83D\uDE43\n\n# Intuition\nThe task requires us to check whether the binary prefix of each number in an array is divisible by 5. We need to return a boolean array where each index corresponds to the result of the check for the binary prefix ending at the same index in the input array. \n\nThe key insight to solve this problem is to understand that we can keep a running count of the binary number as we iterate through the array and check for divisibility by $$5$$ at each step. As the binary number can be very large, we can take advantage of the fact that $$(a*b) \\mod n==((a \\bmod n)*(b \\mod n)) \\mod n$$.\n\n# Approach\nWe initialize a counter to keep track of the running binary number and an array list to store the results. For each number in the input array, we shift the current counter value to the left by one bit (equivalent to multiplying by $$2$$) and add the current number. We then take the modulus by $$5$$ and check if the result is $$0$$. If it is, we add `true` to the results array; otherwise, we add `false`.\n\n# Complexity Analysis\n- Time complexity: The time complexity is $$O(n)$$, where $$n$$ is the length of the input array, because we make a single pass through the array.\n- Space complexity: The space complexity is $$O(n)$$, where $$n$$ is the length of the input array, because we store a result for each element in the array.\n\n# Code\n```java []\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n var result = new ArrayList<Boolean>(nums.length);\n long counter = 0;\n for (int num : nums) {\n counter = ((counter << 1) + num) % 5;\n result.add(counter == 0);\n }\n return result;\n }\n}\n```\n``` cpp []\nclass Solution {\npublic:\n vector<bool> prefixesDivBy5(vector<int>& nums) {\n vector<bool> result;\n int counter = 0;\n for (int num : nums) {\n counter = ((counter << 1) + num) % 5;\n result.push_back(counter == 0);\n }\n return result;\n }\n};\n\n```\n``` python3 []\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n result = []\n counter = 0\n for num in nums:\n counter = ((counter << 1) + num) % 5\n result.append(counter == 0)\n return result\n\n``` | 2 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
Solution | binary-prefix-divisible-by-5 | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<bool> prefixesDivBy5(vector<int>& nums) {\n vector<bool> r;\n int n=0;\n for(int b : nums){\n n = ((n<<1) | b) % 5;\n r.push_back(n==0);\n }\n return r;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n currBinary, result = 0, []\n for bit in nums:\n currBinary = (currBinary * 2 + bit) % 5 \n result.append(currBinary == 0)\n return result\n```\n\n```Java []\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n int c = 0;\n Boolean ans[] = new Boolean[nums.length];\n for(int i=0; i<nums.length; i++){\n c = ((c<<1) + nums[i]) % 5;\n ans[i] = c == 0;\n }\n return Arrays.asList(ans);\n }\n}\n``` | 2 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
Solution | binary-prefix-divisible-by-5 | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<bool> prefixesDivBy5(vector<int>& nums) {\n vector<bool> r;\n int n=0;\n for(int b : nums){\n n = ((n<<1) | b) % 5;\n r.push_back(n==0);\n }\n return r;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n currBinary, result = 0, []\n for bit in nums:\n currBinary = (currBinary * 2 + bit) % 5 \n result.append(currBinary == 0)\n return result\n```\n\n```Java []\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n int c = 0;\n Boolean ans[] = new Boolean[nums.length];\n for(int i=0; i<nums.length; i++){\n c = ((c<<1) + nums[i]) % 5;\n ans[i] = c == 0;\n }\n return Arrays.asList(ans);\n }\n}\n``` | 2 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
|| Easy Solution || DFA || | binary-prefix-divisible-by-5 | 1 | 1 | # Intuition\nUsing Deterministic Finite Automata \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nConstant\n\n# Code\n```\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n List<Boolean> res = new ArrayList<>();\n int daigram[][] ={{0,1},{2,3},{4,0},{1,2},{3,4}};\n int s = 0;\n for(int a : nums)\n {\n s = daigram[s][a];\n if(s==0)\n res.add(true);\n else\n res.add(false);\n }\n return res;\n }\n}\n``` | 1 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
|| Easy Solution || DFA || | binary-prefix-divisible-by-5 | 1 | 1 | # Intuition\nUsing Deterministic Finite Automata \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nConstant\n\n# Code\n```\nclass Solution {\n public List<Boolean> prefixesDivBy5(int[] nums) {\n List<Boolean> res = new ArrayList<>();\n int daigram[][] ={{0,1},{2,3},{4,0},{1,2},{3,4}};\n int s = 0;\n for(int a : nums)\n {\n s = daigram[s][a];\n if(s==0)\n res.add(true);\n else\n res.add(false);\n }\n return res;\n }\n}\n``` | 1 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
Easy Python List boolean | binary-prefix-divisible-by-5 | 0 | 1 | \n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n# Code\n```\nclass Solution(object):\n def prefixesDivBy5(self, nums):\n l, top = [True] * len(nums), 0\n for i in range(len(nums)):\n top = top * 2 + nums[i]\n l[i] = top % 5 == 0\n return l\n``` | 0 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
Easy Python List boolean | binary-prefix-divisible-by-5 | 0 | 1 | \n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n# Code\n```\nclass Solution(object):\n def prefixesDivBy5(self, nums):\n l, top = [True] * len(nums), 0\n for i in range(len(nums)):\n top = top * 2 + nums[i]\n l[i] = top % 5 == 0\n return l\n``` | 0 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
Python 3 solution. Very interesting result!!! | binary-prefix-divisible-by-5 | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n tmp = 0\n res = [0] * len(nums)\n for i, num in enumerate(nums):\n tmp = (2*tmp + num) % 5\n res[i] = tmp == 0\n return res\n``` | 0 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
Python 3 solution. Very interesting result!!! | binary-prefix-divisible-by-5 | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n tmp = 0\n res = [0] * len(nums)\n for i, num in enumerate(nums):\n tmp = (2*tmp + num) % 5\n res[i] = tmp == 0\n return res\n``` | 0 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
1018. Binary Prefix Divisible by 5 || Solution for Python3 | binary-prefix-divisible-by-5 | 0 | 1 | ```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n l = []\n decimal_num = 0\n\n for i in range(len(nums)):\n decimal_num = decimal_num * 2 + nums[i]\n\n if decimal_num % 5 == 0:\n l.append(True)\n else:\n l.append(False)\n \n return l\n\n``` | 0 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
1018. Binary Prefix Divisible by 5 || Solution for Python3 | binary-prefix-divisible-by-5 | 0 | 1 | ```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n l = []\n decimal_num = 0\n\n for i in range(len(nums)):\n decimal_num = decimal_num * 2 + nums[i]\n\n if decimal_num % 5 == 0:\n l.append(True)\n else:\n l.append(False)\n \n return l\n\n``` | 0 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
Fast solution on Python. Runtime 84ms - 100%!!! | binary-prefix-divisible-by-5 | 0 | 1 | \n# Code\n```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n \n num, k, ans = 0, 1, []\n for i in nums:\n num = (num*2+i)%5\n ans.append(num == 0)\n return ans\n\n\n``` | 0 | You are given a binary array `nums` (**0-indexed**).
We define `xi` as the number whose binary representation is the subarray `nums[0..i]` (from most-significant-bit to least-significant-bit).
* For example, if `nums = [1,0,1]`, then `x0 = 1`, `x1 = 2`, and `x2 = 5`.
Return _an array of booleans_ `answer` _where_ `answer[i]` _is_ `true` _if_ `xi` _is divisible by_ `5`.
**Example 1:**
**Input:** nums = \[0,1,1\]
**Output:** \[true,false,false\]
**Explanation:** The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.
Only the first number is divisible by 5, so answer\[0\] is true.
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** \[false,false,false\]
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | null |
Fast solution on Python. Runtime 84ms - 100%!!! | binary-prefix-divisible-by-5 | 0 | 1 | \n# Code\n```\nclass Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n \n num, k, ans = 0, 1, []\n for i in nums:\n num = (num*2+i)%5\n ans.append(num == 0)\n return ans\n\n\n``` | 0 | For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters. | If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits. |
80% TC and 77% SC easy python solution | next-greater-node-in-linked-list | 0 | 1 | ```\ndef nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n\tans = []\n\tstack = []\n\ti = 0\n\tcurr = head\n\twhile(curr):\n\t# just for the length of the linked list.\n\t\tans.append(0)\n\t\tcurr = curr.next\n\twhile(head):\n\t\twhile(stack and stack[-1][1] < head.val):\n\t\t\tindex, _ = stack.pop()\n\t\t\tans[index] = head.val\n\t\tstack.append([i, head.val])\n\t\ti += 1\n\t\thead = head.next\n\treturn ans\n``` | 2 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`.
**Example 1:**
**Input:** head = \[2,1,5\]
**Output:** \[5,5,0\]
**Example 2:**
**Input:** head = \[2,7,4,3,5\]
**Output:** \[7,0,5,5,0\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 104`
* `1 <= Node.val <= 109` | null |
80% TC and 77% SC easy python solution | next-greater-node-in-linked-list | 0 | 1 | ```\ndef nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n\tans = []\n\tstack = []\n\ti = 0\n\tcurr = head\n\twhile(curr):\n\t# just for the length of the linked list.\n\t\tans.append(0)\n\t\tcurr = curr.next\n\twhile(head):\n\t\twhile(stack and stack[-1][1] < head.val):\n\t\t\tindex, _ = stack.pop()\n\t\t\tans[index] = head.val\n\t\tstack.append([i, head.val])\n\t\ti += 1\n\t\thead = head.next\n\treturn ans\n``` | 2 | You are given an `m x n` binary matrix `matrix`.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa).
Return _the maximum number of rows that have all values equal after some number of flips_.
**Example 1:**
**Input:** matrix = \[\[0,1\],\[1,1\]\]
**Output:** 1
**Explanation:** After flipping no values, 1 row has all values equal.
**Example 2:**
**Input:** matrix = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first column, both rows have equal values.
**Example 3:**
**Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first two columns, the last two rows have equal values.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is either `0` or `1`. | We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j . |
Next Greater Node in Linked List (Python) | next-greater-node-in-linked-list | 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)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n if not head:\n return []\n\n # Convert linked list to a list\n values = []\n while head:\n values.append(head.val)\n head = head.next\n\n n = len(values)\n result = [0] * n\n stack = []\n\n for i in range(n):\n while stack and values[i] > values[stack[-1]]:\n j = stack.pop()\n result[j] = values[i]\n stack.append(i)\n\n return result\n``` | 2 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`.
**Example 1:**
**Input:** head = \[2,1,5\]
**Output:** \[5,5,0\]
**Example 2:**
**Input:** head = \[2,7,4,3,5\]
**Output:** \[7,0,5,5,0\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 104`
* `1 <= Node.val <= 109` | null |
Next Greater Node in Linked List (Python) | next-greater-node-in-linked-list | 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)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n if not head:\n return []\n\n # Convert linked list to a list\n values = []\n while head:\n values.append(head.val)\n head = head.next\n\n n = len(values)\n result = [0] * n\n stack = []\n\n for i in range(n):\n while stack and values[i] > values[stack[-1]]:\n j = stack.pop()\n result[j] = values[i]\n stack.append(i)\n\n return result\n``` | 2 | You are given an `m x n` binary matrix `matrix`.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa).
Return _the maximum number of rows that have all values equal after some number of flips_.
**Example 1:**
**Input:** matrix = \[\[0,1\],\[1,1\]\]
**Output:** 1
**Explanation:** After flipping no values, 1 row has all values equal.
**Example 2:**
**Input:** matrix = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first column, both rows have equal values.
**Example 3:**
**Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first two columns, the last two rows have equal values.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is either `0` or `1`. | We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j . |
Python3 Solution with explanation | next-greater-node-in-linked-list | 0 | 1 | As we traverse the linked list, we can use a stack to store a tuple (index, value), where the index is the position of the element in the linkedlist.\n\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n # initializing the position\n\t\tpos = -1\n stack = []\n \n # List[int] to be returned\n\t\tans = []\n \n\t\t#traverse the linked list till you reach the end of it\n\t\twhile head:\n\t\t\t# increment the pos\n pos += 1\n\n\t\t\t# appending a zero when we start with the head\n\t\t\tans.append(0)\n\n\t\t\t# If the stack has some value and the top of stack has value less than the current linked list node value,\n\t\t\t# pop the stack and insert the value of current node at that index\n\t\t\t# do that till the stack is empty. This means for all the values on the left, current value is the next greater\n\t\t\twhile stack and stack[-1][1] < head.val:\n idx, _ = stack.pop()\n ans[idx] = head.val\n \n\t\t\t# push the (index, head.val on the stack to compare with on the next iteration)\n\t\t\tstack.append((pos, head.val))\n head = head.next\n return ans\n``` | 35 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`.
**Example 1:**
**Input:** head = \[2,1,5\]
**Output:** \[5,5,0\]
**Example 2:**
**Input:** head = \[2,7,4,3,5\]
**Output:** \[7,0,5,5,0\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 104`
* `1 <= Node.val <= 109` | null |
Python3 Solution with explanation | next-greater-node-in-linked-list | 0 | 1 | As we traverse the linked list, we can use a stack to store a tuple (index, value), where the index is the position of the element in the linkedlist.\n\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n # initializing the position\n\t\tpos = -1\n stack = []\n \n # List[int] to be returned\n\t\tans = []\n \n\t\t#traverse the linked list till you reach the end of it\n\t\twhile head:\n\t\t\t# increment the pos\n pos += 1\n\n\t\t\t# appending a zero when we start with the head\n\t\t\tans.append(0)\n\n\t\t\t# If the stack has some value and the top of stack has value less than the current linked list node value,\n\t\t\t# pop the stack and insert the value of current node at that index\n\t\t\t# do that till the stack is empty. This means for all the values on the left, current value is the next greater\n\t\t\twhile stack and stack[-1][1] < head.val:\n idx, _ = stack.pop()\n ans[idx] = head.val\n \n\t\t\t# push the (index, head.val on the stack to compare with on the next iteration)\n\t\t\tstack.append((pos, head.val))\n head = head.next\n return ans\n``` | 35 | You are given an `m x n` binary matrix `matrix`.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa).
Return _the maximum number of rows that have all values equal after some number of flips_.
**Example 1:**
**Input:** matrix = \[\[0,1\],\[1,1\]\]
**Output:** 1
**Explanation:** After flipping no values, 1 row has all values equal.
**Example 2:**
**Input:** matrix = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first column, both rows have equal values.
**Example 3:**
**Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first two columns, the last two rows have equal values.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is either `0` or `1`. | We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j . |
python solution use monotonic stack beats 99% | next-greater-node-in-linked-list | 0 | 1 | # Intuition\n# ***Upvote If Its Useful***\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)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, n: Optional[ListNode]) -> List[int]:\n head = []\n while(n):\n head.append(n.val)\n n = n.next\n res = [0] * len(head) \n stack =[]\n for i in range(len(head)):\n while stack and head[stack[-1]] < head[i]:\n res[stack.pop()] = head[i]\n stack.append(i)\n return res\n\n``` | 1 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`.
**Example 1:**
**Input:** head = \[2,1,5\]
**Output:** \[5,5,0\]
**Example 2:**
**Input:** head = \[2,7,4,3,5\]
**Output:** \[7,0,5,5,0\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 104`
* `1 <= Node.val <= 109` | null |
python solution use monotonic stack beats 99% | next-greater-node-in-linked-list | 0 | 1 | # Intuition\n# ***Upvote If Its Useful***\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)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, n: Optional[ListNode]) -> List[int]:\n head = []\n while(n):\n head.append(n.val)\n n = n.next\n res = [0] * len(head) \n stack =[]\n for i in range(len(head)):\n while stack and head[stack[-1]] < head[i]:\n res[stack.pop()] = head[i]\n stack.append(i)\n return res\n\n``` | 1 | You are given an `m x n` binary matrix `matrix`.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa).
Return _the maximum number of rows that have all values equal after some number of flips_.
**Example 1:**
**Input:** matrix = \[\[0,1\],\[1,1\]\]
**Output:** 1
**Explanation:** After flipping no values, 1 row has all values equal.
**Example 2:**
**Input:** matrix = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first column, both rows have equal values.
**Example 3:**
**Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first two columns, the last two rows have equal values.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is either `0` or `1`. | We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j . |
python 98% | easy | next-greater-node-in-linked-list | 0 | 1 | ```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n \n \n u=[]\n \n while head:\n u.append(head.val)\n head = head.next\n \n nge =[0]*(len(u))\n \n stack=[]\n for i in range(len(u)):\n \n while stack and u[stack[-1]] < u[i]:\n nge[stack.pop()] = u[i]\n stack.append(i)\n \n return nge\n \n \n``` | 7 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`.
**Example 1:**
**Input:** head = \[2,1,5\]
**Output:** \[5,5,0\]
**Example 2:**
**Input:** head = \[2,7,4,3,5\]
**Output:** \[7,0,5,5,0\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 104`
* `1 <= Node.val <= 109` | null |
python 98% | easy | next-greater-node-in-linked-list | 0 | 1 | ```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n \n \n u=[]\n \n while head:\n u.append(head.val)\n head = head.next\n \n nge =[0]*(len(u))\n \n stack=[]\n for i in range(len(u)):\n \n while stack and u[stack[-1]] < u[i]:\n nge[stack.pop()] = u[i]\n stack.append(i)\n \n return nge\n \n \n``` | 7 | You are given an `m x n` binary matrix `matrix`.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa).
Return _the maximum number of rows that have all values equal after some number of flips_.
**Example 1:**
**Input:** matrix = \[\[0,1\],\[1,1\]\]
**Output:** 1
**Explanation:** After flipping no values, 1 row has all values equal.
**Example 2:**
**Input:** matrix = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first column, both rows have equal values.
**Example 3:**
**Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first two columns, the last two rows have equal values.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is either `0` or `1`. | We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j . |
Python stack w/ comment | next-greater-node-in-linked-list | 0 | 1 | ```py\n\'\'\'\nw: linked list + stack\n for such type of question, we could only know the value of node when we get there,\n then using a stack to store the previous information should do the job, the key here is \n how to construct the stack. In stead of only storing the value, we store (value, index) so\n we can modify the final result in O(1) on the fly\nh: 1) create a list res to store the result\n 2) every time we walk along the linked list\n 1) we append 0 to res\n if the current val > stack[-1][0]:\n we keep pop and change res[StoredIndex] = current val\n\t\t2) we append (current val, current index) to a stack\n\'\'\'\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n res = []\n stack = []\n idx = 0\n while head:\n res.append(0)\n curVal = head.val\n while stack and stack[-1][0] < curVal:\n _, pidx = stack.pop()\n res[pidx] = curVal\n \n stack.append((curVal, idx))\n idx += 1\n head = head.next\n return res\n``` | 9 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of the next greater node of the `ith` node (**1-indexed**). If the `ith` node does not have a next greater node, set `answer[i] = 0`.
**Example 1:**
**Input:** head = \[2,1,5\]
**Output:** \[5,5,0\]
**Example 2:**
**Input:** head = \[2,7,4,3,5\]
**Output:** \[7,0,5,5,0\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 104`
* `1 <= Node.val <= 109` | null |
Python stack w/ comment | next-greater-node-in-linked-list | 0 | 1 | ```py\n\'\'\'\nw: linked list + stack\n for such type of question, we could only know the value of node when we get there,\n then using a stack to store the previous information should do the job, the key here is \n how to construct the stack. In stead of only storing the value, we store (value, index) so\n we can modify the final result in O(1) on the fly\nh: 1) create a list res to store the result\n 2) every time we walk along the linked list\n 1) we append 0 to res\n if the current val > stack[-1][0]:\n we keep pop and change res[StoredIndex] = current val\n\t\t2) we append (current val, current index) to a stack\n\'\'\'\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n res = []\n stack = []\n idx = 0\n while head:\n res.append(0)\n curVal = head.val\n while stack and stack[-1][0] < curVal:\n _, pidx = stack.pop()\n res[pidx] = curVal\n \n stack.append((curVal, idx))\n idx += 1\n head = head.next\n return res\n``` | 9 | You are given an `m x n` binary matrix `matrix`.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from `0` to `1` or vice versa).
Return _the maximum number of rows that have all values equal after some number of flips_.
**Example 1:**
**Input:** matrix = \[\[0,1\],\[1,1\]\]
**Output:** 1
**Explanation:** After flipping no values, 1 row has all values equal.
**Example 2:**
**Input:** matrix = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first column, both rows have equal values.
**Example 3:**
**Input:** matrix = \[\[0,0,0\],\[0,0,1\],\[1,1,0\]\]
**Output:** 2
**Explanation:** After flipping values in the first two columns, the last two rows have equal values.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is either `0` or `1`. | We can use a stack that stores nodes in monotone decreasing order of value. When we see a node_j with a larger value, every node_i in the stack has next_larger(node_i) = node_j . |
Python3 Solution | number-of-enclaves | 0 | 1 | \n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m=len(grid)\n n=len(grid[0])\n\n stack=[]\n for i in range(m):\n if grid[i][0]:\n stack.append((i,0))\n\n if grid[i][n-1]:\n stack.append((i,n-1)) \n\n for j in range(n):\n if grid[0][j]:\n stack.append((0,j))\n\n if grid[m-1][j]:\n stack.append((m-1,j))\n\n\n while stack:\n i,j=stack.pop()\n grid[i][j]=0\n for x,y in(i-1,j),(i,j-1),(i+1,j),(i,j+1):\n if 0<=x<m and 0<=y<n and grid[x][y]:\n stack.append((x,y))\n\n return sum(map(sum,grid)) \n\n``` | 2 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd. | null |
Python3 Solution | number-of-enclaves | 0 | 1 | \n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m=len(grid)\n n=len(grid[0])\n\n stack=[]\n for i in range(m):\n if grid[i][0]:\n stack.append((i,0))\n\n if grid[i][n-1]:\n stack.append((i,n-1)) \n\n for j in range(n):\n if grid[0][j]:\n stack.append((0,j))\n\n if grid[m-1][j]:\n stack.append((m-1,j))\n\n\n while stack:\n i,j=stack.pop()\n grid[i][j]=0\n for x,y in(i-1,j),(i,j-1),(i+1,j),(i,j+1):\n if 0<=x<m and 0<=y<n and grid[x][y]:\n stack.append((x,y))\n\n return sum(map(sum,grid)) \n\n``` | 2 | Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together.
Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`.
Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros.
**Example 1:**
**Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\]
**Output:** \[1,0,0,0,0\]
**Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16.
**Example 2:**
**Input:** arr1 = \[0\], arr2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** arr1 = \[0\], arr2 = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= arr1.length, arr2.length <= 1000`
* `arr1[i]` and `arr2[i]` are `0` or `1`
* `arr1` and `arr2` have no leading zeros | Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.
Return as answer the number of nodes that are not reachable from the exterior node. |
Python O(m*n) code for reference | number-of-enclaves | 0 | 1 | \n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m,n,ans = len(grid),len(grid[0]),0\n def move(i,j,grid):\n if( i<0 or j < 0 or i>=m or j>=n ):\n return False,0\n elif(grid[i][j] == 0 ):\n return True , 0\n grid[i][j] = 0\n a = move(i-1,j,grid) \n b = move(i+1,j,grid) \n c = move(i,j-1,grid) \n d = move(i,j+1,grid) \n return a[0] and b[0] and c[0] and d[0] , 1+a[1]+b[1]+c[1]+d[1] \n \n for i in range(m):\n for j in range(n):\n if(grid[i][j] ==1 ):\n valid,count = move(i,j,grid)\n if(valid): \n ans += count \n \n return ans \n \n``` | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd. | null |
Python O(m*n) code for reference | number-of-enclaves | 0 | 1 | \n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m,n,ans = len(grid),len(grid[0]),0\n def move(i,j,grid):\n if( i<0 or j < 0 or i>=m or j>=n ):\n return False,0\n elif(grid[i][j] == 0 ):\n return True , 0\n grid[i][j] = 0\n a = move(i-1,j,grid) \n b = move(i+1,j,grid) \n c = move(i,j-1,grid) \n d = move(i,j+1,grid) \n return a[0] and b[0] and c[0] and d[0] , 1+a[1]+b[1]+c[1]+d[1] \n \n for i in range(m):\n for j in range(n):\n if(grid[i][j] ==1 ):\n valid,count = move(i,j,grid)\n if(valid): \n ans += count \n \n return ans \n \n``` | 1 | Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together.
Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`.
Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros.
**Example 1:**
**Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\]
**Output:** \[1,0,0,0,0\]
**Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16.
**Example 2:**
**Input:** arr1 = \[0\], arr2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** arr1 = \[0\], arr2 = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= arr1.length, arr2.length <= 1000`
* `arr1[i]` and `arr2[i]` are `0` or `1`
* `arr1` and `arr2` have no leading zeros | Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.
Return as answer the number of nodes that are not reachable from the exterior node. |
Two Approaches ||TLE to Success|| Easy with Explanation | number-of-enclaves | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought after seeing the question was that it\'s quit understood we have to use dfs(Travelling along all side and choose the one we want) with somehow marking the cell we visit .So first i tried with traversing each land and if it does not reaches land than counting all the cell traversed during this process and making them 0 so we don\'t traverse them again.\nThis approach is usefull if we have to find length or something like that . Even though this passed the testCase but it was slow (only 5.62%)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem with the approach was that there were not boundary one , we still try to find an escape which is impossible.\nSo in next approach we do exact opposite.\nwe will count the 1\'s which are connected to boundary 1\'s and make them 0 as they are not of our intreset.Rest of them will be our answer.\nGetting a 0 means we can\'t use that side.\nGetting all side 0 means that following land satisfy condition.\nBut after removing escape 1\'s all other will be our answer.\n\nThere may be many modification of these two approaches.\n\n# Thanks and hope it Helps\nSee if you can upvote\n# Code for first approach\n```class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n dic={}\n row=len(grid)\n col=len(grid[0])\n visited=[]\n def funClear(vis):\n for i in vis:\n grid[i[0]][i[1]]=0\n def fun(i,j):\n if i<0 or j<0 or i>=row or j>=col:\n return True\n if grid[i][j]==0:\n return False\n if [i,j] in visited:return False\n visited.append([i,j])\n up=fun(i-1,j)\n down=fun(i+1,j)\n left=fun(i,j+1)\n right=fun(i,j-1)\n return up or down or left or right\n c=0\n for i in range(row):\n for j in range(col):\n if ( grid[i][j] and not fun(i,j)) :\n c+=len(visited)\n funClear(visited)\n visited=[]\n return c\n```\n\n# Code for First approach Optimised\n```class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n dic={}\n row=len(grid)\n col=len(grid[0])\n visited=[]\n def funClear(vis):\n for i in vis:\n grid[i[0]][i[1]]=0\n def fun(i,j):\n if i<0 or j<0 or i>=row or j>=col:\n return True\n if grid[i][j]==0:\n return False\n if [i,j] in visited:return False\n visited.append([i,j])\n up=fun(i-1,j)\n down=fun(i+1,j)\n left=fun(i,j+1)\n right=fun(i,j-1)\n return up or down or left or right\n c=0\n for i in range(row):\n for j in range(col):\n if ( grid[i][j] and not fun(i,j)) :\n c+=len(visited)\n funClear(visited)\n visited=[]\n return c\n```\n \n\nuse int instead of array for visited for faster result\n# Code for 2nd approach\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n rows,cols = len(grid),len(grid[0])\n def fun(i,j):\n if i<0 or j<0 or i == rows or j == cols or not grid[i][j]:\n return \n grid[i][j] = 0 # we can escape with this one so we make it 0\n fun(i+1,j)\n fun(i-1,j)\n fun(i,j+1)\n fun(i,j-1)\n for i in range(rows):\n for j in range(cols):\n if (i == 0 or i == rows-1 or j== 0 or j == cols-1) and grid[i][j]:\n fun(i,j) \n c = 0\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n c += 1\n return c\n``` | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd. | null |
Two Approaches ||TLE to Success|| Easy with Explanation | number-of-enclaves | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought after seeing the question was that it\'s quit understood we have to use dfs(Travelling along all side and choose the one we want) with somehow marking the cell we visit .So first i tried with traversing each land and if it does not reaches land than counting all the cell traversed during this process and making them 0 so we don\'t traverse them again.\nThis approach is usefull if we have to find length or something like that . Even though this passed the testCase but it was slow (only 5.62%)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem with the approach was that there were not boundary one , we still try to find an escape which is impossible.\nSo in next approach we do exact opposite.\nwe will count the 1\'s which are connected to boundary 1\'s and make them 0 as they are not of our intreset.Rest of them will be our answer.\nGetting a 0 means we can\'t use that side.\nGetting all side 0 means that following land satisfy condition.\nBut after removing escape 1\'s all other will be our answer.\n\nThere may be many modification of these two approaches.\n\n# Thanks and hope it Helps\nSee if you can upvote\n# Code for first approach\n```class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n dic={}\n row=len(grid)\n col=len(grid[0])\n visited=[]\n def funClear(vis):\n for i in vis:\n grid[i[0]][i[1]]=0\n def fun(i,j):\n if i<0 or j<0 or i>=row or j>=col:\n return True\n if grid[i][j]==0:\n return False\n if [i,j] in visited:return False\n visited.append([i,j])\n up=fun(i-1,j)\n down=fun(i+1,j)\n left=fun(i,j+1)\n right=fun(i,j-1)\n return up or down or left or right\n c=0\n for i in range(row):\n for j in range(col):\n if ( grid[i][j] and not fun(i,j)) :\n c+=len(visited)\n funClear(visited)\n visited=[]\n return c\n```\n\n# Code for First approach Optimised\n```class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n dic={}\n row=len(grid)\n col=len(grid[0])\n visited=[]\n def funClear(vis):\n for i in vis:\n grid[i[0]][i[1]]=0\n def fun(i,j):\n if i<0 or j<0 or i>=row or j>=col:\n return True\n if grid[i][j]==0:\n return False\n if [i,j] in visited:return False\n visited.append([i,j])\n up=fun(i-1,j)\n down=fun(i+1,j)\n left=fun(i,j+1)\n right=fun(i,j-1)\n return up or down or left or right\n c=0\n for i in range(row):\n for j in range(col):\n if ( grid[i][j] and not fun(i,j)) :\n c+=len(visited)\n funClear(visited)\n visited=[]\n return c\n```\n \n\nuse int instead of array for visited for faster result\n# Code for 2nd approach\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n rows,cols = len(grid),len(grid[0])\n def fun(i,j):\n if i<0 or j<0 or i == rows or j == cols or not grid[i][j]:\n return \n grid[i][j] = 0 # we can escape with this one so we make it 0\n fun(i+1,j)\n fun(i-1,j)\n fun(i,j+1)\n fun(i,j-1)\n for i in range(rows):\n for j in range(cols):\n if (i == 0 or i == rows-1 or j== 0 or j == cols-1) and grid[i][j]:\n fun(i,j) \n c = 0\n for i in range(rows):\n for j in range(cols):\n if grid[i][j] == 1:\n c += 1\n return c\n``` | 1 | Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together.
Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`.
Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros.
**Example 1:**
**Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\]
**Output:** \[1,0,0,0,0\]
**Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16.
**Example 2:**
**Input:** arr1 = \[0\], arr2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** arr1 = \[0\], arr2 = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= arr1.length, arr2.length <= 1000`
* `arr1[i]` and `arr2[i]` are `0` or `1`
* `arr1` and `arr2` have no leading zeros | Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.
Return as answer the number of nodes that are not reachable from the exterior node. |
Python Easy O(n) Stack DFS Beats 99% Explained | number-of-enclaves | 0 | 1 | # Intuition\nIn graph search problems it\'s always easier to start at the border or boundaries and search inwards. Thus, despite the problem asking for the number of cells forming islands that do not touch the border of the grid, it\'s easier to count the inverse: the number of cells that are connected to the border of the grid, and subtract it from the total.\n\n# Approach\nWe solve this problem in 3 easy steps:\n1. Count the total number of 1s in the grid\n2. Search the border cells\n a. Initialize a DFS stack with the coordinates of any 1s\n b. Mark these 1s as visited and count them (in my implementation, I did so by simply changing the value in the grid to 0. You can also do so by maintaining a Set of visited coordinates.)\n3. Stack DFS\n a. Pop the top coordinate\n b. Check the neighboring cells for 1s\n c. Add any neighboring cells to the stack, mark as visited, and increment the count\n\nWe can then subtract the count from the original number of 1s to obtain our answer.\n\n# Complexity\n- Time complexity:\nO(n): the first loop runs exactly n iterations (n for the purpose of complexity class discussion is the entire input, not n in the code/problem definition), the second pair of loops is O(n), and the DFS is O(n) as well, searching 4n times with O(1) operations during each search.\n\n- Space complexity:\nO(n): the stack is O(n), and other variables are O(1).\n\n\n\n# Code\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n\n # Count the total number of 1s in the grid\n ones = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n ones += 1\n\n # Search the border of the grid for 1s and add to DFS stack\n # Flip any 1s to 0s to mark them as visited\n stack = []\n for i in range(m):\n if grid[i][0]:\n stack.append((i, 0))\n grid[i][0] = 0\n if grid[i][n-1]:\n stack.append((i, n - 1))\n grid[i][n-1] = 0\n for i in range(n):\n if grid[0][i]:\n stack.append((0, i))\n grid[0][i] = 0\n if grid[m-1][i]:\n stack.append((m - 1, i))\n grid[m-1][i] = 0\n\n # DFS to count the number of cells connected to the border\n ct = len(stack)\n while stack:\n x, y = stack.pop()\n # Check neighboring cells\n for x2, y2 in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:\n # If (x2, y2) is a valid coord and is a 1\n if 0 <= x2 and x2 < m and 0 <= y2 and y2 < n and grid[x2][y2]:\n # Add to stack, mark as visited, and increment ct\n stack.append((x2, y2))\n grid[x2][y2] = 0\n ct += 1\n \n # Return 1s not connected to the boundary = total 1s - 1s connected to boundary\n return ones - ct\n```\n\nFor a slightly less intuitive code that trims off n operations:\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n\n # Search the border of the grid for 1s and add to DFS stack\n # Flip any 1s to 0s to mark them as visited\n stack = []\n for i in range(m):\n if grid[i][0]:\n stack.append((i, 0))\n grid[i][0] = 0\n if grid[i][n-1]:\n stack.append((i, n - 1))\n grid[i][n-1] = 0\n for i in range(n):\n if grid[0][i]:\n stack.append((0, i))\n grid[0][i] = 0\n if grid[m-1][i]:\n stack.append((m - 1, i))\n grid[m-1][i] = 0\n\n # DFS\n while stack:\n x, y = stack.pop()\n # Check neighboring cells\n for x2, y2 in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:\n # If (x2, y2) is a valid coord and is a 1\n if 0 <= x2 and x2 < m and 0 <= y2 and y2 < n and grid[x2][y2]:\n # Add to stack, mark as visited\n stack.append((x2, y2))\n grid[x2][y2] = 0\n \n # Count the remaining number of 1s in the grid\n ct = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n ct += 1\n\n return ct\n``` | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd. | null |
Python Easy O(n) Stack DFS Beats 99% Explained | number-of-enclaves | 0 | 1 | # Intuition\nIn graph search problems it\'s always easier to start at the border or boundaries and search inwards. Thus, despite the problem asking for the number of cells forming islands that do not touch the border of the grid, it\'s easier to count the inverse: the number of cells that are connected to the border of the grid, and subtract it from the total.\n\n# Approach\nWe solve this problem in 3 easy steps:\n1. Count the total number of 1s in the grid\n2. Search the border cells\n a. Initialize a DFS stack with the coordinates of any 1s\n b. Mark these 1s as visited and count them (in my implementation, I did so by simply changing the value in the grid to 0. You can also do so by maintaining a Set of visited coordinates.)\n3. Stack DFS\n a. Pop the top coordinate\n b. Check the neighboring cells for 1s\n c. Add any neighboring cells to the stack, mark as visited, and increment the count\n\nWe can then subtract the count from the original number of 1s to obtain our answer.\n\n# Complexity\n- Time complexity:\nO(n): the first loop runs exactly n iterations (n for the purpose of complexity class discussion is the entire input, not n in the code/problem definition), the second pair of loops is O(n), and the DFS is O(n) as well, searching 4n times with O(1) operations during each search.\n\n- Space complexity:\nO(n): the stack is O(n), and other variables are O(1).\n\n\n\n# Code\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n\n # Count the total number of 1s in the grid\n ones = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n ones += 1\n\n # Search the border of the grid for 1s and add to DFS stack\n # Flip any 1s to 0s to mark them as visited\n stack = []\n for i in range(m):\n if grid[i][0]:\n stack.append((i, 0))\n grid[i][0] = 0\n if grid[i][n-1]:\n stack.append((i, n - 1))\n grid[i][n-1] = 0\n for i in range(n):\n if grid[0][i]:\n stack.append((0, i))\n grid[0][i] = 0\n if grid[m-1][i]:\n stack.append((m - 1, i))\n grid[m-1][i] = 0\n\n # DFS to count the number of cells connected to the border\n ct = len(stack)\n while stack:\n x, y = stack.pop()\n # Check neighboring cells\n for x2, y2 in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:\n # If (x2, y2) is a valid coord and is a 1\n if 0 <= x2 and x2 < m and 0 <= y2 and y2 < n and grid[x2][y2]:\n # Add to stack, mark as visited, and increment ct\n stack.append((x2, y2))\n grid[x2][y2] = 0\n ct += 1\n \n # Return 1s not connected to the boundary = total 1s - 1s connected to boundary\n return ones - ct\n```\n\nFor a slightly less intuitive code that trims off n operations:\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n\n # Search the border of the grid for 1s and add to DFS stack\n # Flip any 1s to 0s to mark them as visited\n stack = []\n for i in range(m):\n if grid[i][0]:\n stack.append((i, 0))\n grid[i][0] = 0\n if grid[i][n-1]:\n stack.append((i, n - 1))\n grid[i][n-1] = 0\n for i in range(n):\n if grid[0][i]:\n stack.append((0, i))\n grid[0][i] = 0\n if grid[m-1][i]:\n stack.append((m - 1, i))\n grid[m-1][i] = 0\n\n # DFS\n while stack:\n x, y = stack.pop()\n # Check neighboring cells\n for x2, y2 in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)]:\n # If (x2, y2) is a valid coord and is a 1\n if 0 <= x2 and x2 < m and 0 <= y2 and y2 < n and grid[x2][y2]:\n # Add to stack, mark as visited\n stack.append((x2, y2))\n grid[x2][y2] = 0\n \n # Count the remaining number of 1s in the grid\n ct = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]:\n ct += 1\n\n return ct\n``` | 1 | Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together.
Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`.
Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros.
**Example 1:**
**Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\]
**Output:** \[1,0,0,0,0\]
**Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16.
**Example 2:**
**Input:** arr1 = \[0\], arr2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** arr1 = \[0\], arr2 = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= arr1.length, arr2.length <= 1000`
* `arr1[i]` and `arr2[i]` are `0` or `1`
* `arr1` and `arr2` have no leading zeros | Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.
Return as answer the number of nodes that are not reachable from the exterior node. |
✅🐍Python3 || simplest solution 🔥🔥|| detailed explained | number-of-enclaves | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Using DFS**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- we know doing moves, we want to come to border 1\'s and after that we can tip off of the board.\n- so it is wise to start from boarder 1\'s and make dfs to 4 direction.\n- while we traverse particular cell having 1 we will mark it with 0 as a cap for understanding that we already traversed this.\n- do this for all border 1\'s.\n- now after this all process, traverse again the grid and count number of remaining 1\'s that is answer.\n\n# Function Understanding\n- **Ok(r, c)**: checks if row and column in current dfs call is valid or not\n- **isBorder(r, c)**: checks if current row and column of loop is lying in border of grid.\n\n# Complexity\n- Time complexity: O(N^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n ans = 0\n R = len(grid) - 1\n C = len(grid[0]) - 1\n \n def Ok(r, c):\n return 0 <= c <= C and 0 <= r <= R\n\n def isBorder(r, c):\n return r == 0 or c == 0 or c == C or r == R\n\n def dfs(r, c):\n if Ok(r, c):\n if grid[r][c] == 1:\n grid[r][c] = 0\n dfs(r, c+1)\n dfs(r, c-1)\n dfs(r+1, c)\n dfs(r-1, c)\n return\n\n for r in range(R+1):\n for c in range(C+1):\n if isBorder(r, c) and grid[r][c] == 1:\n dfs(r, c)\n \n for r in range(R+1):\n for c in range(C+1):\n if grid[r][c]: ans += 1\n \n return ans\n```\n# Please like and comment below (\u0336\u25C9\u035B\u203F\u25C9\u0336) | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd. | null |
✅🐍Python3 || simplest solution 🔥🔥|| detailed explained | number-of-enclaves | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Using DFS**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- we know doing moves, we want to come to border 1\'s and after that we can tip off of the board.\n- so it is wise to start from boarder 1\'s and make dfs to 4 direction.\n- while we traverse particular cell having 1 we will mark it with 0 as a cap for understanding that we already traversed this.\n- do this for all border 1\'s.\n- now after this all process, traverse again the grid and count number of remaining 1\'s that is answer.\n\n# Function Understanding\n- **Ok(r, c)**: checks if row and column in current dfs call is valid or not\n- **isBorder(r, c)**: checks if current row and column of loop is lying in border of grid.\n\n# Complexity\n- Time complexity: O(N^3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n ans = 0\n R = len(grid) - 1\n C = len(grid[0]) - 1\n \n def Ok(r, c):\n return 0 <= c <= C and 0 <= r <= R\n\n def isBorder(r, c):\n return r == 0 or c == 0 or c == C or r == R\n\n def dfs(r, c):\n if Ok(r, c):\n if grid[r][c] == 1:\n grid[r][c] = 0\n dfs(r, c+1)\n dfs(r, c-1)\n dfs(r+1, c)\n dfs(r-1, c)\n return\n\n for r in range(R+1):\n for c in range(C+1):\n if isBorder(r, c) and grid[r][c] == 1:\n dfs(r, c)\n \n for r in range(R+1):\n for c in range(C+1):\n if grid[r][c]: ans += 1\n \n return ans\n```\n# Please like and comment below (\u0336\u25C9\u035B\u203F\u25C9\u0336) | 1 | Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together.
Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`.
Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros.
**Example 1:**
**Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\]
**Output:** \[1,0,0,0,0\]
**Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16.
**Example 2:**
**Input:** arr1 = \[0\], arr2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** arr1 = \[0\], arr2 = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= arr1.length, arr2.length <= 1000`
* `arr1[i]` and `arr2[i]` are `0` or `1`
* `arr1` and `arr2` have no leading zeros | Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.
Return as answer the number of nodes that are not reachable from the exterior node. |
[C++/Python] Union-Find | number-of-enclaves | 0 | 1 | # Complexity\n- Time complexity: $$O(mn*\u03B1(mn))$$, where m and n are the dimensions of the input matrix, and $$\u03B1$$ is the inverse Ackermann function, which grows very slowly and can be considered as a constant for all practical purposes.\nThe overall time complexity comes from two parts. Firstly, the Union-Find operations have an amortized time complexity of $$\u03B1(mn)$$, which can be treated as a constant for the input size of the problem. Secondly, the loop that traverses the boundary cells of the matrix has a time complexity of $$O(mn)$$, since each cell is visited once.\n- Space complexity: O(mn). This is because we are using the UnionFind data structure, which has a space complexity of $$O(mn)$$. Additionally, we are using a visited array to keep track of cells that have already been processed, which also has a space complexity of $$O(mn)$$.\n\n# Code\n```C++ []\nclass UnionFind {\npublic: \n\tUnionFind(int n) : parent(n), rank(n) {\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tparent[i] = i;\n\t}\n\t\n\tint find(int x) {\n\t\tif (parent[x] == x) return x;\n\t\treturn parent[x] = find(parent[x]);\n\t}\n\t\n\tvoid unite(int x, int y) {\n\t\tint px = find(x), py = find(y);\n\t\tif (px != py) {\n\t\t\tif (rank[px] < rank[py]) swap(px, py);\n\t\t\tparent[py] = px;\n\t\t\tif (rank[px] == rank[py]) rank[px]++;\n\t\t}\n\t}\n\t\n\tbool same(int x, int y) {\n\t\treturn find(x) == find(y);\n\t}\nprivate:\n\tvector<int> parent, rank;\n};\n\nclass Solution {\npublic:\n int numEnclaves(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n UnionFind uf(m * n + 1);\n\n int virtualNode = m * n;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {\n if (grid[i][j] == 1) {\n uf.unite(i * n + j, virtualNode);\n }\n }\n }\n }\n\n int dD[] = {1, 0, -1, 0, 1};\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n for (int k = 0; k < 4; k++) {\n int x = i + dD[k], y = j + dD[k+1];\n if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {\n uf.unite(i * n + j, x * n + y);\n }\n }\n }\n }\n }\n\n int ans = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n if(!uf.same(i * n + j, virtualNode)) ans++;\n }\n }\n }\n return ans;\n }\n};\n```\n```python []\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.parent[x] == x:\n return x\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def unite(self, x, y):\n px, py = self.find(x), self.find(y)\n if px != py:\n if self.rank[px] < self.rank[py]:\n px, py = py, px\n self.parent[py] = px\n if self.rank[px] == self.rank[py]:\n self.rank[px] += 1\n\n def same(self, x, y):\n return self.find(x) == self.find(y)\n\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n uf = UnionFind(m * n + 1)\n\n virtual_node = m * n\n for i in range(m):\n for j in range(n):\n if i == 0 or j == 0 or i == m - 1 or j == n - 1:\n if grid[i][j] == 1:\n uf.unite(i * n + j, virtual_node)\n\n dxdy = [1, 0, -1, 0, 1]\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n for k in range(4):\n x, y = i + dxdy[k], j + dxdy[k+1]\n if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:\n uf.unite(i * n + j, x * n + y)\n\n ans = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and not uf.same(i * n + j, virtual_node):\n ans += 1\n return ans\n``` | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_.
**Example 1:**
**Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\]
**Output:** 3
**Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
**Example 2:**
**Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\]
**Output:** 0
**Explanation:** All 1s are either on the boundary or can reach the boundary.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid[i][j]` is either `0` or `1`.
For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd. | null |
[C++/Python] Union-Find | number-of-enclaves | 0 | 1 | # Complexity\n- Time complexity: $$O(mn*\u03B1(mn))$$, where m and n are the dimensions of the input matrix, and $$\u03B1$$ is the inverse Ackermann function, which grows very slowly and can be considered as a constant for all practical purposes.\nThe overall time complexity comes from two parts. Firstly, the Union-Find operations have an amortized time complexity of $$\u03B1(mn)$$, which can be treated as a constant for the input size of the problem. Secondly, the loop that traverses the boundary cells of the matrix has a time complexity of $$O(mn)$$, since each cell is visited once.\n- Space complexity: O(mn). This is because we are using the UnionFind data structure, which has a space complexity of $$O(mn)$$. Additionally, we are using a visited array to keep track of cells that have already been processed, which also has a space complexity of $$O(mn)$$.\n\n# Code\n```C++ []\nclass UnionFind {\npublic: \n\tUnionFind(int n) : parent(n), rank(n) {\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tparent[i] = i;\n\t}\n\t\n\tint find(int x) {\n\t\tif (parent[x] == x) return x;\n\t\treturn parent[x] = find(parent[x]);\n\t}\n\t\n\tvoid unite(int x, int y) {\n\t\tint px = find(x), py = find(y);\n\t\tif (px != py) {\n\t\t\tif (rank[px] < rank[py]) swap(px, py);\n\t\t\tparent[py] = px;\n\t\t\tif (rank[px] == rank[py]) rank[px]++;\n\t\t}\n\t}\n\t\n\tbool same(int x, int y) {\n\t\treturn find(x) == find(y);\n\t}\nprivate:\n\tvector<int> parent, rank;\n};\n\nclass Solution {\npublic:\n int numEnclaves(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n UnionFind uf(m * n + 1);\n\n int virtualNode = m * n;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {\n if (grid[i][j] == 1) {\n uf.unite(i * n + j, virtualNode);\n }\n }\n }\n }\n\n int dD[] = {1, 0, -1, 0, 1};\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n for (int k = 0; k < 4; k++) {\n int x = i + dD[k], y = j + dD[k+1];\n if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {\n uf.unite(i * n + j, x * n + y);\n }\n }\n }\n }\n }\n\n int ans = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n if(!uf.same(i * n + j, virtualNode)) ans++;\n }\n }\n }\n return ans;\n }\n};\n```\n```python []\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.parent[x] == x:\n return x\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def unite(self, x, y):\n px, py = self.find(x), self.find(y)\n if px != py:\n if self.rank[px] < self.rank[py]:\n px, py = py, px\n self.parent[py] = px\n if self.rank[px] == self.rank[py]:\n self.rank[px] += 1\n\n def same(self, x, y):\n return self.find(x) == self.find(y)\n\nclass Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n uf = UnionFind(m * n + 1)\n\n virtual_node = m * n\n for i in range(m):\n for j in range(n):\n if i == 0 or j == 0 or i == m - 1 or j == n - 1:\n if grid[i][j] == 1:\n uf.unite(i * n + j, virtual_node)\n\n dxdy = [1, 0, -1, 0, 1]\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n for k in range(4):\n x, y = i + dxdy[k], j + dxdy[k+1]\n if 0 <= x < m and 0 <= y < n and grid[x][y] == 1:\n uf.unite(i * n + j, x * n + y)\n\n ans = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1 and not uf.same(i * n + j, virtual_node):\n ans += 1\n return ans\n``` | 1 | Given two numbers `arr1` and `arr2` in base **\-2**, return the result of adding them together.
Each number is given in _array format_: as an array of 0s and 1s, from most significant bit to least significant bit. For example, `arr = [1,1,0,1]` represents the number `(-2)^3 + (-2)^2 + (-2)^0 = -3`. A number `arr` in _array, format_ is also guaranteed to have no leading zeros: either `arr == [0]` or `arr[0] == 1`.
Return the result of adding `arr1` and `arr2` in the same format: as an array of 0s and 1s with no leading zeros.
**Example 1:**
**Input:** arr1 = \[1,1,1,1,1\], arr2 = \[1,0,1\]
**Output:** \[1,0,0,0,0\]
**Explanation:** arr1 represents 11, arr2 represents 5, the output represents 16.
**Example 2:**
**Input:** arr1 = \[0\], arr2 = \[0\]
**Output:** \[0\]
**Example 3:**
**Input:** arr1 = \[0\], arr2 = \[1\]
**Output:** \[1\]
**Constraints:**
* `1 <= arr1.length, arr2.length <= 1000`
* `arr1[i]` and `arr2[i]` are `0` or `1`
* `arr1` and `arr2` have no leading zeros | Can you model this problem as a graph problem? Create n * m + 1 nodes where n * m nodes represents each cell of the map and one extra node to represent the exterior of the map. In the map add edges between neighbors on land cells. And add edges between the exterior and land nodes which are in the boundary.
Return as answer the number of nodes that are not reachable from the exterior node. |
Solution | remove-outermost-parentheses | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n string res;\n int opened = 0;\n for (char c : S) {\n if (c == \'(\' && opened++ > 0) res += c;\n if (c == \')\' && opened-- > 1) res += c;\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n res, opened = [], 0\n for c in S:\n if c == \'(\' and opened > 0: res.append(c)\n if c == \')\' and opened > 1: res.append(c)\n opened += 1 if c == \'(\' else -1\n \n return "".join(res)\n```\n\n```Java []\nclass Solution {\n public String removeOuterParentheses(String s) {\n int len = s.length();\n if (len <= 2) return "";\n char[] c = s.toCharArray();\n StringBuilder newString = new StringBuilder();\n int open = 1;\n int openLeft = 0;\n for (int i = 1; i < len; i++) {\n if (c[i] == \'(\') {\n open++;\n if (open > 1) newString.append(\'(\');\n }\n else {\n if (open > 1) newString.append(\')\');\n open--;\n }\n }\n return newString.toString();\n }\n}\n``` | 463 | A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.
Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.
Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.
**Example 1:**
**Input:** s = "(()())(()) "
**Output:** "()()() "
**Explanation:**
The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ".
After removing outer parentheses of each part, this is "()() " + "() " = "()()() ".
**Example 2:**
**Input:** s = "(()())(())(()(())) "
**Output:** "()()()()(()) "
**Explanation:**
The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ".
After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ".
**Example 3:**
**Input:** s = "()() "
**Output:** " "
**Explanation:**
The input string is "()() ", with primitive decomposition "() " + "() ".
After removing outer parentheses of each part, this is " " + " " = " ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'('` or `')'`.
* `s` is a valid parentheses string. | null |
Solution | remove-outermost-parentheses | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n string removeOuterParentheses(string S) {\n string res;\n int opened = 0;\n for (char c : S) {\n if (c == \'(\' && opened++ > 0) res += c;\n if (c == \')\' && opened-- > 1) res += c;\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def removeOuterParentheses(self, S: str) -> str:\n res, opened = [], 0\n for c in S:\n if c == \'(\' and opened > 0: res.append(c)\n if c == \')\' and opened > 1: res.append(c)\n opened += 1 if c == \'(\' else -1\n \n return "".join(res)\n```\n\n```Java []\nclass Solution {\n public String removeOuterParentheses(String s) {\n int len = s.length();\n if (len <= 2) return "";\n char[] c = s.toCharArray();\n StringBuilder newString = new StringBuilder();\n int open = 1;\n int openLeft = 0;\n for (int i = 1; i < len; i++) {\n if (c[i] == \'(\') {\n open++;\n if (open > 1) newString.append(\'(\');\n }\n else {\n if (open > 1) newString.append(\')\');\n open--;\n }\n }\n return newString.toString();\n }\n}\n``` | 463 | Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`.
Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`.
**Example 1:**
**Input:** text = "alice is a good girl she is a good student", first = "a", second = "good"
**Output:** \["girl","student"\]
**Example 2:**
**Input:** text = "we will we will rock you", first = "we", second = "will"
**Output:** \["we","rock"\]
**Constraints:**
* `1 <= text.length <= 1000`
* `text` consists of lowercase English letters and spaces.
* All the words in `text` a separated by **a single space**.
* `1 <= first.length, second.length <= 10`
* `first` and `second` consist of lowercase English letters. | Can you find the primitive decomposition? The number of ( and ) characters must be equal. |
💡One Pass | FAANG SDE-1 Interview😯 | remove-outermost-parentheses | 1 | 1 | ```\nVery Easy Beginner Friendly Solution \uD83D\uDCA1\nDo not use stack to prevent more extra space.\n\n\nPlease do Upvote if it helps :)\n```\n\n# Complexity\n- Time complexity: O(n) //One pass\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) //For resultant string\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string res;\n int count=0;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\' && count==0)\n count++;\n else if(s[i]==\'(\' && count>=1){\n res+=s[i];\n count++;\n } \n else if(s[i]==\')\' && count>1){\n res+=s[i];\n count--;\n }\n else if(s[i]==\')\' && count==1)\n count--;\n }\n return res;\n }\n};\n``` | 54 | A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.
Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.
Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.
**Example 1:**
**Input:** s = "(()())(()) "
**Output:** "()()() "
**Explanation:**
The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ".
After removing outer parentheses of each part, this is "()() " + "() " = "()()() ".
**Example 2:**
**Input:** s = "(()())(())(()(())) "
**Output:** "()()()()(()) "
**Explanation:**
The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ".
After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ".
**Example 3:**
**Input:** s = "()() "
**Output:** " "
**Explanation:**
The input string is "()() ", with primitive decomposition "() " + "() ".
After removing outer parentheses of each part, this is " " + " " = " ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'('` or `')'`.
* `s` is a valid parentheses string. | null |
💡One Pass | FAANG SDE-1 Interview😯 | remove-outermost-parentheses | 1 | 1 | ```\nVery Easy Beginner Friendly Solution \uD83D\uDCA1\nDo not use stack to prevent more extra space.\n\n\nPlease do Upvote if it helps :)\n```\n\n# Complexity\n- Time complexity: O(n) //One pass\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n) //For resultant string\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string removeOuterParentheses(string s) {\n string res;\n int count=0;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'(\' && count==0)\n count++;\n else if(s[i]==\'(\' && count>=1){\n res+=s[i];\n count++;\n } \n else if(s[i]==\')\' && count>1){\n res+=s[i];\n count--;\n }\n else if(s[i]==\')\' && count==1)\n count--;\n }\n return res;\n }\n};\n``` | 54 | Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`.
Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`.
**Example 1:**
**Input:** text = "alice is a good girl she is a good student", first = "a", second = "good"
**Output:** \["girl","student"\]
**Example 2:**
**Input:** text = "we will we will rock you", first = "we", second = "will"
**Output:** \["we","rock"\]
**Constraints:**
* `1 <= text.length <= 1000`
* `text` consists of lowercase English letters and spaces.
* All the words in `text` a separated by **a single space**.
* `1 <= first.length, second.length <= 10`
* `first` and `second` consist of lowercase English letters. | Can you find the primitive decomposition? The number of ( and ) characters must be equal. |
Easy Python Solution! | remove-outermost-parentheses | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nComment if you need any explaination or have any doubts.\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n out = \'\'\n count = -1\n f = True\n for i in s:\n if f:\n f = False\n count +=1\n continue\n if i==\'(\':\n out+=i\n count +=1\n if i ==\')\':\n count -=1\n if count == -1:\n f = not f\n continue\n out +=i\n return out\n``` | 1 | A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings.
Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings.
Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`.
**Example 1:**
**Input:** s = "(()())(()) "
**Output:** "()()() "
**Explanation:**
The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ".
After removing outer parentheses of each part, this is "()() " + "() " = "()()() ".
**Example 2:**
**Input:** s = "(()())(())(()(())) "
**Output:** "()()()()(()) "
**Explanation:**
The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ".
After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ".
**Example 3:**
**Input:** s = "()() "
**Output:** " "
**Explanation:**
The input string is "()() ", with primitive decomposition "() " + "() ".
After removing outer parentheses of each part, this is " " + " " = " ".
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'('` or `')'`.
* `s` is a valid parentheses string. | null |
Easy Python Solution! | remove-outermost-parentheses | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nComment if you need any explaination or have any doubts.\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeOuterParentheses(self, s: str) -> str:\n out = \'\'\n count = -1\n f = True\n for i in s:\n if f:\n f = False\n count +=1\n continue\n if i==\'(\':\n out+=i\n count +=1\n if i ==\')\':\n count -=1\n if count == -1:\n f = not f\n continue\n out +=i\n return out\n``` | 1 | Given two strings `first` and `second`, consider occurrences in some text of the form `"first second third "`, where `second` comes immediately after `first`, and `third` comes immediately after `second`.
Return _an array of all the words_ `third` _for each occurrence of_ `"first second third "`.
**Example 1:**
**Input:** text = "alice is a good girl she is a good student", first = "a", second = "good"
**Output:** \["girl","student"\]
**Example 2:**
**Input:** text = "we will we will rock you", first = "we", second = "will"
**Output:** \["we","rock"\]
**Constraints:**
* `1 <= text.length <= 1000`
* `text` consists of lowercase English letters and spaces.
* All the words in `text` a separated by **a single space**.
* `1 <= first.length, second.length <= 10`
* `first` and `second` consist of lowercase English letters. | Can you find the primitive decomposition? The number of ( and ) characters must be equal. |
Solution | sum-of-root-to-leaf-binary-numbers | 1 | 1 | ```C++ []\nclass Solution {\npublic:\nvoid helper(TreeNode* root, int val, int& res){\n if(!root) return;\n\n val = val | root->val;\n if(!root->left && !root->right){\n res+=val;\n return;\n }\n helper(root->left, val<<1, res);\n helper(root->right, val<<1, res);\n}\nvoid helper1(TreeNode* root, int out, int& res){\n if(!root) return;\n\n out = (out<<1) + root->val;\n if(!root->left && !root->right){\n res+=out;\n return;\n }\n helper1(root->left,out,res);\n helper1(root->right,out,res);\n}\nint sumRootToLeaf(TreeNode* root) {\n int res = 0;\n helper1(root,0,res);\n return res; \n}\n};\n```\n\n```Python3 []\nclass Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n result = 0\n if not root:\n return 0\n def dfs(node, slate):\n nonlocal result\n if not node.left and not node.right:\n slate.append(str(node.val))\n result += int("".join(slate), 2)\n \n if node.left: dfs(node.left, slate + [str(node.val)])\n if node.right: dfs(node.right, slate + [str(node.val)])\n \n dfs(root, [])\n return result\n```\n\n```Java []\nclass Solution {\n private int pathSumRootToLeaf(TreeNode root, int parentNodeSum){\n if(root == null) return 0;\n \n parentNodeSum = 2 * parentNodeSum + root.val;\n if(root.left == null && root.right == null){\n return parentNodeSum;\n }\n return pathSumRootToLeaf(root.left, parentNodeSum) + pathSumRootToLeaf(root.right, parentNodeSum);\n }\n public int sumRootToLeaf(TreeNode root) {\n return pathSumRootToLeaf(root, 0);\n }\n}\n``` | 1 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`. | null |
Solution | sum-of-root-to-leaf-binary-numbers | 1 | 1 | ```C++ []\nclass Solution {\npublic:\nvoid helper(TreeNode* root, int val, int& res){\n if(!root) return;\n\n val = val | root->val;\n if(!root->left && !root->right){\n res+=val;\n return;\n }\n helper(root->left, val<<1, res);\n helper(root->right, val<<1, res);\n}\nvoid helper1(TreeNode* root, int out, int& res){\n if(!root) return;\n\n out = (out<<1) + root->val;\n if(!root->left && !root->right){\n res+=out;\n return;\n }\n helper1(root->left,out,res);\n helper1(root->right,out,res);\n}\nint sumRootToLeaf(TreeNode* root) {\n int res = 0;\n helper1(root,0,res);\n return res; \n}\n};\n```\n\n```Python3 []\nclass Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n result = 0\n if not root:\n return 0\n def dfs(node, slate):\n nonlocal result\n if not node.left and not node.right:\n slate.append(str(node.val))\n result += int("".join(slate), 2)\n \n if node.left: dfs(node.left, slate + [str(node.val)])\n if node.right: dfs(node.right, slate + [str(node.val)])\n \n dfs(root, [])\n return result\n```\n\n```Java []\nclass Solution {\n private int pathSumRootToLeaf(TreeNode root, int parentNodeSum){\n if(root == null) return 0;\n \n parentNodeSum = 2 * parentNodeSum + root.val;\n if(root.left == null && root.right == null){\n return parentNodeSum;\n }\n return pathSumRootToLeaf(root.left, parentNodeSum) + pathSumRootToLeaf(root.right, parentNodeSum);\n }\n public int sumRootToLeaf(TreeNode root) {\n return pathSumRootToLeaf(root, 0);\n }\n}\n``` | 1 | You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it.
Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`.
**Example 1:**
**Input:** tiles = "AAB "
**Output:** 8
**Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ".
**Example 2:**
**Input:** tiles = "AAABBC "
**Output:** 188
**Example 3:**
**Input:** tiles = "V "
**Output:** 1
**Constraints:**
* `1 <= tiles.length <= 7`
* `tiles` consists of uppercase English letters. | Find each path, then transform that path to an integer in base 10. |
✔️ [Python3] 5-LINES ☜ ( ͡❛ 👅 ͡❛), Explained | sum-of-root-to-leaf-binary-numbers | 0 | 1 | We use the recursive Depth First Search here to build all binary numbers from the root-to-leaf path and sum them together. When a leaf node is reached, the function returns the built number. For the rest of the nodes, the function simply sums results from recursive calls. For building the binary number in the path we use a binary operation `(path << 1)` which shifts all bits to the left by one bit to free space for the current bit which we simply add to the path. Example:\n\n`path=0 => (path<<1) + 1 = 01`\n`path=01 => (path<<1) + 1 = 11`\n`path=11 => (path<<1) + 0 = 110`\n`path=110 => (path<<1) + 1 = 1101`\n\nTime: **O(N)** - for DFS\nSpace: **O(N)** - recursive stack for binary tree is equal to the tree height\n\nRuntime: 36 ms, faster than **80.51%** of Python3 online submissions for Sum of Root To Leaf Binary Numbers.\nMemory Usage: 14.4 MB, less than **96.20%** of Python3 online submissions for Sum of Root To Leaf Binary Numbers.\n\n```\nclass Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n def dfs(node, path):\n if not node: return 0\n\n path = (path << 1) + node.val\n\t\t\t\n if not node.left and not node.right:\n return path\n \n return dfs(node.left, path) + dfs(node.right, path)\n \n return dfs(root, 0)\n``` | 26 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`. | null |
✔️ [Python3] 5-LINES ☜ ( ͡❛ 👅 ͡❛), Explained | sum-of-root-to-leaf-binary-numbers | 0 | 1 | We use the recursive Depth First Search here to build all binary numbers from the root-to-leaf path and sum them together. When a leaf node is reached, the function returns the built number. For the rest of the nodes, the function simply sums results from recursive calls. For building the binary number in the path we use a binary operation `(path << 1)` which shifts all bits to the left by one bit to free space for the current bit which we simply add to the path. Example:\n\n`path=0 => (path<<1) + 1 = 01`\n`path=01 => (path<<1) + 1 = 11`\n`path=11 => (path<<1) + 0 = 110`\n`path=110 => (path<<1) + 1 = 1101`\n\nTime: **O(N)** - for DFS\nSpace: **O(N)** - recursive stack for binary tree is equal to the tree height\n\nRuntime: 36 ms, faster than **80.51%** of Python3 online submissions for Sum of Root To Leaf Binary Numbers.\nMemory Usage: 14.4 MB, less than **96.20%** of Python3 online submissions for Sum of Root To Leaf Binary Numbers.\n\n```\nclass Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n def dfs(node, path):\n if not node: return 0\n\n path = (path << 1) + node.val\n\t\t\t\n if not node.left and not node.right:\n return path\n \n return dfs(node.left, path) + dfs(node.right, path)\n \n return dfs(root, 0)\n``` | 26 | You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it.
Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`.
**Example 1:**
**Input:** tiles = "AAB "
**Output:** 8
**Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ".
**Example 2:**
**Input:** tiles = "AAABBC "
**Output:** 188
**Example 3:**
**Input:** tiles = "V "
**Output:** 1
**Constraints:**
* `1 <= tiles.length <= 7`
* `tiles` consists of uppercase English letters. | Find each path, then transform that path to an integer in base 10. |
Very easy DFS python 🐍 solution | sum-of-root-to-leaf-binary-numbers | 0 | 1 | ```\nclass Solution:\n def sumRootToLeaf(self, root: TreeNode) -> int:\n total=0\n \n stack=[(root,str(root.val))]\n \n while stack:\n node,binVal=stack.pop()\n \n if node.left:\n stack.append((node.left,binVal+str(node.left.val)))\n \n if node.right:\n stack.append((node.right,binVal+str(node.right.val)))\n\n if not node.left and not node.right:\n total+=int(binVal,2)\n return total \n``` | 11 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`. | null |
Very easy DFS python 🐍 solution | sum-of-root-to-leaf-binary-numbers | 0 | 1 | ```\nclass Solution:\n def sumRootToLeaf(self, root: TreeNode) -> int:\n total=0\n \n stack=[(root,str(root.val))]\n \n while stack:\n node,binVal=stack.pop()\n \n if node.left:\n stack.append((node.left,binVal+str(node.left.val)))\n \n if node.right:\n stack.append((node.right,binVal+str(node.right.val)))\n\n if not node.left and not node.right:\n total+=int(binVal,2)\n return total \n``` | 11 | You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it.
Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`.
**Example 1:**
**Input:** tiles = "AAB "
**Output:** 8
**Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ".
**Example 2:**
**Input:** tiles = "AAABBC "
**Output:** 188
**Example 3:**
**Input:** tiles = "V "
**Output:** 1
**Constraints:**
* `1 <= tiles.length <= 7`
* `tiles` consists of uppercase English letters. | Find each path, then transform that path to an integer in base 10. |
Solution | camelcase-matching | 1 | 1 | ```C++ []\nclass Solution {\n public:\n vector<bool> camelMatch(vector<string>& queries, string pattern) {\n vector<bool> ans;\n\n for (const string& q : queries)\n ans.push_back(isMatch(q, pattern));\n\n return ans;\n }\n private:\n bool isMatch(const string& q, const string& pattern) {\n int j = 0;\n\n for (int i = 0; i < q.length(); ++i)\n if (j < pattern.length() && q[i] == pattern[j])\n ++j;\n else if (isupper(q[i]))\n return false;\n\n return j == pattern.length();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def camelMatch(self, qs, p):\n def u(s):\n return [c for c in s if c.isupper()]\n\n def issup(s, t):\n it = iter(t)\n return all(c in it for c in s)\n return [u(p) == u(q) and issup(p, q) for q in qs]\n```\n\n```Java []\nclass Solution {\n public List<Boolean> camelMatch(String[] queries, String pattern) {\n List<Boolean> list = new ArrayList<>();\n\n for (var q : queries) {\n int index = 0;\n boolean flag = true;\n for (var c : q.toCharArray()) {\n if(index < pattern.length() && c == pattern.charAt(index)){\n index++;\n continue;\n }\n if(c >= \'A\' && c <= \'Z\'){\n if(index >= pattern.length() || c != pattern.charAt(index)){\n flag = false;\n break;\n }\n }\n }\n flag = flag && index == pattern.length();\n list.add(flag);\n }\n return list;\n }\n}\n``` | 1 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
Solution | camelcase-matching | 1 | 1 | ```C++ []\nclass Solution {\n public:\n vector<bool> camelMatch(vector<string>& queries, string pattern) {\n vector<bool> ans;\n\n for (const string& q : queries)\n ans.push_back(isMatch(q, pattern));\n\n return ans;\n }\n private:\n bool isMatch(const string& q, const string& pattern) {\n int j = 0;\n\n for (int i = 0; i < q.length(); ++i)\n if (j < pattern.length() && q[i] == pattern[j])\n ++j;\n else if (isupper(q[i]))\n return false;\n\n return j == pattern.length();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def camelMatch(self, qs, p):\n def u(s):\n return [c for c in s if c.isupper()]\n\n def issup(s, t):\n it = iter(t)\n return all(c in it for c in s)\n return [u(p) == u(q) and issup(p, q) for q in qs]\n```\n\n```Java []\nclass Solution {\n public List<Boolean> camelMatch(String[] queries, String pattern) {\n List<Boolean> list = new ArrayList<>();\n\n for (var q : queries) {\n int index = 0;\n boolean flag = true;\n for (var c : q.toCharArray()) {\n if(index < pattern.length() && c == pattern.charAt(index)){\n index++;\n continue;\n }\n if(c >= \'A\' && c <= \'Z\'){\n if(index >= pattern.length() || c != pattern.charAt(index)){\n flag = false;\n break;\n }\n }\n }\n flag = flag && index == pattern.length();\n list.add(flag);\n }\n return list;\n }\n}\n``` | 1 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
Python Easy Solution Faster Than 97.4% | camelcase-matching | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def match(self, query, pattern):\n pidx = 0\n for i in range(len(query)):\n if query[i].isupper():\n if query[i]==pattern[pidx]:\n pidx+=1\n else:\n return False\n else:\n if query[i]==pattern[pidx]:\n pidx+=1 \n if pidx==len(pattern):\n for j in range(i+1, len(query)):\n if query[j].isupper():\n return False\n return True\n\n \n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n ans = [False for _ in range(len(queries))]\n for i in range(len(queries)):\n if self.match(queries[i], pattern):\n ans[i]=True\n return ans\n\n\n``` | 1 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
Python Easy Solution Faster Than 97.4% | camelcase-matching | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def match(self, query, pattern):\n pidx = 0\n for i in range(len(query)):\n if query[i].isupper():\n if query[i]==pattern[pidx]:\n pidx+=1\n else:\n return False\n else:\n if query[i]==pattern[pidx]:\n pidx+=1 \n if pidx==len(pattern):\n for j in range(i+1, len(query)):\n if query[j].isupper():\n return False\n return True\n\n \n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n ans = [False for _ in range(len(queries))]\n for i in range(len(queries)):\n if self.match(queries[i], pattern):\n ans[i]=True\n return ans\n\n\n``` | 1 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
Python3 solution | camelcase-matching | 0 | 1 | ```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n res = []\n for word in queries:\n i = j = 0\n while i < len(word):\n if j < len(pattern) and word[i] == pattern[j]:\n i += 1\n j += 1\n elif word[i].isupper():\n break\n else:\n i += 1\n if i == len(word) and j == len(pattern):\n res.append(True)\n else:\n res.append(False)\n return res\n```\n**If you like this solution, please upvote for this** | 4 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
Python3 solution | camelcase-matching | 0 | 1 | ```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n res = []\n for word in queries:\n i = j = 0\n while i < len(word):\n if j < len(pattern) and word[i] == pattern[j]:\n i += 1\n j += 1\n elif word[i].isupper():\n break\n else:\n i += 1\n if i == len(word) and j == len(pattern):\n res.append(True)\n else:\n res.append(False)\n return res\n```\n**If you like this solution, please upvote for this** | 4 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
82% TC and 68% SC easy python solution | camelcase-matching | 0 | 1 | ```\ndef camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n\tclass Trie:\n\t\tdef __init__(self):\n\t\t\tself.root = dict()\n\t\tdef insert(self, word):\n\t\t\tc = self.root\n\t\t\tfor char in word:\n\t\t\t\tif(char not in c):\n\t\t\t\t\tc[char] = dict()\n\t\t\t\tc = c[char]\n\t\tdef find(self, word):\n\t\t\tc = self.root\n\t\t\ti = 0\n\t\t\tn = len(pattern)\n\t\t\tfor char in word:\n\t\t\t\tif(ord(char) < 97):\n\t\t\t\t\tif(i == n or char != pattern[i]):\n\t\t\t\t\t\treturn False\n\t\t\t\t\telse:\n\t\t\t\t\t\ti += 1\n\t\t\t\t\t\tc = c[char]\n\t\t\t\telse:\n\t\t\t\t\tif(i < n and char == pattern[i]):\n\t\t\t\t\t\ti += 1\n\t\t\t\t\tc = c[char]\n\t\t\treturn i==n\n\tt = Trie()\n\tfor word in queries: t.insert(word)\n\treturn [t.find(word) for word in queries]\n``` | 2 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
82% TC and 68% SC easy python solution | camelcase-matching | 0 | 1 | ```\ndef camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n\tclass Trie:\n\t\tdef __init__(self):\n\t\t\tself.root = dict()\n\t\tdef insert(self, word):\n\t\t\tc = self.root\n\t\t\tfor char in word:\n\t\t\t\tif(char not in c):\n\t\t\t\t\tc[char] = dict()\n\t\t\t\tc = c[char]\n\t\tdef find(self, word):\n\t\t\tc = self.root\n\t\t\ti = 0\n\t\t\tn = len(pattern)\n\t\t\tfor char in word:\n\t\t\t\tif(ord(char) < 97):\n\t\t\t\t\tif(i == n or char != pattern[i]):\n\t\t\t\t\t\treturn False\n\t\t\t\t\telse:\n\t\t\t\t\t\ti += 1\n\t\t\t\t\t\tc = c[char]\n\t\t\t\telse:\n\t\t\t\t\tif(i < n and char == pattern[i]):\n\t\t\t\t\t\ti += 1\n\t\t\t\t\tc = c[char]\n\t\t\treturn i==n\n\tt = Trie()\n\tfor word in queries: t.insert(word)\n\treturn [t.find(word) for word in queries]\n``` | 2 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
Python - Two Pointer - Memory usage less than 100% | camelcase-matching | 0 | 1 | ```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n \n def match(p, q):\n i = 0\n for j, c in enumerate(q):\n if i < len(p) and p[i] == q[j]: i += 1\n elif q[j].isupper(): return False\n return i == len(p)\n \n return [True if match(pattern, s) else False for s in queries]\n``` | 10 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
Python - Two Pointer - Memory usage less than 100% | camelcase-matching | 0 | 1 | ```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n \n def match(p, q):\n i = 0\n for j, c in enumerate(q):\n if i < len(p) and p[i] == q[j]: i += 1\n elif q[j].isupper(): return False\n return i == len(p)\n \n return [True if match(pattern, s) else False for s in queries]\n``` | 10 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
Python - 2 Pointers | camelcase-matching | 0 | 1 | # Code\n```python\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n def matches(query, pattern):\n j = 0\n for i in range(len(query)):\n # If the current character in the pattern matches the\n # current character in the query,\n # move to the next character in both the pattern and the query\n if j < len(pattern) and query[i] == pattern[j]:\n j += 1\n\n # If the current character in the query is uppercase and\n # does not match the current character in the pattern,\n # return False as this means there are extra uppercase letters that are not in the pattern\n elif query[i].isupper():\n return False\n return j == len(pattern)\n\n return [matches(query, pattern) for query in queries]\n```\n\n---\n\n\n# Complexity\nTime complexity: $$O(n * m)$$ [`n` is the number of queries & `m` is the average length of the queries]\n\nSpace complexity: $$O(1)$$\n\n---\n\n | 0 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
Python - 2 Pointers | camelcase-matching | 0 | 1 | # Code\n```python\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n def matches(query, pattern):\n j = 0\n for i in range(len(query)):\n # If the current character in the pattern matches the\n # current character in the query,\n # move to the next character in both the pattern and the query\n if j < len(pattern) and query[i] == pattern[j]:\n j += 1\n\n # If the current character in the query is uppercase and\n # does not match the current character in the pattern,\n # return False as this means there are extra uppercase letters that are not in the pattern\n elif query[i].isupper():\n return False\n return j == len(pattern)\n\n return [matches(query, pattern) for query in queries]\n```\n\n---\n\n\n# Complexity\nTime complexity: $$O(n * m)$$ [`n` is the number of queries & `m` is the average length of the queries]\n\nSpace complexity: $$O(1)$$\n\n---\n\n | 0 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
80% TC and 80% M Easy Solution for Beginners | camelcase-matching | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n def check(word, start):\n for i in range(start, len(word)):\n if word[i].isupper():\n return False\n return True\n \n l = []\n \n for word in queries:\n p1, p2 = 0, 0\n while p1 < len(word) and p2 < len(pattern):\n if word[p1] == pattern[p2]:\n p1 += 1\n p2 += 1\n else:\n if not word[p1].isupper() and pattern[p2].isupper():\n p1 += 1\n elif (word[p1].isupper() and pattern[p2].isupper()):\n break\n elif (not word[p1].isupper() and not pattern[p2].isupper()):\n p1+=1\n else:\n break\n\n if p2 == len(pattern) and check(word, p1):\n l.append(True)\n else:\n l.append(False)\n \n return l\n``` | 0 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
80% TC and 80% M Easy Solution for Beginners | camelcase-matching | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n def check(word, start):\n for i in range(start, len(word)):\n if word[i].isupper():\n return False\n return True\n \n l = []\n \n for word in queries:\n p1, p2 = 0, 0\n while p1 < len(word) and p2 < len(pattern):\n if word[p1] == pattern[p2]:\n p1 += 1\n p2 += 1\n else:\n if not word[p1].isupper() and pattern[p2].isupper():\n p1 += 1\n elif (word[p1].isupper() and pattern[p2].isupper()):\n break\n elif (not word[p1].isupper() and not pattern[p2].isupper()):\n p1+=1\n else:\n break\n\n if p2 == len(pattern) and check(word, p1):\n l.append(True)\n else:\n l.append(False)\n \n return l\n``` | 0 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
Python - Two Pointers | camelcase-matching | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen query[i] == pattern[j] increment both pointers. If there is a mismatch, then the only scenario where we reject is when query[i] is uppercase character, otherwise we keep matching by just incrementing our i pointer (query string pointer). At the end we need to make sure that we exhausted the pattern and there are no uppercase characters left in the query.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n n - len(queries), m - len(pattern), x - len(max(quereis[i]))\n O(n * (m + x))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n n, m = len(queries), len(pattern)\n lowercase = set([chr(i) for i in range(ord(\'a\'), ord(\'z\') + 1)])\n uppercase = set([chr(i) for i in range(ord(\'A\'), ord(\'Z\') + 1)])\n\n def is_match(q):\n l = len(q)\n i = j = 0\n while i < l and j < m:\n if q[i] == pattern[j]:\n i += 1\n j += 1\n else:\n if q[i] in uppercase:\n return False\n i += 1\n\n is_upper_case_present = False\n while i < l:\n if q[i] in uppercase:\n is_upper_case_present = True\n break\n i += 1\n \n return j == m and not is_upper_case_present\n\n res = []\n\n for query in queries:\n res.append(is_match(query))\n\n return res\n\n \n``` | 0 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.
**Example 1:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FB "
**Output:** \[true,false,true,true,false\]
**Explanation:** "FooBar " can be generated like this "F " + "oo " + "B " + "ar ".
"FootBall " can be generated like this "F " + "oot " + "B " + "all ".
"FrameBuffer " can be generated like this "F " + "rame " + "B " + "uffer ".
**Example 2:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBa "
**Output:** \[true,false,true,false,false\]
**Explanation:** "FooBar " can be generated like this "Fo " + "o " + "Ba " + "r ".
"FootBall " can be generated like this "Fo " + "ot " + "Ba " + "ll ".
**Example 3:**
**Input:** queries = \[ "FooBar ", "FooBarTest ", "FootBall ", "FrameBuffer ", "ForceFeedBack "\], pattern = "FoBaT "
**Output:** \[false,true,false,false,false\]
**Explanation:** "FooBarTest " can be generated like this "Fo " + "o " + "Ba " + "r " + "T " + "est ".
**Constraints:**
* `1 <= pattern.length, queries.length <= 100`
* `1 <= queries[i].length <= 100`
* `queries[i]` and `pattern` consist of English letters. | null |
Python - Two Pointers | camelcase-matching | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen query[i] == pattern[j] increment both pointers. If there is a mismatch, then the only scenario where we reject is when query[i] is uppercase character, otherwise we keep matching by just incrementing our i pointer (query string pointer). At the end we need to make sure that we exhausted the pattern and there are no uppercase characters left in the query.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n n - len(queries), m - len(pattern), x - len(max(quereis[i]))\n O(n * (m + x))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n n, m = len(queries), len(pattern)\n lowercase = set([chr(i) for i in range(ord(\'a\'), ord(\'z\') + 1)])\n uppercase = set([chr(i) for i in range(ord(\'A\'), ord(\'Z\') + 1)])\n\n def is_match(q):\n l = len(q)\n i = j = 0\n while i < l and j < m:\n if q[i] == pattern[j]:\n i += 1\n j += 1\n else:\n if q[i] in uppercase:\n return False\n i += 1\n\n is_upper_case_present = False\n while i < l:\n if q[i] in uppercase:\n is_upper_case_present = True\n break\n i += 1\n \n return j == m and not is_upper_case_present\n\n res = []\n\n for query in queries:\n res.append(is_match(query))\n\n return res\n\n \n``` | 0 | Given the `root` of a binary tree and an integer `limit`, delete all **insufficient nodes** in the tree simultaneously, and return _the root of the resulting binary tree_.
A node is **insufficient** if every root to **leaf** path intersecting this node has a sum strictly less than `limit`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14\], limit = 1
**Output:** \[1,2,3,4,null,null,7,8,9,null,14\]
**Example 2:**
**Input:** root = \[5,4,8,11,null,17,4,7,1,null,null,5,3\], limit = 22
**Output:** \[5,4,8,11,null,17,4,7,null,null,null,5\]
**Example 3:**
**Input:** root = \[1,2,-3,-5,null,4,null\], limit = -1
**Output:** \[1,null,-3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 5000]`.
* `-105 <= Node.val <= 105`
* `-109 <= limit <= 109` | Given a single pattern and word, how can we solve it? One way to do it is using a DP (pos1, pos2) where pos1 is a pointer to the word and pos2 to the pattern and returns true if we can match the pattern with the given word. We have two scenarios: The first one is when `word[pos1] == pattern[pos2]`, then the transition will be just DP(pos1 + 1, pos2 + 1). The second scenario is when `word[pos1]` is lowercase then we can add this character to the pattern so that the transition is just DP(pos1 + 1, pos2)
The case base is `if (pos1 == n && pos2 == m) return true;` Where n and m are the sizes of the strings word and pattern respectively. |
Solution | video-stitching | 1 | 1 | ```C++ []\nclass Solution {\n public:\n int videoStitching(vector<vector<int>>& clips, int time) {\n int ans = 0;\n int end = 0;\n int farthest = 0;\n\n sort(std::begin(clips), std::end(clips));\n\n int i = 0;\n while (farthest < time) {\n while (i < clips.size() && clips[i][0] <= end)\n farthest = max(farthest, clips[i++][1]);\n if (end == farthest)\n return -1;\n ++ans;\n end = farthest;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n stack = [[0,0]]\n for c in sorted(clips, key=lambda c: c[0]):\n while len(stack) > 1 and stack[-2][1] >= c[0] and stack[-1][1] < c[1]:\n stack.pop()\n if stack[-1][1] < c[0]: break\n if c[1] >= time: return len(stack)\n stack.append(c)\n return -1\n```\n\n```Java []\nclass Solution {\n public int videoStitching(int[][] clips, int time) {\n int min = 0;\n int max = 0;\n int total = 0;\n \n while(max<time) {\n \n for(int[] clip : clips) {\n int left = clip[0];\n int right = clip[1];\n \n if(left<=min && right >max) {\n max = right;\n }\n }\n if(min == max) {\n return -1;\n }\n min = max;\n total++;\n }\n return total;\n }\n}\n``` | 1 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Solution | video-stitching | 1 | 1 | ```C++ []\nclass Solution {\n public:\n int videoStitching(vector<vector<int>>& clips, int time) {\n int ans = 0;\n int end = 0;\n int farthest = 0;\n\n sort(std::begin(clips), std::end(clips));\n\n int i = 0;\n while (farthest < time) {\n while (i < clips.size() && clips[i][0] <= end)\n farthest = max(farthest, clips[i++][1]);\n if (end == farthest)\n return -1;\n ++ans;\n end = farthest;\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n stack = [[0,0]]\n for c in sorted(clips, key=lambda c: c[0]):\n while len(stack) > 1 and stack[-2][1] >= c[0] and stack[-1][1] < c[1]:\n stack.pop()\n if stack[-1][1] < c[0]: break\n if c[1] >= time: return len(stack)\n stack.append(c)\n return -1\n```\n\n```Java []\nclass Solution {\n public int videoStitching(int[][] clips, int time) {\n int min = 0;\n int max = 0;\n int total = 0;\n \n while(max<time) {\n \n for(int[] clip : clips) {\n int left = clip[0];\n int right = clip[1];\n \n if(left<=min && right >max) {\n max = right;\n }\n }\n if(min == max) {\n return -1;\n }\n min = max;\n total++;\n }\n return total;\n }\n}\n``` | 1 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
[Python] Greedy With Sorting - Comprehensive Explanation | video-stitching | 0 | 1 | # Intuition\n\nThe problem is to stitch video clips in a way that the resulting video covers the entire desired time, and we should use as few clips as possible. To achieve this, we need to select clips that start at or before the current end time and extend the video as far as possible.\n\n# Algorithm\n1. Sort the input clips based on their start times.\n2. Initialize num_clips to 0, current_end_time to 0, and i to 0.\n3. While i is less than the number of clips:\n a. If clips[i][0] is greater than current_end_time, return -1.\n b. Initialize max_end_time to current_end_time.\n c. While i is less than the number of clips and clips[i][0] is less than or equal to current_end_time:\n - i. Update max_end_time to the maximum of max_end_time and clips[i][1].\n - ii. Increment i.\nd. Increment num_clips.\ne. Update current_end_time to max_end_time.\nf. If current_end_time is greater than or equal to time, return num_clips.\n4. Return -1, as the video cannot be stitched to cover the entire desired time.\n\n# Complexity\n - Time complexity: $O(n \\cdot log(n))$, where $n$ is the number of clips. The sorting step has a time complexity of $O(n \\cdot log(n))$, and the rest of the algorithm takes\n\n- Space complexity: $O(1)$, since we only use a constant amount of additional space to store variables like num_clips, current_end_time, and max_end_time.\n\n# Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n clips.sort(key=lambda x: x[0]) \n\n num_clips = 0\n current_end_time = 0\n i = 0\n \n while i < len(clips):\n if clips[i][0] > current_end_time:\n return -1\n \n max_end_time = current_end_time\n while i < len(clips) and clips[i][0] <= current_end_time:\n max_end_time = max(max_end_time, clips[i][1])\n i += 1\n \n num_clips += 1\n current_end_time = max_end_time\n \n if current_end_time >= time:\n return num_clips\n \n return -1\n``` | 1 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
[Python] Greedy With Sorting - Comprehensive Explanation | video-stitching | 0 | 1 | # Intuition\n\nThe problem is to stitch video clips in a way that the resulting video covers the entire desired time, and we should use as few clips as possible. To achieve this, we need to select clips that start at or before the current end time and extend the video as far as possible.\n\n# Algorithm\n1. Sort the input clips based on their start times.\n2. Initialize num_clips to 0, current_end_time to 0, and i to 0.\n3. While i is less than the number of clips:\n a. If clips[i][0] is greater than current_end_time, return -1.\n b. Initialize max_end_time to current_end_time.\n c. While i is less than the number of clips and clips[i][0] is less than or equal to current_end_time:\n - i. Update max_end_time to the maximum of max_end_time and clips[i][1].\n - ii. Increment i.\nd. Increment num_clips.\ne. Update current_end_time to max_end_time.\nf. If current_end_time is greater than or equal to time, return num_clips.\n4. Return -1, as the video cannot be stitched to cover the entire desired time.\n\n# Complexity\n - Time complexity: $O(n \\cdot log(n))$, where $n$ is the number of clips. The sorting step has a time complexity of $O(n \\cdot log(n))$, and the rest of the algorithm takes\n\n- Space complexity: $O(1)$, since we only use a constant amount of additional space to store variables like num_clips, current_end_time, and max_end_time.\n\n# Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n clips.sort(key=lambda x: x[0]) \n\n num_clips = 0\n current_end_time = 0\n i = 0\n \n while i < len(clips):\n if clips[i][0] > current_end_time:\n return -1\n \n max_end_time = current_end_time\n while i < len(clips) and clips[i][0] <= current_end_time:\n max_end_time = max(max_end_time, clips[i][1])\n i += 1\n \n num_clips += 1\n current_end_time = max_end_time\n \n if current_end_time >= time:\n return num_clips\n \n return -1\n``` | 1 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
Python 3 || 11 lines, w/explanation || T/M: 98% / 81% | video-stitching | 0 | 1 | Here\'s the plan:\n- We sort `clip` by increasing `start` and then by decreasing `end` for those clips with same `start`.\n- We initiate `t` to keep track of the`end`of the most recent clip we use. If and when `t` equals or exceeds `time`, we return the number of clips. If we run out of clips before that happens, then we return `-1`.\n- We iterate through clips. First, grabbing the initial clip in the sorted list. Second, we discard all clips that end before that clip\'s`end`. \n- Third, we acrete all clips that start before `t` in `cSet`and then select from`cSet`the clip with the greatest`end`as the new most recent clip.\n- Fouth, we increment`ans`, flush`cSet`, and check whether we are finished.\n\nNote: Originally I checked whether a clip starting at zero did actually exist, but the code passed without the check, so I removed it.\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n\n clips.sort(key = lambda x: (x[0],-x[1]))\n t, cSet, ans = 0, set(), 0\n\n while clips:\n while clips and clips[0][1] <= t: clips.pop(0)\n while clips and clips[0][0] <= t: cSet.add(clips.pop(0)[1])\n\n if clips and not cSet: return -1\n t = max(cSet)\n ans+= 1\n if t >= time: return ans \n cSet.clear()\n\n return -1\n```\n[https://leetcode.com/problems/video-stitching/submissions/875736467/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is worstcase *O*(*N*). | 7 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python 3 || 11 lines, w/explanation || T/M: 98% / 81% | video-stitching | 0 | 1 | Here\'s the plan:\n- We sort `clip` by increasing `start` and then by decreasing `end` for those clips with same `start`.\n- We initiate `t` to keep track of the`end`of the most recent clip we use. If and when `t` equals or exceeds `time`, we return the number of clips. If we run out of clips before that happens, then we return `-1`.\n- We iterate through clips. First, grabbing the initial clip in the sorted list. Second, we discard all clips that end before that clip\'s`end`. \n- Third, we acrete all clips that start before `t` in `cSet`and then select from`cSet`the clip with the greatest`end`as the new most recent clip.\n- Fouth, we increment`ans`, flush`cSet`, and check whether we are finished.\n\nNote: Originally I checked whether a clip starting at zero did actually exist, but the code passed without the check, so I removed it.\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n\n clips.sort(key = lambda x: (x[0],-x[1]))\n t, cSet, ans = 0, set(), 0\n\n while clips:\n while clips and clips[0][1] <= t: clips.pop(0)\n while clips and clips[0][0] <= t: cSet.add(clips.pop(0)[1])\n\n if clips and not cSet: return -1\n t = max(cSet)\n ans+= 1\n if t >= time: return ans \n cSet.clear()\n\n return -1\n```\n[https://leetcode.com/problems/video-stitching/submissions/875736467/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*log*N*) and space complexity is worstcase *O*(*N*). | 7 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
py3 dp | video-stitching | 0 | 1 | # Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n clips.sort()\n n = len(clips)\n @cache\n def dp(pos,limit):\n if limit >= time:\n return 0\n if pos == n:\n return float(\'inf\') \n res = float(\'inf\')\n if clips[pos][0] > limit:\n return res\n elif clips[pos][0]<=limit and clips[pos][1] > limit:\n res = min(res,1+dp(pos+1,clips[pos][1]))\n res = min(res,dp(pos+1,limit))\n return res\n d = dp(0,0)\n return d if d < float(\'inf\') else -1\n\n\n \n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
py3 dp | video-stitching | 0 | 1 | # Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n clips.sort()\n n = len(clips)\n @cache\n def dp(pos,limit):\n if limit >= time:\n return 0\n if pos == n:\n return float(\'inf\') \n res = float(\'inf\')\n if clips[pos][0] > limit:\n return res\n elif clips[pos][0]<=limit and clips[pos][1] > limit:\n res = min(res,1+dp(pos+1,clips[pos][1]))\n res = min(res,dp(pos+1,limit))\n return res\n d = dp(0,0)\n return d if d < float(\'inf\') else -1\n\n\n \n``` | 0 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
Python Recurrent Solution Without Sorting or DP | video-stitching | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom initial 0 point, find the clip that includes the zero point with largest clip ending value. During the iteration, collect all the clips whose beginning point is large than the zero point. \n\nThen, update the zero point to the largest clip ending value, then provide the point with filtered clips to the same function. \n\nThe recursion stops when the new clip includes the target time to return number of recursion, or when there is no clip that updates the point to return -1.\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)$$ -->\n\n# Code\n```\nclass Solution:\n def dfs(self,clips,current,time,ct):\n d1 = []\n highest = current\n for clip in clips:\n if clip[0]<=current and current<=clip[1]:\n highest = max(highest,clip[1])\n if highest>=time: return ct+1\n elif clip[0]> current: \n d1.append(clip)\n if highest == current: return -1\n return self.dfs(d1,highest,time,ct+1)\n\n\n\n\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n return self.dfs(clips,0,time,0)\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python Recurrent Solution Without Sorting or DP | video-stitching | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom initial 0 point, find the clip that includes the zero point with largest clip ending value. During the iteration, collect all the clips whose beginning point is large than the zero point. \n\nThen, update the zero point to the largest clip ending value, then provide the point with filtered clips to the same function. \n\nThe recursion stops when the new clip includes the target time to return number of recursion, or when there is no clip that updates the point to return -1.\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)$$ -->\n\n# Code\n```\nclass Solution:\n def dfs(self,clips,current,time,ct):\n d1 = []\n highest = current\n for clip in clips:\n if clip[0]<=current and current<=clip[1]:\n highest = max(highest,clip[1])\n if highest>=time: return ct+1\n elif clip[0]> current: \n d1.append(clip)\n if highest == current: return -1\n return self.dfs(d1,highest,time,ct+1)\n\n\n\n\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n return self.dfs(clips,0,time,0)\n``` | 0 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
Sorting - O(nlogn) | video-stitching | 0 | 1 | # Complexity\n```\n- Time complexity: O(nlogn)\n- Space complexity: O(1)\n```\n# Code\n```\nclass Solution:\n def videoStitching(self, A: List[List[int]], N: int) -> int:\n A, H, p, mxe, R = sorted(A, key=lambda x: (x[0], -x[1])), [], 0, -1, 0\n for s, e in A:\n if p < s:\n if mxe == -1: return -1\n p, mxe, R = mxe, -1, R + 1\n \n if p < s: return -1\n mxe = max(mxe, e)\n if mxe >= N: return R + 1\n \n return -1\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Sorting - O(nlogn) | video-stitching | 0 | 1 | # Complexity\n```\n- Time complexity: O(nlogn)\n- Space complexity: O(1)\n```\n# Code\n```\nclass Solution:\n def videoStitching(self, A: List[List[int]], N: int) -> int:\n A, H, p, mxe, R = sorted(A, key=lambda x: (x[0], -x[1])), [], 0, -1, 0\n for s, e in A:\n if p < s:\n if mxe == -1: return -1\n p, mxe, R = mxe, -1, R + 1\n \n if p < s: return -1\n mxe = max(mxe, e)\n if mxe >= N: return R + 1\n \n return -1\n``` | 0 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
sort clip[0] in ascending when clip[0] same then clip[1] in descending order, then stack to check | video-stitching | 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)$$ -->\n\n# Code\n```\nclass Solution:\n # https://stackoverflow.com/a/14466141/7163137\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n # sorted(d,key=lambda x:(-x[1],x[0]))\n # (1) check edge case\n clips.sort(key=lambda clip:(clip[0], clip[1])) # O(nlogn)\n n = len(clips)\n # edge case when [[0,2],[1,1]], 2\n if clips[0][0] > 0: # or clips[n - 1][1] < time:\n return -1\n\n # (2) sort differnt clip[0] in asceding order, same clip[0] in reversed clip[1] descending order\n clips.sort(key=lambda clip:(clip[0], -clip[1])) # O(nlogn)\n stack = []\n for clip in clips:\n if not stack:\n stack.append(clip)\n continue\n\n # edge case, if the time come early\n if stack[-1][1] >= time:\n return len(stack)\n\n if stack[-1][0] == clip[0] or stack[-1][1] >= clip[1]:\n continue\n\n # edge case, cannot connected in the middle\n # should be < \n if stack[-1][1] < clip[0]:\n return -1\n \n while stack and stack[-1][1] < clip[1]:\n cur = stack.pop()\n if stack and stack[-1][1] >= clip[0]: # if the previous one has overlap with new one, we can skip cur\n stack.append(clip)\n else:\n stack.append(cur)\n stack.append(clip)\n\n return len(stack) if stack[-1][1] >= time else -1\n\n\n \n\n# (1) the time[1] always > time[0], so after we sorting as time[0], if the last one time[1] is less than time, or first one time[0] is greater than 0, return -1\n\n# [[0,9], [0,2], [1,9], [1,5], [4,6], [5,9], [8,10]]\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
sort clip[0] in ascending when clip[0] same then clip[1] in descending order, then stack to check | video-stitching | 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)$$ -->\n\n# Code\n```\nclass Solution:\n # https://stackoverflow.com/a/14466141/7163137\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n # sorted(d,key=lambda x:(-x[1],x[0]))\n # (1) check edge case\n clips.sort(key=lambda clip:(clip[0], clip[1])) # O(nlogn)\n n = len(clips)\n # edge case when [[0,2],[1,1]], 2\n if clips[0][0] > 0: # or clips[n - 1][1] < time:\n return -1\n\n # (2) sort differnt clip[0] in asceding order, same clip[0] in reversed clip[1] descending order\n clips.sort(key=lambda clip:(clip[0], -clip[1])) # O(nlogn)\n stack = []\n for clip in clips:\n if not stack:\n stack.append(clip)\n continue\n\n # edge case, if the time come early\n if stack[-1][1] >= time:\n return len(stack)\n\n if stack[-1][0] == clip[0] or stack[-1][1] >= clip[1]:\n continue\n\n # edge case, cannot connected in the middle\n # should be < \n if stack[-1][1] < clip[0]:\n return -1\n \n while stack and stack[-1][1] < clip[1]:\n cur = stack.pop()\n if stack and stack[-1][1] >= clip[0]: # if the previous one has overlap with new one, we can skip cur\n stack.append(clip)\n else:\n stack.append(cur)\n stack.append(clip)\n\n return len(stack) if stack[-1][1] >= time else -1\n\n\n \n\n# (1) the time[1] always > time[0], so after we sorting as time[0], if the last one time[1] is less than time, or first one time[0] is greater than 0, return -1\n\n# [[0,9], [0,2], [1,9], [1,5], [4,6], [5,9], [8,10]]\n``` | 0 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
Python O(n log n) sorting + two pointer method | video-stitching | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the clips array according to ascending start time. Also, append a sentinel to the end of the array. It can be anything, but make sure its `start time > time`.\n2. Set two pointers: `start = 0`, `end = -1`.\n3. Iterate over the clips.\n + If the current clip\'s start time is less than the `start` pointer, we check if its end time exceeds the current `end` pointer. (i.e. greedy method)\n + Else, we move forward by setting `start = end`. At the same time, we took into account the previous clip, so `cnt++`. Now, perform the check at this point. If the end pointer already covers the entire `time`, then just return the `cnt`. Otherwise., check if the current clip\'s start time is no later than the current `end` pointer. If so, there is a empty gap which can never be covered by those clips, so return `-1`.\n\n# Complexity\n- Time complexity: $O(n\\log n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n clips.sort()\n clips.append((time, time)) # sentinel\n cnt, start, end = 0, 0, -1\n\n i = 0\n while i < len(clips):\n s, e = clips[i]\n # If the start time is less than the start pivot\n # We greedily search for the latest end time possible\n if s <= start:\n end = max(end, e)\n i += 1\n\n # Otherwise, we need to make sure the new clip\'s start time\n # is no later than the end time of our previously selected\n # clip. Only in this situation, the invertals can overlap and\n # cover the range.\n else:\n start = end\n cnt += 1\n if end >= time:\n return cnt\n elif s > end:\n return -1\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Python O(n log n) sorting + two pointer method | video-stitching | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the clips array according to ascending start time. Also, append a sentinel to the end of the array. It can be anything, but make sure its `start time > time`.\n2. Set two pointers: `start = 0`, `end = -1`.\n3. Iterate over the clips.\n + If the current clip\'s start time is less than the `start` pointer, we check if its end time exceeds the current `end` pointer. (i.e. greedy method)\n + Else, we move forward by setting `start = end`. At the same time, we took into account the previous clip, so `cnt++`. Now, perform the check at this point. If the end pointer already covers the entire `time`, then just return the `cnt`. Otherwise., check if the current clip\'s start time is no later than the current `end` pointer. If so, there is a empty gap which can never be covered by those clips, so return `-1`.\n\n# Complexity\n- Time complexity: $O(n\\log n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n clips.sort()\n clips.append((time, time)) # sentinel\n cnt, start, end = 0, 0, -1\n\n i = 0\n while i < len(clips):\n s, e = clips[i]\n # If the start time is less than the start pivot\n # We greedily search for the latest end time possible\n if s <= start:\n end = max(end, e)\n i += 1\n\n # Otherwise, we need to make sure the new clip\'s start time\n # is no later than the end time of our previously selected\n # clip. Only in this situation, the invertals can overlap and\n # cover the range.\n else:\n start = end\n cnt += 1\n if end >= time:\n return cnt\n elif s > end:\n return -1\n``` | 0 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
Time:O(n); space: O(1) | video-stitching | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMaybe the code can be optimised.\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nOnly one extra space required\n\n# Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n # a <= cur, maximise b where (a, b)\n res = cur = i = 0\n clips.sort()\n while i < len(clips) and clips[i][0] <= cur and cur < time:\n nxt = cur\n while i < len(clips) and clips[i][0] <= cur:\n nxt = max(clips[i][1], nxt)\n i += 1\n res += 1\n cur = nxt\n return res if cur >= time else -1\n``` | 0 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
We can cut these clips into segments freely.
* For example, a clip `[0, 7]` can be cut into segments `[0, 1] + [1, 3] + [3, 7]`.
Return _the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event_ `[0, time]`. If the task is impossible, return `-1`.
**Example 1:**
**Input:** clips = \[\[0,2\],\[4,6\],\[8,10\],\[1,9\],\[1,5\],\[5,9\]\], time = 10
**Output:** 3
**Explanation:** We take the clips \[0,2\], \[8,10\], \[1,9\]; a total of 3 clips.
Then, we can reconstruct the sporting event as follows:
We cut \[1,9\] into segments \[1,2\] + \[2,8\] + \[8,9\].
Now we have segments \[0,2\] + \[2,8\] + \[8,10\] which cover the sporting event \[0, 10\].
**Example 2:**
**Input:** clips = \[\[0,1\],\[1,2\]\], time = 5
**Output:** -1
**Explanation:** We cannot cover \[0,5\] with only \[0,1\] and \[1,2\].
**Example 3:**
**Input:** clips = \[\[0,1\],\[6,8\],\[0,2\],\[5,6\],\[0,4\],\[0,3\],\[6,7\],\[1,3\],\[4,7\],\[1,4\],\[2,5\],\[2,6\],\[3,4\],\[4,5\],\[5,7\],\[6,9\]\], time = 9
**Output:** 3
**Explanation:** We can take clips \[0,4\], \[4,7\], and \[6,9\].
**Constraints:**
* `1 <= clips.length <= 100`
* `0 <= starti <= endi <= 100`
* `1 <= time <= 100`
0 <= i < j < k < nums.length, and nums\[i\] & nums\[j\] & nums\[k\] != 0. (\`&\` represents the bitwise AND operation.) | null |
Time:O(n); space: O(1) | video-stitching | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMaybe the code can be optimised.\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nOnly one extra space required\n\n# Code\n```\nclass Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n # a <= cur, maximise b where (a, b)\n res = cur = i = 0\n clips.sort()\n while i < len(clips) and clips[i][0] <= cur and cur < time:\n nxt = cur\n while i < len(clips) and clips[i][0] <= cur:\n nxt = max(clips[i][1], nxt)\n i += 1\n res += 1\n cur = nxt\n return res if cur >= time else -1\n``` | 0 | Given a string `s`, return _the_ _lexicographically smallest_ _subsequence_ _of_ `s` _that contains all the distinct characters of_ `s` _exactly once_.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 316: [https://leetcode.com/problems/remove-duplicate-letters/](https://leetcode.com/problems/remove-duplicate-letters/) | What if we sort the intervals? Considering the sorted intervals, how can we solve the problem with dynamic programming? Let's consider a DP(pos, limit) where pos represents the position of the current interval we are gonna take the decision and limit is the current covered area from [0 - limit]. This DP returns the minimum number of taken intervals or infinite if it's not possible to cover the [0 - T] section. |
Python One-Liner | Beats 97% | divisor-game | 0 | 1 | # Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return not n % 2\n``` | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Python One-Liner | Beats 97% | divisor-game | 0 | 1 | # Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n return not n % 2\n``` | 1 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` _and their **top five average**. Sort_ `result` _by_ `IDj` _in **increasing order**._
A student's **top five average** is calculated by taking the sum of their top five scores and dividing it by `5` using **integer division**.
**Example 1:**
**Input:** items = \[\[1,91\],\[1,92\],\[2,93\],\[2,97\],\[1,60\],\[2,77\],\[1,65\],\[1,87\],\[1,100\],\[2,100\],\[2,76\]\]
**Output:** \[\[1,87\],\[2,88\]\]
**Explanation:**
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
**Example 2:**
**Input:** items = \[\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\]\]
**Output:** \[\[1,100\],\[7,100\]\]
**Constraints:**
* `1 <= items.length <= 1000`
* `items[i].length == 2`
* `1 <= IDi <= 1000`
* `0 <= scorei <= 100`
* For each `IDi`, there will be **at least** five scores. | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
Very Easy Python Solution | divisor-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n if n%2==0:\n return True\n else:\n return False\n``` | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Very Easy Python Solution | divisor-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def divisorGame(self, n: int) -> bool:\n if n%2==0:\n return True\n else:\n return False\n``` | 1 | Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**.
Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` _and their **top five average**. Sort_ `result` _by_ `IDj` _in **increasing order**._
A student's **top five average** is calculated by taking the sum of their top five scores and dividing it by `5` using **integer division**.
**Example 1:**
**Input:** items = \[\[1,91\],\[1,92\],\[2,93\],\[2,97\],\[1,60\],\[2,77\],\[1,65\],\[1,87\],\[1,100\],\[2,100\],\[2,76\]\]
**Output:** \[\[1,87\],\[2,88\]\]
**Explanation:**
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
**Example 2:**
**Input:** items = \[\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\]\]
**Output:** \[\[1,100\],\[7,100\]\]
**Constraints:**
* `1 <= items.length <= 1000`
* `items[i].length == 2`
* `1 <= IDi <= 1000`
* `0 <= scorei <= 100`
* For each `IDi`, there will be **at least** five scores. | If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even. |
Solution in Python 3 (With Detailed Proof) | divisor-game | 0 | 1 | The proof of why this works can be done formally using Mathematical Induction, specifically using <a href="https://en.wikipedia.org/wiki/Mathematical_induction#Complete_(strong)_induction">Strong Mathematical Induction</a>. However an informal proof will also suffice. Note that it is not enough to show that a player who starts on even always wins. One must also show that a player that starts on odd always loses. Otherwise there are more possible ways to guarantee winning aside from starting on even.\n\n**Given:** The Divisor Game as outlined in the problem\n\n**Prove:** Alice will win if and only if N % 2 == 0\n\n_Part 1)_ If Alice starts with an even number she will always win.\n\nIf Alice has an even number, she can always subtract 1, giving Bob an odd number. Odd numbers are not divisible by 2. They are only divisible by odd numbers. Hence Bob must subtract an odd number. Since odd minus odd is even, Bob will always return an even number to Alice. Alice will thus get a smaller even number after each round of play and Bob will get a smaller odd number after each round of play. Eventually Bob will have to play the number 1 and will lose the game since he will have no options.\n\n_Part 2)_ If Alice starts with an odd number she will always lose.\n\nIf Alice has an odd number, she has no choice but to subtract an odd number as odd numbers have no even divisors. Thus Bob will get an even number. Now using the argument from _Part 1_ above, Bob can take this even number and keep giving an odd number back to Alice by subtracting 1. Thus Bob will always get to play even and Alice will always be stuck with an odd number smaller than her previous odd number after each round. Eventually Alice will have to play the number 1 and will lose the game since she will have no options.\n\nThus, assuming both players play optimally, Alice will win the game if and only if she starts on an even number (i.e. N % 2 == 0).\n```\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n return N % 2 == 0\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com | 177 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.