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 |
---|---|---|---|---|---|---|---|
Python O(N) bit manipulation - beats 100% | can-make-palindrome-from-substring | 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\'\'\'\nFirst how to check if a string rearranged can be a palindrome:\n1. If length is even, Counter(string) needs to yield even counts for all letters\n2. If length is odd, Counter(string) needs to yield even counts for all letters except one\n\nHow does replacement effect things?\nFind how many odd counts are off, if that number is higher than k(i)*2 then it cannot be a palindrome\n\nNow how to handle many queries in sub-quadratic time. Ideas:\n\n1. Keep running totals for all 26 letters? This will allow in O(26) time to get frequencies of all 26 lowercase English letters between i and j\n\nTime complexity: len(alphabet)*len(s) == 26*len(s) which is about same as a n log2(n) approach over 32 bit integer range. Over larger range this approach is asymptotically linear.\n\nImprovement: Also arguably don\'t even need to count frequencies? Can just use a bitmask to see if was_frequency_odd at a given time.\n\'\'\'\n\nfrom collections import Counter\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n counter = 0\n running_totals = []\n for c in s:\n counter ^= 1 << (ord(c) - ord(\'a\'))\n running_totals.append(counter)\n result = []\n for left, right, k in queries:\n frequencies = running_totals[right]\n if left > 0:\n frequencies ^= running_totals[left-1]\n result.append(k >= frequencies.bit_count() // 2)\n return result\n\n\n``` | 1 | You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`.
Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`.
Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`.
**Example :**
**Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\]
**Output:** \[true,false,false,true,true\]
**Explanation:**
queries\[0\]: substring = "d ", is palidrome.
queries\[1\]: substring = "bc ", is not palidrome.
queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character.
queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ".
queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome.
**Example 2:**
**Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\]
**Output:** \[false,true\]
**Constraints:**
* `1 <= s.length, queries.length <= 105`
* `0 <= lefti <= righti < s.length`
* `0 <= ki <= s.length`
* `s` consists of lowercase English letters. | Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter. |
Python O(N) bit manipulation - beats 100% | can-make-palindrome-from-substring | 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\'\'\'\nFirst how to check if a string rearranged can be a palindrome:\n1. If length is even, Counter(string) needs to yield even counts for all letters\n2. If length is odd, Counter(string) needs to yield even counts for all letters except one\n\nHow does replacement effect things?\nFind how many odd counts are off, if that number is higher than k(i)*2 then it cannot be a palindrome\n\nNow how to handle many queries in sub-quadratic time. Ideas:\n\n1. Keep running totals for all 26 letters? This will allow in O(26) time to get frequencies of all 26 lowercase English letters between i and j\n\nTime complexity: len(alphabet)*len(s) == 26*len(s) which is about same as a n log2(n) approach over 32 bit integer range. Over larger range this approach is asymptotically linear.\n\nImprovement: Also arguably don\'t even need to count frequencies? Can just use a bitmask to see if was_frequency_odd at a given time.\n\'\'\'\n\nfrom collections import Counter\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n counter = 0\n running_totals = []\n for c in s:\n counter ^= 1 << (ord(c) - ord(\'a\'))\n running_totals.append(counter)\n result = []\n for left, right, k in queries:\n frequencies = running_totals[right]\n if left > 0:\n frequencies ^= running_totals[left-1]\n result.append(k >= frequencies.bit_count() // 2)\n return result\n\n\n``` | 1 | Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5` | Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome. |
Python3 speed and space > 90% | can-make-palindrome-from-substring | 0 | 1 | # Intuition\nFor every query, we only need to know the number of every letter is even or odd in the substring to get minimum replacement needed. Because there is only 26 letters, we can use a int bitmask to store the parity of every letter in the string.\n# Approach\nUse another array mem with length len(s)+1 to store states of substring. Go through the string and for every char do mask ^= 1 << (char - \'a\'). mem[i] is the state of substring s[0: i-1], storing the parity of every letter in the substring.\n\nThen for every query, we get the state of s[left: right+1] from mem[right+1] ^ mem[left], for every replacement we are allowed to make, we eliminate 2 letter that are not even, if 1 or 0 letter are left as odd after all replacements, then it is a palindrome. n &= (n-1) set the last 1 bit to 0, which is setting an odd letter to even in this case.\n\n# Complexity\n- Time complexity:\nO(M+N), M is length of s and N is length of N\n\n- Space complexity:\nO(M)\n\n# Code\n```\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n l = len(s)\n mem = [0] * (l+1)\n mask = 0\n for i in range(l):\n idx = ord(s[i]) - ord(\'a\')\n mask ^= 1 << idx\n mem[i+1] = mask\n \n ans = [False] * len(queries)\n for i in range(len(queries)):\n left,right,k = queries[i]\n chars = mem[right+1] ^ mem[left]\n for j in range(k):\n if chars == 0:\n break\n chars &= (chars-1)\n chars &= (chars-1)\n chars &= (chars-1)\n if chars == 0:\n ans[i] = True\n \n return ans\n``` | 1 | You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`.
Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`.
Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`.
**Example :**
**Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\]
**Output:** \[true,false,false,true,true\]
**Explanation:**
queries\[0\]: substring = "d ", is palidrome.
queries\[1\]: substring = "bc ", is not palidrome.
queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character.
queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ".
queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome.
**Example 2:**
**Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\]
**Output:** \[false,true\]
**Constraints:**
* `1 <= s.length, queries.length <= 105`
* `0 <= lefti <= righti < s.length`
* `0 <= ki <= s.length`
* `s` consists of lowercase English letters. | Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter. |
Python3 speed and space > 90% | can-make-palindrome-from-substring | 0 | 1 | # Intuition\nFor every query, we only need to know the number of every letter is even or odd in the substring to get minimum replacement needed. Because there is only 26 letters, we can use a int bitmask to store the parity of every letter in the string.\n# Approach\nUse another array mem with length len(s)+1 to store states of substring. Go through the string and for every char do mask ^= 1 << (char - \'a\'). mem[i] is the state of substring s[0: i-1], storing the parity of every letter in the substring.\n\nThen for every query, we get the state of s[left: right+1] from mem[right+1] ^ mem[left], for every replacement we are allowed to make, we eliminate 2 letter that are not even, if 1 or 0 letter are left as odd after all replacements, then it is a palindrome. n &= (n-1) set the last 1 bit to 0, which is setting an odd letter to even in this case.\n\n# Complexity\n- Time complexity:\nO(M+N), M is length of s and N is length of N\n\n- Space complexity:\nO(M)\n\n# Code\n```\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n l = len(s)\n mem = [0] * (l+1)\n mask = 0\n for i in range(l):\n idx = ord(s[i]) - ord(\'a\')\n mask ^= 1 << idx\n mem[i+1] = mask\n \n ans = [False] * len(queries)\n for i in range(len(queries)):\n left,right,k = queries[i]\n chars = mem[right+1] ^ mem[left]\n for j in range(k):\n if chars == 0:\n break\n chars &= (chars-1)\n chars &= (chars-1)\n chars &= (chars-1)\n if chars == 0:\n ans[i] = True\n \n return ans\n``` | 1 | Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5` | Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome. |
Python3 + Bitmask / 10 lines / Beats 99.17% in Speed | can-make-palindrome-from-substring | 0 | 1 | # Code\n```\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n masks = [0]\n for i, c in enumerate(s):\n masks.append((1 << (ord(s[i]) - ord(\'a\'))) ^ masks[-1])\n \n ans = []\n for (l, r, k) in queries:\n ans.append(bin(masks[r + 1] ^ masks[l])[2:].count(\'1\') <= 2 * k + 1)\n return ans\n``` | 0 | You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`.
Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`.
Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`.
**Example :**
**Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\]
**Output:** \[true,false,false,true,true\]
**Explanation:**
queries\[0\]: substring = "d ", is palidrome.
queries\[1\]: substring = "bc ", is not palidrome.
queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character.
queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ".
queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome.
**Example 2:**
**Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\]
**Output:** \[false,true\]
**Constraints:**
* `1 <= s.length, queries.length <= 105`
* `0 <= lefti <= righti < s.length`
* `0 <= ki <= s.length`
* `s` consists of lowercase English letters. | Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter. |
Python3 + Bitmask / 10 lines / Beats 99.17% in Speed | can-make-palindrome-from-substring | 0 | 1 | # Code\n```\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n masks = [0]\n for i, c in enumerate(s):\n masks.append((1 << (ord(s[i]) - ord(\'a\'))) ^ masks[-1])\n \n ans = []\n for (l, r, k) in queries:\n ans.append(bin(masks[r + 1] ^ masks[l])[2:].count(\'1\') <= 2 * k + 1)\n return ans\n``` | 0 | Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5` | Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome. |
modified from another solution | can-make-palindrome-from-substring | 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\n# modified from solution 100% Python with Bit mask\n\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: list[list[int]]) -> list[bool]:\n mask = 0\n chardict = {chr(i): 1<<(i-ord("a")) for i in range(ord("a"), ord("z")+1)}\n result = []\n after_pass = [0] \n\n for i, char in enumerate(s):\n mask ^= chardict[char]\n after_pass += [mask]\n\n for i, (l,r,k) in enumerate(queries):\n if (r-l +1)//2 <=k:\n result += [True]\n else: \n num_odd = (after_pass[l] ^ after_pass[r+1]).bit_count()\n result += [num_odd//2 <= k]\n return result\n\n\n\n\n\n\n``` | 0 | You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`.
Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`.
Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`.
**Example :**
**Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\]
**Output:** \[true,false,false,true,true\]
**Explanation:**
queries\[0\]: substring = "d ", is palidrome.
queries\[1\]: substring = "bc ", is not palidrome.
queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character.
queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ".
queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome.
**Example 2:**
**Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\]
**Output:** \[false,true\]
**Constraints:**
* `1 <= s.length, queries.length <= 105`
* `0 <= lefti <= righti < s.length`
* `0 <= ki <= s.length`
* `s` consists of lowercase English letters. | Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter. |
modified from another solution | can-make-palindrome-from-substring | 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\n# modified from solution 100% Python with Bit mask\n\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: list[list[int]]) -> list[bool]:\n mask = 0\n chardict = {chr(i): 1<<(i-ord("a")) for i in range(ord("a"), ord("z")+1)}\n result = []\n after_pass = [0] \n\n for i, char in enumerate(s):\n mask ^= chardict[char]\n after_pass += [mask]\n\n for i, (l,r,k) in enumerate(queries):\n if (r-l +1)//2 <=k:\n result += [True]\n else: \n num_odd = (after_pass[l] ^ after_pass[r+1]).bit_count()\n result += [num_odd//2 <= k]\n return result\n\n\n\n\n\n\n``` | 0 | Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5` | Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome. |
100% Python with Bit mask | can-make-palindrome-from-substring | 0 | 1 | Check [my first submission](https://leetcode.com/problems/can-make-palindrome-from-substring/submissions/952532375/)\n\n\n# Intuition\n- focus on the not-paired characters\n\n# Approach\n- bit mask\n\n# Complexity\n- Time complexity: O(len(s)+len(queries))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(len(s)+len(queries))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# At first I thought this should be "hard" but since we can rearrange\n# the substring, we can focus on the not-paired characters.\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: list[list[int]]) -> list[bool]:\n mask = 0 # prefix-parity of each character,0 -> even, 1 -> odd\n parity_after = [0] * (len(s) + 1)\n d = {chr(i): 1 << (i - ord("a")) for i in range(ord("a"), ord("z") + 1)}\n for i, c in enumerate(s, start=1):\n mask ^= d[c]\n parity_after[i] = mask\n\n ans = [True] * len(queries)\n for i, (l, r, k) in enumerate(queries): # l, r inclusive\n if k >= (r - l + 1) // 2:\n continue\n odd = parity_after[r + 1] ^ parity_after[l] # mask of odd-parity\n ans[i] = (odd.bit_count()) // 2 <= k # count,ans: 3,1; 4,2; 5,2\n return ans\n\n\n``` | 0 | You are given a string `s` and array `queries` where `queries[i] = [lefti, righti, ki]`. We may rearrange the substring `s[lefti...righti]` for each query and then choose up to `ki` of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`. Otherwise, the result is `false`.
Return a boolean array `answer` where `answer[i]` is the result of the `ith` query `queries[i]`.
Note that each letter is counted individually for replacement, so if, for example `s[lefti...righti] = "aaa "`, and `ki = 2`, we can only replace two of the letters. Also, note that no query modifies the initial string `s`.
**Example :**
**Input:** s = "abcda ", queries = \[\[3,3,0\],\[1,2,0\],\[0,3,1\],\[0,3,2\],\[0,4,1\]\]
**Output:** \[true,false,false,true,true\]
**Explanation:**
queries\[0\]: substring = "d ", is palidrome.
queries\[1\]: substring = "bc ", is not palidrome.
queries\[2\]: substring = "abcd ", is not palidrome after replacing only 1 character.
queries\[3\]: substring = "abcd ", could be changed to "abba " which is palidrome. Also this can be changed to "baab " first rearrange it "bacd " then replace "cd " with "ab ".
queries\[4\]: substring = "abcda ", could be changed to "abcba " which is palidrome.
**Example 2:**
**Input:** s = "lyb ", queries = \[\[0,1,0\],\[2,2,1\]\]
**Output:** \[false,true\]
**Constraints:**
* `1 <= s.length, queries.length <= 105`
* `0 <= lefti <= righti < s.length`
* `0 <= ki <= s.length`
* `s` consists of lowercase English letters. | Start at any node A and traverse the tree to find the furthest node from it, let's call it B. Having found the furthest node B, traverse the tree from B to find the furthest node from it, lets call it C. The distance between B and C is the tree diameter. |
100% Python with Bit mask | can-make-palindrome-from-substring | 0 | 1 | Check [my first submission](https://leetcode.com/problems/can-make-palindrome-from-substring/submissions/952532375/)\n\n\n# Intuition\n- focus on the not-paired characters\n\n# Approach\n- bit mask\n\n# Complexity\n- Time complexity: O(len(s)+len(queries))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(len(s)+len(queries))\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# At first I thought this should be "hard" but since we can rearrange\n# the substring, we can focus on the not-paired characters.\nclass Solution:\n def canMakePaliQueries(self, s: str, queries: list[list[int]]) -> list[bool]:\n mask = 0 # prefix-parity of each character,0 -> even, 1 -> odd\n parity_after = [0] * (len(s) + 1)\n d = {chr(i): 1 << (i - ord("a")) for i in range(ord("a"), ord("z") + 1)}\n for i, c in enumerate(s, start=1):\n mask ^= d[c]\n parity_after[i] = mask\n\n ans = [True] * len(queries)\n for i, (l, r, k) in enumerate(queries): # l, r inclusive\n if k >= (r - l + 1) // 2:\n continue\n odd = parity_after[r + 1] ^ parity_after[l] # mask of odd-parity\n ans[i] = (odd.bit_count()) // 2 <= k # count,ans: 3,1; 4,2; 5,2\n return ans\n\n\n``` | 0 | Given an integer number `n`, return the difference between the product of its digits and the sum of its digits.
**Example 1:**
**Input:** n = 234
**Output:** 15
**Explanation:**
Product of digits = 2 \* 3 \* 4 = 24
Sum of digits = 2 + 3 + 4 = 9
Result = 24 - 9 = 15
**Example 2:**
**Input:** n = 4421
**Output:** 21
**Explanation:**
Product of digits = 4 \* 4 \* 2 \* 1 = 32
Sum of digits = 4 + 4 + 2 + 1 = 11
Result = 32 - 11 = 21
**Constraints:**
* `1 <= n <= 10^5` | Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome. |
[Python] Trie/Bitmasking Solutions with Explanation | number-of-valid-words-for-each-puzzle | 0 | 1 | ### Approach 1: Trie\n\nThis approach is more intuitive for working with sets of words. Essentially, we can perform the following:\n\n- Generate a Trie for all the given words in the input. (If you don\'t know what a Trie is or how it works, I suggest starting [here](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014).)\n\n```python\nclass TrieNode:\n\t"""This class represents a node in a Trie."""\n def __init__(self, ch: Optional[str] = \'\'):\n self.ch = ch # denotes the current character\n self.count = 0 # denotes how many words end here\n self.children = {} # denotes possible next characters\n\nclass Trie:\n\t"""This class represents the Trie itself."""\n def __init__(self):\n self.root = TrieNode()\n \n def add(self, word: str) -> None:\n\t\t"""Adding words into the Trie in linear time."""\n node = self.root\n for ch in word:\n if ch not in node.children.keys():\n node.children[ch] = TrieNode(ch)\n node = node.children[ch]\n node.count += 1\n```\n\n- Perform DFS search for each word in the given puzzles to see how many words in the Trie match.\n\n```python\nclass Trie:\n\t# as per ealier implementation...\n def search(self, word: str) -> int:\n\t\t"""DFS search for all words that are valid based on input."""\n def dfs(node: TrieNode, found: Optional[bool] = False) -> int:\n\t\t\t"""\n\t\t\tDFS algo search.\n\t\t\t:param node: The current node being searched.\n\t\t\t:param found: Flag to indicate if the first character has been found (validity criteria).\n\t\t\t:returns: The total number of valid words found.\n\t\t\t"""\n result = node.count*found # if there are words here, add them only if first character is found\n for ch in word:\n if ch in node.children.keys():\n\t\t\t\t\t# traverse through all valid next characters to find valid words\n result += dfs(node.children[ch], found or ch == word[0])\n return result\n return dfs(self.root)\n```\n\nThis gives us the following (long) implementation:\n\n```python\nclass TrieNode:\n def __init__(self, ch: Optional[str] = \'\'):\n self.ch = ch\n self.count = 0\n self.children = {}\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n \n def add(self, word: str) -> None:\n node = self.root\n for ch in word:\n if ch not in node.children.keys():\n node.children[ch] = TrieNode(ch)\n node = node.children[ch]\n node.count += 1\n \n def search(self, word: str) -> int: \n def dfs(node: TrieNode, found: Optional[bool] = False) -> int:\n result = node.count*found\n for ch in word:\n if ch in node.children.keys():\n result += dfs(node.children[ch], found or ch == word[0])\n return result\n return dfs(self.root)\n\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n trie = Trie()\n for word in words:\n trie.add(word)\n return [trie.search(word) for word in puzzles]\n```\n\nAs you can tell, the runtime and memory usage for the above solution isn\'t great (it barely passes both). [This post](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/371876/Detailed-Explanation-using-Trie-O(word_length-%2B-100*puzzle_length)) (with credit to [@Just__a__Visitor](https://leetcode.com/Just__a__Visitor/)) goes into much more detail as to why this is the case, if you are interested. It should also be noted that we can [implement the Trie more concisely](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/372368/Concise-python-trie-solution) (with credit to [@tclh123](https://leetcode.com/tclh123/)) which would significantly increase performance but still come out slow and less efficient overall. So, maybe Trie just isn\'t cut out for this problem after all.\n\n---\n\n### Approach 2: Bitmasking\n\nThis approach works by comparing masks instead of words, improving the comparison from O(mn) to O(1) time. The idea is that:\n\n- We generate masks for each word, and for each puzzle subsequently.\n\n```python\ndef mask(self, word: str) -> int:\n\t"""Generate mask for a given word."""\n\tresult = 0\n\tfor ch in word:\n\t\tresult |= 1 << (ord(ch)-ord(\'a\')) # [a-z] constraint\n\treturn result\n```\n\n- Iterating through each puzzle, we check if its mask matches any of the word masks. Then, we obtain the masks of each possible combination of letters in the puzzle, and check if those masks match.\n\nFor example, if the puzzle was \'abcdefg\', its mask would be `1111111` (omitting leading `0`s). Then, if a word only used the letters \'a\'-\'d\', we would expect its mask to be `0001111` which can be obtained from the puzzle mask by flipping the \'e\', \'f\' and \'g\' bits off (i.e. denoting not in use).\n\nThere is a clever way of iterating through all possible mask combinations of a 7-letter puzzle: `(curr_mask-1) & original_mask`. This turns the toggled bits in the mask off iteratively from the rightmost bit to the leftmost bit, while preserving the untoggled bits of the original mask. For example:\n\n```text\nPuzzle: \'ejkmv\'\n v\n zyxwvutsrqponmlkjihgfedcba\nOriginal: 00001001001001011000010000\n-1: 00001001001001011000001111\n&orig: 00001001001001011000000000\n ^\nSub-puzzle: \'jkmv\'\n```\n\nNote that the first letter of the puzzle has to be included in the words. Hence, to avoid toggling that letter off, we can generate the mask for the first letter and the rest of the puzzle word separately, and perform bitwise-OR afterward.\n\n```python\nclass Solution:\n def mask(self, word: str) -> int:\n result = 0\n for ch in word:\n result |= 1 << (ord(ch)-ord(\'a\'))\n return result\n\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n word_count = Counter(self.mask(word) for word in words)\n result = []\n for puzzle in puzzles:\n original_mask, first = self.mask(puzzle[1:]), self.mask(puzzle[0])\n curr_mask, count = original_mask, word_count[first]\n while curr_mask:\n count += word_count[curr_mask|first]\n curr_mask = (curr_mask-1)&original_mask\n result.append(count)\n return result\n```\n\n---\n\n### Final Result\n\n\n\nPlease upvote if this has helped you! Appreciate any comments as well :) | 16 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
[Python] Trie/Bitmasking Solutions with Explanation | number-of-valid-words-for-each-puzzle | 0 | 1 | ### Approach 1: Trie\n\nThis approach is more intuitive for working with sets of words. Essentially, we can perform the following:\n\n- Generate a Trie for all the given words in the input. (If you don\'t know what a Trie is or how it works, I suggest starting [here](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014).)\n\n```python\nclass TrieNode:\n\t"""This class represents a node in a Trie."""\n def __init__(self, ch: Optional[str] = \'\'):\n self.ch = ch # denotes the current character\n self.count = 0 # denotes how many words end here\n self.children = {} # denotes possible next characters\n\nclass Trie:\n\t"""This class represents the Trie itself."""\n def __init__(self):\n self.root = TrieNode()\n \n def add(self, word: str) -> None:\n\t\t"""Adding words into the Trie in linear time."""\n node = self.root\n for ch in word:\n if ch not in node.children.keys():\n node.children[ch] = TrieNode(ch)\n node = node.children[ch]\n node.count += 1\n```\n\n- Perform DFS search for each word in the given puzzles to see how many words in the Trie match.\n\n```python\nclass Trie:\n\t# as per ealier implementation...\n def search(self, word: str) -> int:\n\t\t"""DFS search for all words that are valid based on input."""\n def dfs(node: TrieNode, found: Optional[bool] = False) -> int:\n\t\t\t"""\n\t\t\tDFS algo search.\n\t\t\t:param node: The current node being searched.\n\t\t\t:param found: Flag to indicate if the first character has been found (validity criteria).\n\t\t\t:returns: The total number of valid words found.\n\t\t\t"""\n result = node.count*found # if there are words here, add them only if first character is found\n for ch in word:\n if ch in node.children.keys():\n\t\t\t\t\t# traverse through all valid next characters to find valid words\n result += dfs(node.children[ch], found or ch == word[0])\n return result\n return dfs(self.root)\n```\n\nThis gives us the following (long) implementation:\n\n```python\nclass TrieNode:\n def __init__(self, ch: Optional[str] = \'\'):\n self.ch = ch\n self.count = 0\n self.children = {}\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n \n def add(self, word: str) -> None:\n node = self.root\n for ch in word:\n if ch not in node.children.keys():\n node.children[ch] = TrieNode(ch)\n node = node.children[ch]\n node.count += 1\n \n def search(self, word: str) -> int: \n def dfs(node: TrieNode, found: Optional[bool] = False) -> int:\n result = node.count*found\n for ch in word:\n if ch in node.children.keys():\n result += dfs(node.children[ch], found or ch == word[0])\n return result\n return dfs(self.root)\n\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n trie = Trie()\n for word in words:\n trie.add(word)\n return [trie.search(word) for word in puzzles]\n```\n\nAs you can tell, the runtime and memory usage for the above solution isn\'t great (it barely passes both). [This post](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/371876/Detailed-Explanation-using-Trie-O(word_length-%2B-100*puzzle_length)) (with credit to [@Just__a__Visitor](https://leetcode.com/Just__a__Visitor/)) goes into much more detail as to why this is the case, if you are interested. It should also be noted that we can [implement the Trie more concisely](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/372368/Concise-python-trie-solution) (with credit to [@tclh123](https://leetcode.com/tclh123/)) which would significantly increase performance but still come out slow and less efficient overall. So, maybe Trie just isn\'t cut out for this problem after all.\n\n---\n\n### Approach 2: Bitmasking\n\nThis approach works by comparing masks instead of words, improving the comparison from O(mn) to O(1) time. The idea is that:\n\n- We generate masks for each word, and for each puzzle subsequently.\n\n```python\ndef mask(self, word: str) -> int:\n\t"""Generate mask for a given word."""\n\tresult = 0\n\tfor ch in word:\n\t\tresult |= 1 << (ord(ch)-ord(\'a\')) # [a-z] constraint\n\treturn result\n```\n\n- Iterating through each puzzle, we check if its mask matches any of the word masks. Then, we obtain the masks of each possible combination of letters in the puzzle, and check if those masks match.\n\nFor example, if the puzzle was \'abcdefg\', its mask would be `1111111` (omitting leading `0`s). Then, if a word only used the letters \'a\'-\'d\', we would expect its mask to be `0001111` which can be obtained from the puzzle mask by flipping the \'e\', \'f\' and \'g\' bits off (i.e. denoting not in use).\n\nThere is a clever way of iterating through all possible mask combinations of a 7-letter puzzle: `(curr_mask-1) & original_mask`. This turns the toggled bits in the mask off iteratively from the rightmost bit to the leftmost bit, while preserving the untoggled bits of the original mask. For example:\n\n```text\nPuzzle: \'ejkmv\'\n v\n zyxwvutsrqponmlkjihgfedcba\nOriginal: 00001001001001011000010000\n-1: 00001001001001011000001111\n&orig: 00001001001001011000000000\n ^\nSub-puzzle: \'jkmv\'\n```\n\nNote that the first letter of the puzzle has to be included in the words. Hence, to avoid toggling that letter off, we can generate the mask for the first letter and the rest of the puzzle word separately, and perform bitwise-OR afterward.\n\n```python\nclass Solution:\n def mask(self, word: str) -> int:\n result = 0\n for ch in word:\n result |= 1 << (ord(ch)-ord(\'a\'))\n return result\n\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n word_count = Counter(self.mask(word) for word in words)\n result = []\n for puzzle in puzzles:\n original_mask, first = self.mask(puzzle[1:]), self.mask(puzzle[0])\n curr_mask, count = original_mask, word_count[first]\n while curr_mask:\n count += word_count[curr_mask|first]\n curr_mask = (curr_mask-1)&original_mask\n result.append(count)\n return result\n```\n\n---\n\n### Final Result\n\n\n\nPlease upvote if this has helped you! Appreciate any comments as well :) | 16 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
Python solution. beats 100% | number-of-valid-words-for-each-puzzle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find the number of valid words for each puzzle in the list, we can create a dictionary where the keys are masks representing the unique characters in each word and the values are the number of occurrences of words with those characters. Then, for each puzzle, we can iterate through all possible subsets of the characters in the puzzle (excluding the first character) and check if the mask representing those characters is present in the dictionary. If it is, we can add the corresponding value to the total count. Finally, we can check if the first character of the puzzle is present in any of the words and add the corresponding value from the dictionary to the total count.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize an empty dictionary d.\n- Iterate through the list of words and for each word, create a mask representing the unique characters in the word by setting the corresponding bit in the mask to 1. For example, if the word has the characters \'a\', \'c\' and \'e\', the mask will be 111001.\n- If the mask is not present in the dictionary, set the value of the mask in the dictionary to 1. If it is present, increment the value by 1.\n- Initialize an empty result list ans.\n- Iterate through the list of puzzles and for each puzzle, create a mask representing the characters in the puzzle (excluding the first character) and store it in a variable mask.\n- Initialize a variable subset to the value of mask.\n- While subset is not 0, create a new mask representing the characters in the subset combined with the first character of the puzzle and store it in a variable s.\n- If s is present in the dictionary, add the corresponding value to the total count.\n- Update the value of subset to be the result of performing a bitwise AND operation between subset - 1 and mask.\n- If the mask representing the first character of the puzzle is present in the dictionary, add the corresponding value to the total count.\n- Append the total count to the result list.\n- Return the result list.\n# Complexity\n- Time complexity: O(n * 2^l)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nwhere n is the number of puzzles and l is the maximum length of any puzzle. This is because we have a loop that runs for all n puzzles and for each puzzle, we have a loop that runs for all 2^l possible subsets of the characters in the puzzle.\n\n\n- Space complexity: O(2^l) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nAs we use a dictionary to store the masks representing the unique characters in the words, and the maximum number of entries in the dictionary is 2^l.\n# Code\n```\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n d = {}\n for word in words:\n mask = 0\n for c in word:\n mask |= 1 << (ord(c) - ord(\'a\'))\n d[mask] = d.get(mask, 0) + 1\n ans = []\n for puzzle in puzzles:\n total = 0\n mask = 0\n for i in range(1, 7):\n mask |= 1 << (ord(puzzle[i]) - ord(\'a\'))\n subset = mask\n while subset:\n s = subset | (1 << (ord(puzzle[0]) - ord(\'a\')))\n if s in d:\n total += d[s]\n subset = (subset - 1) & mask\n if (1 << (ord(puzzle[0]) - ord(\'a\'))) in d:\n total += d[1 << (ord(puzzle[0]) - ord(\'a\'))]\n ans.append(total)\n return ans\n``` | 1 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
Python solution. beats 100% | number-of-valid-words-for-each-puzzle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find the number of valid words for each puzzle in the list, we can create a dictionary where the keys are masks representing the unique characters in each word and the values are the number of occurrences of words with those characters. Then, for each puzzle, we can iterate through all possible subsets of the characters in the puzzle (excluding the first character) and check if the mask representing those characters is present in the dictionary. If it is, we can add the corresponding value to the total count. Finally, we can check if the first character of the puzzle is present in any of the words and add the corresponding value from the dictionary to the total count.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialize an empty dictionary d.\n- Iterate through the list of words and for each word, create a mask representing the unique characters in the word by setting the corresponding bit in the mask to 1. For example, if the word has the characters \'a\', \'c\' and \'e\', the mask will be 111001.\n- If the mask is not present in the dictionary, set the value of the mask in the dictionary to 1. If it is present, increment the value by 1.\n- Initialize an empty result list ans.\n- Iterate through the list of puzzles and for each puzzle, create a mask representing the characters in the puzzle (excluding the first character) and store it in a variable mask.\n- Initialize a variable subset to the value of mask.\n- While subset is not 0, create a new mask representing the characters in the subset combined with the first character of the puzzle and store it in a variable s.\n- If s is present in the dictionary, add the corresponding value to the total count.\n- Update the value of subset to be the result of performing a bitwise AND operation between subset - 1 and mask.\n- If the mask representing the first character of the puzzle is present in the dictionary, add the corresponding value to the total count.\n- Append the total count to the result list.\n- Return the result list.\n# Complexity\n- Time complexity: O(n * 2^l)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nwhere n is the number of puzzles and l is the maximum length of any puzzle. This is because we have a loop that runs for all n puzzles and for each puzzle, we have a loop that runs for all 2^l possible subsets of the characters in the puzzle.\n\n\n- Space complexity: O(2^l) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nAs we use a dictionary to store the masks representing the unique characters in the words, and the maximum number of entries in the dictionary is 2^l.\n# Code\n```\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n d = {}\n for word in words:\n mask = 0\n for c in word:\n mask |= 1 << (ord(c) - ord(\'a\'))\n d[mask] = d.get(mask, 0) + 1\n ans = []\n for puzzle in puzzles:\n total = 0\n mask = 0\n for i in range(1, 7):\n mask |= 1 << (ord(puzzle[i]) - ord(\'a\'))\n subset = mask\n while subset:\n s = subset | (1 << (ord(puzzle[0]) - ord(\'a\')))\n if s in d:\n total += d[s]\n subset = (subset - 1) & mask\n if (1 << (ord(puzzle[0]) - ord(\'a\'))) in d:\n total += d[1 << (ord(puzzle[0]) - ord(\'a\'))]\n ans.append(total)\n return ans\n``` | 1 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
[Python] 26 Tries | number-of-valid-words-for-each-puzzle | 0 | 1 | **Approach:**\n\nMake an array (```trees```) of 26 Tries where ```trees[0]``` is a Trie that only \nhas words that contain the letter "a" and ```trees[25]``` is a Trie \nthat only has words that contain the letter "z". \n\n<details>\n\n<summary><b>Why?</b> (click to show)</summary>\n\n*This step is taken because the first letter of puzzle must appear in word\nso we want to group words that contain a specific letter:* ```puzzle[0]```\n\n</details>\n\nNext convert all words to a sorted set: "badfad" -> [\'a\', \'b\', \'d\', \'f\']\nAnd insert the sorted set into trees[0], trees[1], trees[3], and trees[5]\nbecause word contains the 1<sup>st</sup>, 2<sup>nd</sup>, 4<sup>th</sup>, and 6<sup>th</sup> letter of the alphabet.\n\n<details>\n\n<summary><b>Why?</b> (click to show)</summary>\n\n*The second condition in the problem description allows us to reuse \nletters from puzzle when checking if word is in puzzle. Since the\nword "aaaaaaaaaaa" is a subset of puzzle "a" we can reduce \neach word to a set.\n\n*The second thing to notice is that we sort the set. This is not\na necessary step, but it is an optimization. By sorting set(word) we\nsignificantly reduce the size of each Trie because there is a higher\nprobability of two words sharing the same node(s) in the Trie.*\n\n</details>\n\nLastly, for each puzzle perform a DFS in ```trees[ord(puzzle[0]) - 97]``` to find out\nhow many words are a subset of that puzzle.\n\n<details>\n\n<summary><b>Notes:</b> (click to show)</summary> \n\n*```ord(puzzle[0]) - 97``` is used because the integer representation of "a"\nis 97 (ord("a") = 97) and the integer representation of "z" is 122. So the \nminus 97 maps "a" to 0 and "z" to 25.*\n\n*We only perform a DFS search on ```trees[puzzle[0]]``` because this\nTrie only consists of words that contain puzzle[0] as a letter.*\n\n*When inserting words into a Trie, we mark the end of a word by\nincrementing node.tail by 1. This is because we may have multiple\nwords that are the same when doing sorted(set(word)). Furthermore\nthis allows us to count how many words are a subset of puzzle\nby adding node.tail as we traverse the Trie.*\n\n</details>\n\n<br>\n\n```python\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n words = [sorted(set(w)) for w in words]\n puzzles = [(p[0], set(p)) for p in puzzles]\n trees = [Trie() for _ in range(26)]\n for w in words:\n for char in w:\n trees[ord(char) - 97].insert(w)\n return [trees[ord(f) - 97].puzzle_match(p) for f,p in puzzles]\n\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.children = {}\n self.tail = 0\n \nclass Trie(object):\n def __init__(self):\n self.root = Node(None)\n \n def insert(self, word):\n curr = self.root\n for char in word:\n if char not in curr.children:\n curr.children[char] = Node(char)\n curr = curr.children[char]\n curr.tail += 1\n \n def puzzle_match(self, puzzle):\n def helper(node):\n nonlocal res\n res += node.tail\n for child in node.children:\n if child in puzzle:\n helper(node.children[child])\n res = 0\n helper(self.root)\n return res\n``` | 5 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
[Python] 26 Tries | number-of-valid-words-for-each-puzzle | 0 | 1 | **Approach:**\n\nMake an array (```trees```) of 26 Tries where ```trees[0]``` is a Trie that only \nhas words that contain the letter "a" and ```trees[25]``` is a Trie \nthat only has words that contain the letter "z". \n\n<details>\n\n<summary><b>Why?</b> (click to show)</summary>\n\n*This step is taken because the first letter of puzzle must appear in word\nso we want to group words that contain a specific letter:* ```puzzle[0]```\n\n</details>\n\nNext convert all words to a sorted set: "badfad" -> [\'a\', \'b\', \'d\', \'f\']\nAnd insert the sorted set into trees[0], trees[1], trees[3], and trees[5]\nbecause word contains the 1<sup>st</sup>, 2<sup>nd</sup>, 4<sup>th</sup>, and 6<sup>th</sup> letter of the alphabet.\n\n<details>\n\n<summary><b>Why?</b> (click to show)</summary>\n\n*The second condition in the problem description allows us to reuse \nletters from puzzle when checking if word is in puzzle. Since the\nword "aaaaaaaaaaa" is a subset of puzzle "a" we can reduce \neach word to a set.\n\n*The second thing to notice is that we sort the set. This is not\na necessary step, but it is an optimization. By sorting set(word) we\nsignificantly reduce the size of each Trie because there is a higher\nprobability of two words sharing the same node(s) in the Trie.*\n\n</details>\n\nLastly, for each puzzle perform a DFS in ```trees[ord(puzzle[0]) - 97]``` to find out\nhow many words are a subset of that puzzle.\n\n<details>\n\n<summary><b>Notes:</b> (click to show)</summary> \n\n*```ord(puzzle[0]) - 97``` is used because the integer representation of "a"\nis 97 (ord("a") = 97) and the integer representation of "z" is 122. So the \nminus 97 maps "a" to 0 and "z" to 25.*\n\n*We only perform a DFS search on ```trees[puzzle[0]]``` because this\nTrie only consists of words that contain puzzle[0] as a letter.*\n\n*When inserting words into a Trie, we mark the end of a word by\nincrementing node.tail by 1. This is because we may have multiple\nwords that are the same when doing sorted(set(word)). Furthermore\nthis allows us to count how many words are a subset of puzzle\nby adding node.tail as we traverse the Trie.*\n\n</details>\n\n<br>\n\n```python\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n words = [sorted(set(w)) for w in words]\n puzzles = [(p[0], set(p)) for p in puzzles]\n trees = [Trie() for _ in range(26)]\n for w in words:\n for char in w:\n trees[ord(char) - 97].insert(w)\n return [trees[ord(f) - 97].puzzle_match(p) for f,p in puzzles]\n\nclass Node(object):\n def __init__(self, val):\n self.val = val\n self.children = {}\n self.tail = 0\n \nclass Trie(object):\n def __init__(self):\n self.root = Node(None)\n \n def insert(self, word):\n curr = self.root\n for char in word:\n if char not in curr.children:\n curr.children[char] = Node(char)\n curr = curr.children[char]\n curr.tail += 1\n \n def puzzle_match(self, puzzle):\n def helper(node):\n nonlocal res\n res += node.tail\n for child in node.children:\n if child in puzzle:\n helper(node.children[child])\n res = 0\n helper(self.root)\n return res\n``` | 5 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
Python 3 FT 90%: TC O(W+P * min(2^L, W)), SC O(W): Trie with Ordered Entries | number-of-valid-words-for-each-puzzle | 0 | 1 | # Intuition\n\nThere\'s an easier bit masking solution. The idea is you encode words as 26 bit integers, with a 1 if there\'s at least one copy of each corresponding character, and 0 otherwise. Then you start with `puzzleEncoding` and do a "masked decrement" to zero to find all `wordEncoding`s with those bits, and add them up.\n\nBut this one is good recursion practice, and also seems to be faster based on the runtime. And more efficient if there are relatively few words.\n\nThe idea is this:\n1. sort the unique characters in each word\n2. then add the resulting sorted string to a prefix trie\n3. then for each query:\n * find characters at the root of the trie in the query, and recurse on them. If we see the first character of the query, set `seenFirst=True`\n * for each node, if we\'ve `seenFirst`, add the number of strings that end at this node\n * then for each child for a character in `seenFirst`, recurse on it\n\nIn this way\n* the tree is at most 26 levels deep, one for each unique character. Hence the tree taking only O(W) space for W words\n* we recurse on at most 2^L or so nodes, because the words in the tree are sorted, and there are at most L characters in each puzzle. The recursion is equivalent to look at all words with or without each character in the query\n\n# Approach\n\nThe code has a simple trie implementation where each node is an instance of `Node`. The root is just the first `Node`. The `add` method makes it easy to add things to the trie. Each `Node` records the number of words ending at that node.\n\nThe search is a DFS function that has the current node to search from (representing a prefix in the sorted unique characters), and a boolean `hasFirst` that records if we\'ve seen the first character of the query thus far.\n\nSorting the unique characters of each word before adding it to the tree reduces the space taken by the tree, and lets the search run in at most 2^L steps for a query of length L. The most nodes that can be visited though are O(W) though because that\'s the total number of nodes. So the time complexity for each query is the smaller of 2^L or W.\n\n# Complexity\n- Time complexity: $O(W + P \\min{(2^L, W)})$\n - $W$ is the number of words\n - $P$ is the number of puzzles\n - $2^L$ is the max number of characters in each query\n - the leading $W$ comes from building the prefix trie\n - the trailing `min` part is because `count` visits at most `2^L` nodes for a query of length `L`. But it obviously can\'t visit more than all of the O(W) nodes in the trie. So it visits the lesser of $2^L$ and $O(W)$\n\n- Space complexity: $O(W)$, for the prefix trie.\n - the search part takes O(1) memory because each level of the DFS path corresponds to a word with one more letter, and there\'s a maximum of $L$ letters if the longest query is $L$. We only have lower-case letters so $L$ is at most 26, or O(1).\n\n# Code\n```\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n # want count(w) | w in words and satisfies(p, p) for each p in puzzles\n\n # satisfies(w, p):\n # > w contains p[0]\n # > p contains all chars in w; p can have more characters though\n\n # lowercase letters only\n\n # can answer `includes` in O(1) with a bitset\n\n # W ~ 1e5, P ~ 1e4.\n # O(P W) is too many, uh-oh.\n \n # Each puzzle has up to 7 characters, all unique. That helps probably.\n # Each word has up to 26 characters, can we store 26 choose 7?\n # Yup, 26 choose 1 to 26 choose 7 is about 1e6, doable\n \n # But what do we do with that? That would give us the count of words meeting the second criterion\n # The first criterion \n\n # So bitset stuff isn\'t helping.\n # What about a trie structure?\n \n # If we had a trie of words based on unique letters: root -> withA and -> withoutA children\n # For chars \'a\' .. \'z\':\n # if c is p[0]: take only the branch with has(c); words must have p[0]\n # elif c is in p: take both branches, word having a copy of c is optional\n # else: take only the branches without c, word can\'t have chars outside\n \n # So max branching is 2**7 << 1000 so this will work!\n # BUT: the trie as I\'ve written here needs all 2**26 nodes, which is just too many nodes. MLE.\n \n\n # class Node:\n # def __init__(self, c: chr):\n # self.c = c\n # self.count = 0\n # self.children = {}\n\n # def create(self, c: chr):\n # if c in self.children:\n # return self.children[c]\n # else:\n # n = Node(c)\n # self.children[c] = n\n # return n\n\n # def get(self, c: chr):\n # return self.children.get(c, None)\n\n # root = Node(\'!\')\n # for w in words:\n # curr = root\n # uniques = set(w)\n # for c in str.lower:\n # curr = curr.create(c)\n \n\n # What if we do a trie on the sorted chars of each word?\n # apple => aelp is in trie\n #\n # and suppose the puzzle as cdefg\n # word must have c: so follow the c branch\n # word can\'t have letters that are not cdefg, so only follow those paths\n\n # so root\n # c: MUST follow c\n # d: optional\n # e: optional\n\n # What does "optional" mean exactly? It means from the node for !a !b c:\n # add the count of the current node, words that have just letters up to this point (if we\'ve traversed the required word)\n # follow any children from c that correspond to letters defg and that\'s it\n\n class Node:\n def __init__(self):\n self.count = 0 # words that end with this char\n self.children = {} # chr -> child node(s)\n\n def add(self, c: chr):\n n = self.children.get(c, None)\n\n if n: return n\n\n n = Node()\n self.children[c] = n\n return n\n\n root = Node()\n for w in words:\n uniques = list(set(w))\n uniques.sort()\n curr = root\n for c in uniques:\n curr = curr.add(c)\n\n curr.count += 1\n\n def count(q: str, n: \'Node\', hasFirst: bool = False) -> int:\n """Returns count of words that have q[0], and only have the chars in q"""\n\n ans = 0\n if hasFirst: ans += n.count\n\n for c, child in n.children.items():\n if c not in q: continue # don\'t use words that have other chars outside q\n\n ans += count(q, child, hasFirst or c == q[0])\n\n return ans\n\n return [count(q, root, False) for q in puzzles]\n\n``` | 0 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
Python 3 FT 90%: TC O(W+P * min(2^L, W)), SC O(W): Trie with Ordered Entries | number-of-valid-words-for-each-puzzle | 0 | 1 | # Intuition\n\nThere\'s an easier bit masking solution. The idea is you encode words as 26 bit integers, with a 1 if there\'s at least one copy of each corresponding character, and 0 otherwise. Then you start with `puzzleEncoding` and do a "masked decrement" to zero to find all `wordEncoding`s with those bits, and add them up.\n\nBut this one is good recursion practice, and also seems to be faster based on the runtime. And more efficient if there are relatively few words.\n\nThe idea is this:\n1. sort the unique characters in each word\n2. then add the resulting sorted string to a prefix trie\n3. then for each query:\n * find characters at the root of the trie in the query, and recurse on them. If we see the first character of the query, set `seenFirst=True`\n * for each node, if we\'ve `seenFirst`, add the number of strings that end at this node\n * then for each child for a character in `seenFirst`, recurse on it\n\nIn this way\n* the tree is at most 26 levels deep, one for each unique character. Hence the tree taking only O(W) space for W words\n* we recurse on at most 2^L or so nodes, because the words in the tree are sorted, and there are at most L characters in each puzzle. The recursion is equivalent to look at all words with or without each character in the query\n\n# Approach\n\nThe code has a simple trie implementation where each node is an instance of `Node`. The root is just the first `Node`. The `add` method makes it easy to add things to the trie. Each `Node` records the number of words ending at that node.\n\nThe search is a DFS function that has the current node to search from (representing a prefix in the sorted unique characters), and a boolean `hasFirst` that records if we\'ve seen the first character of the query thus far.\n\nSorting the unique characters of each word before adding it to the tree reduces the space taken by the tree, and lets the search run in at most 2^L steps for a query of length L. The most nodes that can be visited though are O(W) though because that\'s the total number of nodes. So the time complexity for each query is the smaller of 2^L or W.\n\n# Complexity\n- Time complexity: $O(W + P \\min{(2^L, W)})$\n - $W$ is the number of words\n - $P$ is the number of puzzles\n - $2^L$ is the max number of characters in each query\n - the leading $W$ comes from building the prefix trie\n - the trailing `min` part is because `count` visits at most `2^L` nodes for a query of length `L`. But it obviously can\'t visit more than all of the O(W) nodes in the trie. So it visits the lesser of $2^L$ and $O(W)$\n\n- Space complexity: $O(W)$, for the prefix trie.\n - the search part takes O(1) memory because each level of the DFS path corresponds to a word with one more letter, and there\'s a maximum of $L$ letters if the longest query is $L$. We only have lower-case letters so $L$ is at most 26, or O(1).\n\n# Code\n```\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n # want count(w) | w in words and satisfies(p, p) for each p in puzzles\n\n # satisfies(w, p):\n # > w contains p[0]\n # > p contains all chars in w; p can have more characters though\n\n # lowercase letters only\n\n # can answer `includes` in O(1) with a bitset\n\n # W ~ 1e5, P ~ 1e4.\n # O(P W) is too many, uh-oh.\n \n # Each puzzle has up to 7 characters, all unique. That helps probably.\n # Each word has up to 26 characters, can we store 26 choose 7?\n # Yup, 26 choose 1 to 26 choose 7 is about 1e6, doable\n \n # But what do we do with that? That would give us the count of words meeting the second criterion\n # The first criterion \n\n # So bitset stuff isn\'t helping.\n # What about a trie structure?\n \n # If we had a trie of words based on unique letters: root -> withA and -> withoutA children\n # For chars \'a\' .. \'z\':\n # if c is p[0]: take only the branch with has(c); words must have p[0]\n # elif c is in p: take both branches, word having a copy of c is optional\n # else: take only the branches without c, word can\'t have chars outside\n \n # So max branching is 2**7 << 1000 so this will work!\n # BUT: the trie as I\'ve written here needs all 2**26 nodes, which is just too many nodes. MLE.\n \n\n # class Node:\n # def __init__(self, c: chr):\n # self.c = c\n # self.count = 0\n # self.children = {}\n\n # def create(self, c: chr):\n # if c in self.children:\n # return self.children[c]\n # else:\n # n = Node(c)\n # self.children[c] = n\n # return n\n\n # def get(self, c: chr):\n # return self.children.get(c, None)\n\n # root = Node(\'!\')\n # for w in words:\n # curr = root\n # uniques = set(w)\n # for c in str.lower:\n # curr = curr.create(c)\n \n\n # What if we do a trie on the sorted chars of each word?\n # apple => aelp is in trie\n #\n # and suppose the puzzle as cdefg\n # word must have c: so follow the c branch\n # word can\'t have letters that are not cdefg, so only follow those paths\n\n # so root\n # c: MUST follow c\n # d: optional\n # e: optional\n\n # What does "optional" mean exactly? It means from the node for !a !b c:\n # add the count of the current node, words that have just letters up to this point (if we\'ve traversed the required word)\n # follow any children from c that correspond to letters defg and that\'s it\n\n class Node:\n def __init__(self):\n self.count = 0 # words that end with this char\n self.children = {} # chr -> child node(s)\n\n def add(self, c: chr):\n n = self.children.get(c, None)\n\n if n: return n\n\n n = Node()\n self.children[c] = n\n return n\n\n root = Node()\n for w in words:\n uniques = list(set(w))\n uniques.sort()\n curr = root\n for c in uniques:\n curr = curr.add(c)\n\n curr.count += 1\n\n def count(q: str, n: \'Node\', hasFirst: bool = False) -> int:\n """Returns count of words that have q[0], and only have the chars in q"""\n\n ans = 0\n if hasFirst: ans += n.count\n\n for c, child in n.children.items():\n if c not in q: continue # don\'t use words that have other chars outside q\n\n ans += count(q, child, hasFirst or c == q[0])\n\n return ans\n\n return [count(q, root, False) for q in puzzles]\n\n``` | 0 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
Python - 9 line tidy code using itertools and Counter. | number-of-valid-words-for-each-puzzle | 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```\nfrom collections import Counter\nfrom itertools import combinations\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n frequencies = Counter(map(frozenset, words))\n result = []\n for puzzle, first_letter in zip(map(set, puzzles), map(lambda x: x[0], puzzles)):\n puzzle.remove(first_letter)\n valid = frequencies.get(frozenset(first_letter), 0)\n for i in range(1, len(puzzle)+1):\n for combo in combinations(puzzle, i):\n valid += frequencies.get(frozenset(combo + (first_letter,)), 0)\n result.append(valid) \n return result\n``` | 0 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
Python - 9 line tidy code using itertools and Counter. | number-of-valid-words-for-each-puzzle | 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```\nfrom collections import Counter\nfrom itertools import combinations\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n frequencies = Counter(map(frozenset, words))\n result = []\n for puzzle, first_letter in zip(map(set, puzzles), map(lambda x: x[0], puzzles)):\n puzzle.remove(first_letter)\n valid = frequencies.get(frozenset(first_letter), 0)\n for i in range(1, len(puzzle)+1):\n for combo in combinations(puzzle, i):\n valid += frequencies.get(frozenset(combo + (first_letter,)), 0)\n result.append(valid) \n return result\n``` | 0 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
Python Solution using binary search | number-of-valid-words-for-each-puzzle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(64*M log(N))\n- where M:- 10^4 and N:- 10^5\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 findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n l=[]\n for i in range(len(words)):\n s=0\n for j in words[i]:\n s=s|(1<<(ord(j))-97)\n l+=[s]\n l.sort()\n ans=[]\n for i in range(len(puzzles)):\n s=0\n l1=[]\n for j in puzzles[i]:\n s=s|(1<<(ord(j))-97)\n l1+=[ord(j)-97]\n b1=bisect.bisect_right(l,2**l1[0]-1)\n b2=bisect.bisect_left(l,2**l1[0]+1)\n c=b2-b1\n a=l1.pop(0)\n for k in range(1,2**(len(l1))):\n s1=2**a\n count=0\n while k!=0:\n if k&1!=0:\n s1+=2**l1[count]\n k=k>>1\n count+=1\n b1=bisect.bisect_right(l,s1-1)\n b2=bisect.bisect_left(l,s1+1)\n c+=b2-b1\n ans+=[c]\n return ans\n``` | 0 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
Python Solution using binary search | number-of-valid-words-for-each-puzzle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(64*M log(N))\n- where M:- 10^4 and N:- 10^5\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 findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n l=[]\n for i in range(len(words)):\n s=0\n for j in words[i]:\n s=s|(1<<(ord(j))-97)\n l+=[s]\n l.sort()\n ans=[]\n for i in range(len(puzzles)):\n s=0\n l1=[]\n for j in puzzles[i]:\n s=s|(1<<(ord(j))-97)\n l1+=[ord(j)-97]\n b1=bisect.bisect_right(l,2**l1[0]-1)\n b2=bisect.bisect_left(l,2**l1[0]+1)\n c=b2-b1\n a=l1.pop(0)\n for k in range(1,2**(len(l1))):\n s1=2**a\n count=0\n while k!=0:\n if k&1!=0:\n s1+=2**l1[count]\n k=k>>1\n count+=1\n b1=bisect.bisect_right(l,s1-1)\n b2=bisect.bisect_left(l,s1+1)\n c+=b2-b1\n ans+=[c]\n return ans\n``` | 0 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
Without Bitmasking and Trie, Optimization || Python 3 | number-of-valid-words-for-each-puzzle | 0 | 1 | # Code\n```\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n\n words = ["".join(sorted(set(w))) for w in words]\n ct = Counter(words)\n words = [set(w) for w in list(set(words))]\n\n dt = defaultdict(lambda: [])\n for ws in words:\n for c in list(ws):\n dt[c].append(ws)\n\n res = []\n for p in puzzles:\n t = 0\n ps = set(p)\n for ws in dt[p[0]]:\n if ws.issubset(ps):\n t += ct["".join(sorted(list(ws)))] \n res.append(t)\n \n return res\n\n\n``` | 0 | With respect to a given `puzzle` string, a `word` is _valid_ if both the following conditions are satisfied:
* `word` contains the first letter of `puzzle`.
* For each letter in `word`, that letter is in `puzzle`.
* For example, if the puzzle is `"abcdefg "`, then valid words are `"faced "`, `"cabbage "`, and `"baggage "`, while
* invalid words are `"beefed "` (does not include `'a'`) and `"based "` (includes `'s'` which is not in the puzzle).
Return _an array_ `answer`_, where_ `answer[i]` _is the number of words in the given word list_ `words` _that is valid with respect to the puzzle_ `puzzles[i]`.
**Example 1:**
**Input:** words = \[ "aaaa ", "asas ", "able ", "ability ", "actt ", "actor ", "access "\], puzzles = \[ "aboveyz ", "abrodyz ", "abslute ", "absoryz ", "actresz ", "gaswxyz "\]
**Output:** \[1,1,3,2,4,0\]
**Explanation:**
1 valid word for "aboveyz " : "aaaa "
1 valid word for "abrodyz " : "aaaa "
3 valid words for "abslute " : "aaaa ", "asas ", "able "
2 valid words for "absoryz " : "aaaa ", "asas "
4 valid words for "actresz " : "aaaa ", "asas ", "actt ", "access "
There are no valid words for "gaswxyz " cause none of the words in the list contains letter 'g'.
**Example 2:**
**Input:** words = \[ "apple ", "pleas ", "please "\], puzzles = \[ "aelwxyz ", "aelpxyz ", "aelpsxy ", "saelpxy ", "xaelpsy "\]
**Output:** \[0,1,3,2,0\]
**Constraints:**
* `1 <= words.length <= 105`
* `4 <= words[i].length <= 50`
* `1 <= puzzles.length <= 104`
* `puzzles[i].length == 7`
* `words[i]` and `puzzles[i]` consist of lowercase English letters.
* Each `puzzles[i]` does not contain repeated characters. | Can you reduce this problem to a classic problem? The problem is equivalent to finding any palindromic subsequence of length at least N-K where N is the length of the string. Try to find the longest palindromic subsequence. Use DP to do that. |
Without Bitmasking and Trie, Optimization || Python 3 | number-of-valid-words-for-each-puzzle | 0 | 1 | # Code\n```\nclass Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n\n words = ["".join(sorted(set(w))) for w in words]\n ct = Counter(words)\n words = [set(w) for w in list(set(words))]\n\n dt = defaultdict(lambda: [])\n for ws in words:\n for c in list(ws):\n dt[c].append(ws)\n\n res = []\n for p in puzzles:\n t = 0\n ps = set(p)\n for ws in dt[p[0]]:\n if ws.issubset(ps):\n t += ct["".join(sorted(list(ws)))] \n res.append(t)\n \n return res\n\n\n``` | 0 | There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n` | Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask. |
[Python3] Good enough | distance-between-bus-stops | 0 | 1 | ``` Python3 []\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n minn = min(start, destination)\n maxx = max(start, destination)\n return min(sum(distance[minn:maxx]), sum(distance[:minn] + distance[maxx:]))\n``` | 3 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given `start` and `destination` stops.
**Example 1:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.
**Example 2:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.
**Example 3:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.
**Constraints:**
* `1 <= n <= 10^4`
* `distance.length == n`
* `0 <= start, destination < n`
* `0 <= distance[i] <= 10^4` | Sort the pickup and dropoff events by location, then process them in order. |
[Python3] Good enough | distance-between-bus-stops | 0 | 1 | ``` Python3 []\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n minn = min(start, destination)\n maxx = max(start, destination)\n return min(sum(distance[minn:maxx]), sum(distance[:minn] + distance[maxx:]))\n``` | 3 | Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105` | Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions. |
Python distance difference | distance-between-bus-stops | 0 | 1 | \n# Code\n```\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n if start == destination:\n return 0\n elif start < destination:\n trip = sum(distance[start:destination])\n else:\n trip = sum(distance[destination:start])\n\n circle = sum(distance)\n\n if circle - trip > trip:\n return trip\n return circle - trip\n``` | 2 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given `start` and `destination` stops.
**Example 1:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.
**Example 2:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.
**Example 3:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.
**Constraints:**
* `1 <= n <= 10^4`
* `distance.length == n`
* `0 <= start, destination < n`
* `0 <= distance[i] <= 10^4` | Sort the pickup and dropoff events by location, then process them in order. |
Python distance difference | distance-between-bus-stops | 0 | 1 | \n# Code\n```\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n if start == destination:\n return 0\n elif start < destination:\n trip = sum(distance[start:destination])\n else:\n trip = sum(distance[destination:start])\n\n circle = sum(distance)\n\n if circle - trip > trip:\n return trip\n return circle - trip\n``` | 2 | Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105` | Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions. |
Python3 O(n) || O(1) # Runtime: 63ms 60.00% Memory: 14.9mb 93.48% | distance-between-bus-stops | 0 | 1 | ```\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n# O(n) || O(1)\n# Runtime: 63ms 60.00% Memory: 14.9mb 93.48%\n clockWiseDirection = 0\n totalSum = 0\n\n for idx, val in enumerate(distance):\n if start < destination and (idx >= start and idx < destination ):\n clockWiseDirection += val\n\n if start > destination and (idx >= start or idx < destination ):\n clockWiseDirection += val\n\n totalSum += val\n\n return min(clockWiseDirection, totalSum-clockWiseDirection)\n``` | 1 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given `start` and `destination` stops.
**Example 1:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.
**Example 2:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.
**Example 3:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.
**Constraints:**
* `1 <= n <= 10^4`
* `distance.length == n`
* `0 <= start, destination < n`
* `0 <= distance[i] <= 10^4` | Sort the pickup and dropoff events by location, then process them in order. |
Python3 O(n) || O(1) # Runtime: 63ms 60.00% Memory: 14.9mb 93.48% | distance-between-bus-stops | 0 | 1 | ```\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n# O(n) || O(1)\n# Runtime: 63ms 60.00% Memory: 14.9mb 93.48%\n clockWiseDirection = 0\n totalSum = 0\n\n for idx, val in enumerate(distance):\n if start < destination and (idx >= start and idx < destination ):\n clockWiseDirection += val\n\n if start > destination and (idx >= start or idx < destination ):\n clockWiseDirection += val\n\n totalSum += val\n\n return min(clockWiseDirection, totalSum-clockWiseDirection)\n``` | 1 | Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105` | Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions. |
My Solution :) | distance-between-bus-stops | 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:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n clockwise = 0\n counterclockwise = 0\n route = list(range(0, len(distance)))\n count = 0\n i = start\n while count < len(route):\n if route[i] == destination:\n break\n clockwise += distance[i]\n if i == len(distance)-1:\n i = -1\n count += 1\n i += 1\n count = 0\n j = start\n while count < len(route):\n if route[j] == destination:\n break\n counterclockwise += distance[j-1]\n count += 1\n j -= 1\n if clockwise > counterclockwise:\n return counterclockwise\n return clockwise\n``` | 0 | A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given `start` and `destination` stops.
**Example 1:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 1
**Output:** 1
**Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1.
**Example 2:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 2
**Output:** 3
**Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3.
**Example 3:**
**Input:** distance = \[1,2,3,4\], start = 0, destination = 3
**Output:** 4
**Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4.
**Constraints:**
* `1 <= n <= 10^4`
* `distance.length == n`
* `0 <= start, destination < n`
* `0 <= distance[i] <= 10^4` | Sort the pickup and dropoff events by location, then process them in order. |
My Solution :) | distance-between-bus-stops | 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:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n clockwise = 0\n counterclockwise = 0\n route = list(range(0, len(distance)))\n count = 0\n i = start\n while count < len(route):\n if route[i] == destination:\n break\n clockwise += distance[i]\n if i == len(distance)-1:\n i = -1\n count += 1\n i += 1\n count = 0\n j = start\n while count < len(route):\n if route[j] == destination:\n break\n counterclockwise += distance[j-1]\n count += 1\n j -= 1\n if clockwise > counterclockwise:\n return counterclockwise\n return clockwise\n``` | 0 | Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
**Example 1:**
**Input:** arr = \[1,2,2,6,6,6,6,7,10\]
**Output:** 6
**Example 2:**
**Input:** arr = \[1,1\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 105` | Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions. |
1 line python beats 97% | day-of-the-week | 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 dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n\t return date(year, month, day).strftime("%A") \n``` | 1 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
1 line python beats 97% | day-of-the-week | 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 dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n\t return date(year, month, day).strftime("%A") \n``` | 1 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Python simple one line solution | day-of-the-week | 0 | 1 | **Python :**\n\n```\ndef dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n\treturn date(year, month, day).strftime("%A")\n```\n\n**Like it ? please upvote !** | 21 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
Python simple one line solution | day-of-the-week | 0 | 1 | **Python :**\n\n```\ndef dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n\treturn date(year, month, day).strftime("%A")\n```\n\n**Like it ? please upvote !** | 21 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Solution in Python 3 (beats 100.0 %) (one line) | day-of-the-week | 0 | 1 | ```\nfrom datetime import date\n\nclass Solution:\n def dayOfTheWeek(self, d: int, m: int, y: int) -> str:\n \treturn date(y,m,d).strftime("%A")\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com | 10 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
Solution in Python 3 (beats 100.0 %) (one line) | day-of-the-week | 0 | 1 | ```\nfrom datetime import date\n\nclass Solution:\n def dayOfTheWeek(self, d: int, m: int, y: int) -> str:\n \treturn date(y,m,d).strftime("%A")\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com | 10 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Python3 simple solution | day-of-the-week | 0 | 1 | ```\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n prev_year = year - 1\n days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400\n days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1])\n days += day\n\n if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):\n days += 1\n\n return [\'Sunday\', \'Monday\', \'Tuesday\', \'Wednesday\', \'Thursday\', \'Friday\', \'Saturday\'][days % 7]\n```\n**If you like the solution, please vote for this** | 7 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
Python3 simple solution | day-of-the-week | 0 | 1 | ```\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n prev_year = year - 1\n days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400\n days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1])\n days += day\n\n if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):\n days += 1\n\n return [\'Sunday\', \'Monday\', \'Tuesday\', \'Wednesday\', \'Thursday\', \'Friday\', \'Saturday\'][days % 7]\n```\n**If you like the solution, please vote for this** | 7 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Python Simple Logic with easy Steps | day-of-the-week | 0 | 1 | # Intuition\nLet us consider the odd days in the given year. As the test cases renge is from 1970 to 2100 so we can choose a year before 1970 and which comes after leap year. So we can take 1969 which has 3 odd days. Then subtract the given year by 1969 then store it in diff_y which is difference of years. For leap years present in between the given year and 1969 odd days is 2 and for non-leap years it is 1. So we use another variable leap_y stores the leap years by floor division of diff_y. Then store the odd days of years in odd_days.\n\nThen create a days list in which it contains the days name in order starts from Sunday to Saturday and the odd days represent the index number of list days. Then create another list l which stores the number of days in a month. Then loop it till month-1 and add it to odd_days. Finally add the number of days to the odd_days and return the days modulus of 7 which represents the index value of days and returns the corrresponding day of the given date which is in range year greater than 1969. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(month)\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 dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]\n diff_y=abs(year-1969)\n leap_y=diff_y//4\n odd_days=leap_y*2+(diff_y-leap_y)+2\n l=[31,28,31,30,31,30,31,31,30,31,30,31]\n if year%400==0 or (year%4==0 and year%100!=0) :\n l[1]=29\n for i in range(month-1):\n odd_days+=l[i]\n odd_days+=day\n return days[odd_days%7]\n\n\n \n \n``` | 1 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
Python Simple Logic with easy Steps | day-of-the-week | 0 | 1 | # Intuition\nLet us consider the odd days in the given year. As the test cases renge is from 1970 to 2100 so we can choose a year before 1970 and which comes after leap year. So we can take 1969 which has 3 odd days. Then subtract the given year by 1969 then store it in diff_y which is difference of years. For leap years present in between the given year and 1969 odd days is 2 and for non-leap years it is 1. So we use another variable leap_y stores the leap years by floor division of diff_y. Then store the odd days of years in odd_days.\n\nThen create a days list in which it contains the days name in order starts from Sunday to Saturday and the odd days represent the index number of list days. Then create another list l which stores the number of days in a month. Then loop it till month-1 and add it to odd_days. Finally add the number of days to the odd_days and return the days modulus of 7 which represents the index value of days and returns the corrresponding day of the given date which is in range year greater than 1969. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(month)\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 dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]\n diff_y=abs(year-1969)\n leap_y=diff_y//4\n odd_days=leap_y*2+(diff_y-leap_y)+2\n l=[31,28,31,30,31,30,31,31,30,31,30,31]\n if year%400==0 or (year%4==0 and year%100!=0) :\n l[1]=29\n for i in range(month-1):\n odd_days+=l[i]\n odd_days+=day\n return days[odd_days%7]\n\n\n \n \n``` | 1 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
One line Python Solution | day-of-the-week | 0 | 1 | # Intuition:\nBy using the Python programming language and its built-in datetime module.\n\n# Approach\ncreates a datetime object using the provided values. The strftime method is then used to format the date as a string, specifying %A as the format code to retrieve the full weekday name. Finally, the function returns the resulting day of the week.\n\nYou can modify the day, month, and year variables to get the day of the week for different dates.\n\n# Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n return date(year, month, day).strftime("%A")\n``` | 1 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
One line Python Solution | day-of-the-week | 0 | 1 | # Intuition:\nBy using the Python programming language and its built-in datetime module.\n\n# Approach\ncreates a datetime object using the provided values. The strftime method is then used to format the date as a string, specifying %A as the format code to retrieve the full weekday name. Finally, the function returns the resulting day of the week.\n\nYou can modify the day, month, and year variables to get the day of the week for different dates.\n\n# Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n return date(year, month, day).strftime("%A")\n``` | 1 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Easy Python3 Solution | day-of-the-week | 0 | 1 | ```\nfrom datetime import date\n\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n \treturn date(year,month ,day).strftime("%A")\n```\nInspired from code written by Junaid Mansuri | 5 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
Easy Python3 Solution | day-of-the-week | 0 | 1 | ```\nfrom datetime import date\n\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n \treturn date(year,month ,day).strftime("%A")\n```\nInspired from code written by Junaid Mansuri | 5 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Simple & Easy Solution by Python 3 | day-of-the-week | 0 | 1 | ```\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n prev_year = year - 1\n days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400\n days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1])\n days += day\n\n if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):\n days += 1\n\n return [\'Sunday\', \'Monday\', \'Tuesday\', \'Wednesday\', \'Thursday\', \'Friday\', \'Saturday\'][days % 7]\n``` | 9 | Given a date, return the corresponding day of the week for that date.
The input is given as three integers representing the `day`, `month` and `year` respectively.
Return the answer as one of the following values `{ "Sunday ", "Monday ", "Tuesday ", "Wednesday ", "Thursday ", "Friday ", "Saturday "}`.
**Example 1:**
**Input:** day = 31, month = 8, year = 2019
**Output:** "Saturday "
**Example 2:**
**Input:** day = 18, month = 7, year = 1999
**Output:** "Sunday "
**Example 3:**
**Input:** day = 15, month = 8, year = 1993
**Output:** "Sunday "
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | Based on whether A[i-1] < A[i] < A[i+1], A[i-1] < A[i] > A[i+1], or A[i-1] > A[i] > A[i+1], we are either at the left side, peak, or right side of the mountain. We can binary search to find the peak.
After finding the peak, we can binary search two more times to find whether the value occurs on either side of the peak. |
Simple & Easy Solution by Python 3 | day-of-the-week | 0 | 1 | ```\nclass Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n prev_year = year - 1\n days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400\n days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1])\n days += day\n\n if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):\n days += 1\n\n return [\'Sunday\', \'Monday\', \'Tuesday\', \'Wednesday\', \'Thursday\', \'Friday\', \'Saturday\'][days % 7]\n``` | 9 | Given an `n x n` integer matrix `grid`, return _the minimum sum of a **falling path with non-zero shifts**_.
A **falling path with non-zero shifts** is a choice of exactly one element from each row of `grid` such that no two elements chosen in adjacent rows are in the same column.
**Example 1:**
**Input:** arr = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** 13
**Explanation:**
The possible falling paths are:
\[1,5,9\], \[1,5,7\], \[1,6,7\], \[1,6,8\],
\[2,4,8\], \[2,4,9\], \[2,6,7\], \[2,6,8\],
\[3,4,8\], \[3,4,9\], \[3,5,7\], \[3,5,9\]
The falling path with the smallest sum is \[1,5,7\], so the answer is 13.
**Example 2:**
**Input:** grid = \[\[7\]\]
**Output:** 7
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 200`
* `-99 <= grid[i][j] <= 99` | Sum up the number of days for the years before the given year. Handle the case of a leap year. Find the number of days for each month of the given year. |
Simple python solution, ~10 lines, top 99% time & mem. Comments before every line. | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\n\nA good way to build intuition for this problem is by first solving its simpler version: Maximum Subarray (problem 53 in LeetCode). This will provide an understanding of the basic update set.\n\n# Approach\n\nWhile the current num is non-negative, we simply add it. Otherwise, we required more elaborate update. \n\nThe main idea is that we keep two sums: one that doesn\'t allow skipping, and one that does. By updating the \'noskip\' sum later, it points to the sum that was achieved on the previous step. Thus, if we use it, it is as if we skipped the current num. \n\nLast note is that we need to \'reset\' the sums in case they are negative before they are used. The reason is that A + B < B for any negative A. \n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def maximumSum(self, nums: List[int]) -> int:\n # summation with possible skips\n skip = nums[0]\n # summation without skips\n noskip = nums[0]\n # holder for maximal value\n maxv = nums[0]\n for num in nums[1:]:\n # reset skip if negative\n if skip < 0: skip = 0\n # if num is positive just add. otherwise take the maximum between adding it,\n # and skipping it - represented by noskip that currently is on previous position\n skip = skip + num if num >= 0 else max(skip + num, noskip) \n # reset noskip if negative\n if noskip < 0: noskip = 0\n # always add\n noskip += num \n # track maximum\n maxv = max(maxv, noskip, skip)\n\n return maxv \n \n``` | 2 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
Simple python solution, ~10 lines, top 99% time & mem. Comments before every line. | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\n\nA good way to build intuition for this problem is by first solving its simpler version: Maximum Subarray (problem 53 in LeetCode). This will provide an understanding of the basic update set.\n\n# Approach\n\nWhile the current num is non-negative, we simply add it. Otherwise, we required more elaborate update. \n\nThe main idea is that we keep two sums: one that doesn\'t allow skipping, and one that does. By updating the \'noskip\' sum later, it points to the sum that was achieved on the previous step. Thus, if we use it, it is as if we skipped the current num. \n\nLast note is that we need to \'reset\' the sums in case they are negative before they are used. The reason is that A + B < B for any negative A. \n\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def maximumSum(self, nums: List[int]) -> int:\n # summation with possible skips\n skip = nums[0]\n # summation without skips\n noskip = nums[0]\n # holder for maximal value\n maxv = nums[0]\n for num in nums[1:]:\n # reset skip if negative\n if skip < 0: skip = 0\n # if num is positive just add. otherwise take the maximum between adding it,\n # and skipping it - represented by noskip that currently is on previous position\n skip = skip + num if num >= 0 else max(skip + num, noskip) \n # reset noskip if negative\n if noskip < 0: noskip = 0\n # always add\n noskip += num \n # track maximum\n maxv = max(maxv, noskip, skip)\n\n return maxv \n \n``` | 2 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
[Python] Kadane's Algorithm easy solution | maximum-subarray-sum-with-one-deletion | 0 | 1 | Keep two array\'s one will have prefix sum ending at that index from start and one will have prefix sum ending at that index from end, using kadane\'s algorithm. For each i these array\'s will denote maximum subarray ending at i-1 and maximum subarray starting at i+1 so when you add these two values it will denote maximum subarray after deleting i.\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n n = len(arr)\n #maximum subarray starting from the last element i.e. backwards \n prefix_sum_ending = [float(\'-inf\')]*n\n #maximum subarray starting from the first element i.e forwards\n prefix_sum_starting = [float(\'-inf\')]*n\n prefix_sum_ending[n-1] = arr[n-1]\n prefix_sum_starting[0] = arr[0]\n \n for i in range(1,n):\n prefix_sum_starting[i] = max(prefix_sum_starting[i-1]+arr[i], arr[i])\n for i in range(n-2,-1,-1):\n prefix_sum_ending[i] = max(prefix_sum_ending[i+1]+arr[i], arr[i])\n \n max_without_deletion = max(prefix_sum_starting)\n max_with_deletion = float(\'-inf\')\n for i in range(1,n-1):\n max_with_deletion = max(max_with_deletion, prefix_sum_starting[i-1]+prefix_sum_ending[i+1])\n \n return max(max_without_deletion, max_with_deletion)\n``` | 13 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
[Python] Kadane's Algorithm easy solution | maximum-subarray-sum-with-one-deletion | 0 | 1 | Keep two array\'s one will have prefix sum ending at that index from start and one will have prefix sum ending at that index from end, using kadane\'s algorithm. For each i these array\'s will denote maximum subarray ending at i-1 and maximum subarray starting at i+1 so when you add these two values it will denote maximum subarray after deleting i.\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n n = len(arr)\n #maximum subarray starting from the last element i.e. backwards \n prefix_sum_ending = [float(\'-inf\')]*n\n #maximum subarray starting from the first element i.e forwards\n prefix_sum_starting = [float(\'-inf\')]*n\n prefix_sum_ending[n-1] = arr[n-1]\n prefix_sum_starting[0] = arr[0]\n \n for i in range(1,n):\n prefix_sum_starting[i] = max(prefix_sum_starting[i-1]+arr[i], arr[i])\n for i in range(n-2,-1,-1):\n prefix_sum_ending[i] = max(prefix_sum_ending[i+1]+arr[i], arr[i])\n \n max_without_deletion = max(prefix_sum_starting)\n max_with_deletion = float(\'-inf\')\n for i in range(1,n-1):\n max_with_deletion = max(max_with_deletion, prefix_sum_starting[i-1]+prefix_sum_ending[i+1])\n \n return max(max_without_deletion, max_with_deletion)\n``` | 13 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
python3 | DP + memorize | maximum-subarray-sum-with-one-deletion | 0 | 1 | \n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n @cache\n def dp(i,delete):\n if i==0: return arr[i]\n if delete==0: return max(dp(i-1,delete)+arr[i],arr[i])\n return max(dp(i-1,delete)+arr[i],dp(i-1,delete-1),arr[i])\n ans = -float("inf")\n for i in range(len(arr)):\n ans = max(ans,dp(i,1))\n return ans\n \n``` | 1 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
python3 | DP + memorize | maximum-subarray-sum-with-one-deletion | 0 | 1 | \n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n @cache\n def dp(i,delete):\n if i==0: return arr[i]\n if delete==0: return max(dp(i-1,delete)+arr[i],arr[i])\n return max(dp(i-1,delete)+arr[i],dp(i-1,delete-1),arr[i])\n ans = -float("inf")\n for i in range(len(arr)):\n ans = max(ans,dp(i,1))\n return ans\n \n``` | 1 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
| Simple 5 line | Kadane's Algorithm | Beats 91%, 82% | | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\nSimple solution using the idea of Kadane\'s Algorithm. This solution is built on top of [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) question\'s solution using Kadane\'s Algorithm. \n \n---\n\n# Approach\nThe basic idea of Kadane\'s algorithm for solving Maximum Subarray problem is a greedy like approach where we keep track of 2 variables: \n- `cur_sum`: *sum of current subarray*\n- `max_sum`: *max sum of subarray seen so far*\n\nSolution looks like this: \n\n```\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n #1\n cur_sum = max_sum = nums[0]\n #2\n for num in nums[1:]:\n #3\n cur_sum = max(cur_sum + num, num)\n #4\n max_sum = max(max_sum, cur_sum)\n #5\n return max_sum\n```\n`#1`: Set `cur_sum` and `max_sum` to first element\n\n`#2`: Iterate over rest of the array\n\n`#3`: \n\n`cur_sum` needs to be set to maximum of 2 things: \n - `cur_sum + num`: Extend current subarray by adding `num`\n - `num`: Start a new subarray from `num`\n \n`#4`: Update `max_sum` to keep track of maximum sum of subarray seen so far\n\n`#5`: Return `max_sum`\n\n\n---\n\nThis question goes a step further on Maximum Subarray one, where we are allowed to delete one of the elements in the array. We can easily extend the previous solution to take care of the deletion case.\n\nNow we need to keep track of 3 variables:\n- `cur_sum_del`: *sum of current subarray with **one** deletion*\n- `cur_sum_no_del`: *sum of current subarray with **no** deletion*\n- `max_sum`: *max sum of subarray seen so far*\n\nSolution looks like this:\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n #1\n cur_sum_no_del = cur_sum_del = max_sum = arr[0]\n #2 \n for num in arr[1:]:\n #3\n cur_sum_del = max(cur_sum_del + num, num, cur_sum_no_del)\n #4\n cur_sum_no_del = max(cur_sum_no_del + num, num)\n #5\n max_sum = max(max_sum, cur_sum_no_del, cur_sum_del)\n #6\n return max_sum\n```\n\n`#1`: Set `cur_sum_del`, `cur_sum_no_del` and `max_sum` to first element\n\n`#2`: Iterate over rest of the array\n\n`#3`: \n \n`cur_sum_del` needs to be set to maximum of 3 things\n - `cur_sum_del + num`: Extend current subarray with one deletion by adding `num`\n - `cur_sum_no_del`: Delete the current `num` \n - `num`: Start a new subarray from `num`\n\n`#4`: \n\n`cur_sum_no_del` needs to be set to maximum of 2 things:\n - `cur_sum_no_del + num`: Extend current subarray without deletion by adding `num`\n - `num`: Start a new subarray from `num`\n\n`#5`: Update `max_sum` to keep track of maximum sum of subarray seen so far\n\n`#6`: Return `max_sum`\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n\n | 0 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
| Simple 5 line | Kadane's Algorithm | Beats 91%, 82% | | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\nSimple solution using the idea of Kadane\'s Algorithm. This solution is built on top of [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) question\'s solution using Kadane\'s Algorithm. \n \n---\n\n# Approach\nThe basic idea of Kadane\'s algorithm for solving Maximum Subarray problem is a greedy like approach where we keep track of 2 variables: \n- `cur_sum`: *sum of current subarray*\n- `max_sum`: *max sum of subarray seen so far*\n\nSolution looks like this: \n\n```\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n #1\n cur_sum = max_sum = nums[0]\n #2\n for num in nums[1:]:\n #3\n cur_sum = max(cur_sum + num, num)\n #4\n max_sum = max(max_sum, cur_sum)\n #5\n return max_sum\n```\n`#1`: Set `cur_sum` and `max_sum` to first element\n\n`#2`: Iterate over rest of the array\n\n`#3`: \n\n`cur_sum` needs to be set to maximum of 2 things: \n - `cur_sum + num`: Extend current subarray by adding `num`\n - `num`: Start a new subarray from `num`\n \n`#4`: Update `max_sum` to keep track of maximum sum of subarray seen so far\n\n`#5`: Return `max_sum`\n\n\n---\n\nThis question goes a step further on Maximum Subarray one, where we are allowed to delete one of the elements in the array. We can easily extend the previous solution to take care of the deletion case.\n\nNow we need to keep track of 3 variables:\n- `cur_sum_del`: *sum of current subarray with **one** deletion*\n- `cur_sum_no_del`: *sum of current subarray with **no** deletion*\n- `max_sum`: *max sum of subarray seen so far*\n\nSolution looks like this:\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n #1\n cur_sum_no_del = cur_sum_del = max_sum = arr[0]\n #2 \n for num in arr[1:]:\n #3\n cur_sum_del = max(cur_sum_del + num, num, cur_sum_no_del)\n #4\n cur_sum_no_del = max(cur_sum_no_del + num, num)\n #5\n max_sum = max(max_sum, cur_sum_no_del, cur_sum_del)\n #6\n return max_sum\n```\n\n`#1`: Set `cur_sum_del`, `cur_sum_no_del` and `max_sum` to first element\n\n`#2`: Iterate over rest of the array\n\n`#3`: \n \n`cur_sum_del` needs to be set to maximum of 3 things\n - `cur_sum_del + num`: Extend current subarray with one deletion by adding `num`\n - `cur_sum_no_del`: Delete the current `num` \n - `num`: Start a new subarray from `num`\n\n`#4`: \n\n`cur_sum_no_del` needs to be set to maximum of 2 things:\n - `cur_sum_no_del + num`: Extend current subarray without deletion by adding `num`\n - `num`: Start a new subarray from `num`\n\n`#5`: Update `max_sum` to keep track of maximum sum of subarray seen so far\n\n`#6`: Return `max_sum`\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n\n | 0 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
Python 3: TC O(N) SC O(1) DP | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\n\n## Zero Deletion "DP"\n\nThe classic solution to this problem with 0 deletions is to track a window sum to the left that includes the current element.\n\nIf the sum is positive, see if it\'s the new best.\n\nIf the sum is 0 or negative, then the cumulative sum is 0.\n\n## One Deletion DP\n\nSo I thought I\'d try two window sums... but it turns out it doesn\'t work. At least not the way I tried. The reason is that it\'s hard to update the two subarrays *because we don\'t know the best subarray ending with the prior element.*\n\nThen I realized that DP is probably the answer here. And it is!\n\nThe answer is the best *nonempty* subarray sum with 0 or 1 elements deleted.\n\nSo we can infer that we want something like `dp[0][i]` for the best subarray ending at `i` with `0` deletions, and `dp[1][i]` for the best subarray with `1` deletion. But we have to be very careful about making sure the answer has at least one element, otherwise we fail the test cases with all or mostly negative numbers.\n\n### Deriving the DP Formula\n\nSuppose we know the best values `dp` up through index `i`.\n\nAt index `i+1` our options for 0-deletion arrays with one element are these:\n* the best 0-deletes subarray at i, then add `n`: `dp[0][i] + n`\n * this has 2+ elements: at least one by construction from `dp[0][i]`, and another from `n`\n* or just the most recent element `n`\n * this has 1 element\n* so the combination of these two is all subarrays with 1+ elements\n\nAt index `i+1`, our options for 1-delete subarrays are these:\n* we can delete `n`: so the answer would be `dp[0][i]`, the sum of 1+ elements except `n` because we deleted it\n* we can keep `n`\n * for just one element, we can delete the prior number at `i`: `n` itself (if `i >= 0`)\n * or for 2+ we can keep `n` and attach to another array where we deleted one already: `dp[1][i] + n`\n\nSo overall we get these options for `i > 0`\n* `dp[0][i] = max(dp[0][i-1]+n, n)`\n* `dp[1][i] = max(dp[0][i-1], dp[1][i]+n, n)`\n\nTo make sure we start the DP arrays off with valid values (they must both be the sum of 1+ element subarrays after any deletions) I wrote up the solutions for the first two indices by hand:\n* dp[0][1]: `arr[1]`, plus `arr[0]` as well if it\'s positive (see the DP update formula)\n* dp[1][0]: `arr[0]+arr[1] - min(arr[0],arr[1])` because we have to delete an element, and there are only two to choose from\n\n### Sequence Problems in General\n\nWhen applying DP to a sequence problem, you can almost always derive the DP formua in one of two ways:\n1. looking backward: for the current "state," in this case `dp[k][i]` with `k` deletions, think of how to get to this state with the operation (in this case, taking or leaving an element). This gives you the recurrence relation directly.\n2. sometimes that\'s hard though, so you can do something else:\n a. write out all the states, in this case `dp[k][i]`\n b. for each, write out all the legal "actions" you can do (in this case: keep or delete an element) and record what the new state is: various `dp[k\'][i+1]` values\n c. then for each `dp[k\'][i+1]`, aggregate over all the `dp[k][i]` terms that contribute to it. In this case we want the best answer, so we return max. In counting problems, we\'d sum to get the total ways of doing something.\n\n# Approach\n\nThe idea above works, and gives you a SC O(N). That\'s okay, but we can do better.\n\nThe reason is we only need `dp[:][i-1]` to do the update at `i`. So we don\'t need the whole table; we can just store two `dp[:][i]` values as two scalars.\n\nThis way we take only O(1) space.\n\nYou can use this O(N) -> O(1) trick whenever you only need the prior index to do the update. Often times you can do the same thing to get a O(M N) -> O(N) reduction for the same reason, where you only need the prior row or column. In rare cases you can reduce O(M N P) -> O(M N). The pattern is you can reduce one dimension of your DP tensor to a constant by being clever about the order in which you fill in the DP table.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n # max subarray sum, but we can delete an element\n\n # for the non-delete versions we have a sliding window of positive sum, if the sum drops to 0 or below then flush the window\n # each iteration we add a new right-most element to the array\n\n # for the delete version: we have have a subarray L, a negative element deleted, and subarray R\n #\n # e.g. .... |------ L ------| n |------ R -------|\n # <0\n #\n # we want to delete the most negative number, if any, so n should be the most negative\n # when we find a most negative number, vs. the prior iteration we have ----L---- n ------R----- n\'\n # suppose L is always positive\n\n # L > 0\n # if L+n <= 0: remove L and n from window\n # if R < 0; we know L+R > 0, otherwise whole window gets cleared\n # if R < 0: we need to get the part of R, if any, that has the largest subarray sum\n # wait...\n # let\'s say we know the best subarray sum ending with a given element, or no subarray at all (empty)\n\n # call that best0[i]: with no deletions\n # for element i+1:\n # we can delete i: best1[i+1] = best0[i]\n # or we can keep i: best1[i+1] = best1[i] + arr[i]\n # and best0[i+1] = best0[i] + arr[i]\n # take maxes of these and zero\n\n N = len(arr)\n if N == 1: return arr[0]\n if N == 2: return max(arr)\n\n p = arr[0] + arr[1]\n # with 0 and 1 deletion through the first two elements, at least one element\n best0 = arr[1] + max(arr[0], 0) # FIX: for e.g. [-5, 8] the best 0-delete array is [8]\n best1 = p - min(arr[0], arr[1])\n ans = max(arr[0], arr[1], p) # either element or both\n for i in range(2, N):\n n = arr[i]\n # print(f"{best0=}, {best1=}, {i=}, {n=}")\n # best 0: n by itself (1), or n and best0 (2+)\n # best 1: can delete n: take best0 (1+)\n # or can keep n: take best1 + n (2+ elts) or just n (i.e. delete i-1)\n # best 1: can delete a prior element (best1+n) or delete this one: best0\n best0, best1 = max(best0 + n, n), max(best0, best1 + n, n)\n # print(f" {best0=}, {best1=}")\n ans = max(ans, best0, best1)\n\n return ans\n``` | 0 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
Python 3: TC O(N) SC O(1) DP | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\n\n## Zero Deletion "DP"\n\nThe classic solution to this problem with 0 deletions is to track a window sum to the left that includes the current element.\n\nIf the sum is positive, see if it\'s the new best.\n\nIf the sum is 0 or negative, then the cumulative sum is 0.\n\n## One Deletion DP\n\nSo I thought I\'d try two window sums... but it turns out it doesn\'t work. At least not the way I tried. The reason is that it\'s hard to update the two subarrays *because we don\'t know the best subarray ending with the prior element.*\n\nThen I realized that DP is probably the answer here. And it is!\n\nThe answer is the best *nonempty* subarray sum with 0 or 1 elements deleted.\n\nSo we can infer that we want something like `dp[0][i]` for the best subarray ending at `i` with `0` deletions, and `dp[1][i]` for the best subarray with `1` deletion. But we have to be very careful about making sure the answer has at least one element, otherwise we fail the test cases with all or mostly negative numbers.\n\n### Deriving the DP Formula\n\nSuppose we know the best values `dp` up through index `i`.\n\nAt index `i+1` our options for 0-deletion arrays with one element are these:\n* the best 0-deletes subarray at i, then add `n`: `dp[0][i] + n`\n * this has 2+ elements: at least one by construction from `dp[0][i]`, and another from `n`\n* or just the most recent element `n`\n * this has 1 element\n* so the combination of these two is all subarrays with 1+ elements\n\nAt index `i+1`, our options for 1-delete subarrays are these:\n* we can delete `n`: so the answer would be `dp[0][i]`, the sum of 1+ elements except `n` because we deleted it\n* we can keep `n`\n * for just one element, we can delete the prior number at `i`: `n` itself (if `i >= 0`)\n * or for 2+ we can keep `n` and attach to another array where we deleted one already: `dp[1][i] + n`\n\nSo overall we get these options for `i > 0`\n* `dp[0][i] = max(dp[0][i-1]+n, n)`\n* `dp[1][i] = max(dp[0][i-1], dp[1][i]+n, n)`\n\nTo make sure we start the DP arrays off with valid values (they must both be the sum of 1+ element subarrays after any deletions) I wrote up the solutions for the first two indices by hand:\n* dp[0][1]: `arr[1]`, plus `arr[0]` as well if it\'s positive (see the DP update formula)\n* dp[1][0]: `arr[0]+arr[1] - min(arr[0],arr[1])` because we have to delete an element, and there are only two to choose from\n\n### Sequence Problems in General\n\nWhen applying DP to a sequence problem, you can almost always derive the DP formua in one of two ways:\n1. looking backward: for the current "state," in this case `dp[k][i]` with `k` deletions, think of how to get to this state with the operation (in this case, taking or leaving an element). This gives you the recurrence relation directly.\n2. sometimes that\'s hard though, so you can do something else:\n a. write out all the states, in this case `dp[k][i]`\n b. for each, write out all the legal "actions" you can do (in this case: keep or delete an element) and record what the new state is: various `dp[k\'][i+1]` values\n c. then for each `dp[k\'][i+1]`, aggregate over all the `dp[k][i]` terms that contribute to it. In this case we want the best answer, so we return max. In counting problems, we\'d sum to get the total ways of doing something.\n\n# Approach\n\nThe idea above works, and gives you a SC O(N). That\'s okay, but we can do better.\n\nThe reason is we only need `dp[:][i-1]` to do the update at `i`. So we don\'t need the whole table; we can just store two `dp[:][i]` values as two scalars.\n\nThis way we take only O(1) space.\n\nYou can use this O(N) -> O(1) trick whenever you only need the prior index to do the update. Often times you can do the same thing to get a O(M N) -> O(N) reduction for the same reason, where you only need the prior row or column. In rare cases you can reduce O(M N P) -> O(M N). The pattern is you can reduce one dimension of your DP tensor to a constant by being clever about the order in which you fill in the DP table.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n # max subarray sum, but we can delete an element\n\n # for the non-delete versions we have a sliding window of positive sum, if the sum drops to 0 or below then flush the window\n # each iteration we add a new right-most element to the array\n\n # for the delete version: we have have a subarray L, a negative element deleted, and subarray R\n #\n # e.g. .... |------ L ------| n |------ R -------|\n # <0\n #\n # we want to delete the most negative number, if any, so n should be the most negative\n # when we find a most negative number, vs. the prior iteration we have ----L---- n ------R----- n\'\n # suppose L is always positive\n\n # L > 0\n # if L+n <= 0: remove L and n from window\n # if R < 0; we know L+R > 0, otherwise whole window gets cleared\n # if R < 0: we need to get the part of R, if any, that has the largest subarray sum\n # wait...\n # let\'s say we know the best subarray sum ending with a given element, or no subarray at all (empty)\n\n # call that best0[i]: with no deletions\n # for element i+1:\n # we can delete i: best1[i+1] = best0[i]\n # or we can keep i: best1[i+1] = best1[i] + arr[i]\n # and best0[i+1] = best0[i] + arr[i]\n # take maxes of these and zero\n\n N = len(arr)\n if N == 1: return arr[0]\n if N == 2: return max(arr)\n\n p = arr[0] + arr[1]\n # with 0 and 1 deletion through the first two elements, at least one element\n best0 = arr[1] + max(arr[0], 0) # FIX: for e.g. [-5, 8] the best 0-delete array is [8]\n best1 = p - min(arr[0], arr[1])\n ans = max(arr[0], arr[1], p) # either element or both\n for i in range(2, N):\n n = arr[i]\n # print(f"{best0=}, {best1=}, {i=}, {n=}")\n # best 0: n by itself (1), or n and best0 (2+)\n # best 1: can delete n: take best0 (1+)\n # or can keep n: take best1 + n (2+ elts) or just n (i.e. delete i-1)\n # best 1: can delete a prior element (best1+n) or delete this one: best0\n best0, best1 = max(best0 + n, n), max(best0, best1 + n, n)\n # print(f" {best0=}, {best1=}")\n ans = max(ans, best0, best1)\n\n return ans\n``` | 0 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
commented kadane solution. | maximum-subarray-sum-with-one-deletion | 0 | 1 | \n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n if len(arr) == 1 : \n # if only one element, just return it \n return arr[0]\n\n l = len(arr)\n # kadane from left and right \n # left[i] keep max sum of subarray ends at i\n left = [0] * l\n left[0] = arr[0]\n for i in range(1, l): \n left[i] = max(arr[i], arr[i] + left[i-1])\n # right[i] keep max sum of subarray starts at i \n right = [0] * l\n right[l-1] = arr[l-1]\n for i in range(l-2, -1,-1): \n right[i] = max(arr[i], arr[i] + right[i+1])\n\n res = float(\'-inf\')\n for i in range(l): \n if i == 0 : \n res = max(\n res, \n right[i], # no skip \n right[i+1] # skip the first \n ) \n elif i == l-1: \n res = max(\n res, \n left[i], # no skip\n left[i-1] # skip the rightmost element \n ) \n else: \n res = max(res, \n left[i-1] + right[i+1], # skip the ith element \n left[i-1] + right[i+1] + arr[i] # no skip \n )\n \n return res\n \n \n \n``` | 0 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
commented kadane solution. | maximum-subarray-sum-with-one-deletion | 0 | 1 | \n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n if len(arr) == 1 : \n # if only one element, just return it \n return arr[0]\n\n l = len(arr)\n # kadane from left and right \n # left[i] keep max sum of subarray ends at i\n left = [0] * l\n left[0] = arr[0]\n for i in range(1, l): \n left[i] = max(arr[i], arr[i] + left[i-1])\n # right[i] keep max sum of subarray starts at i \n right = [0] * l\n right[l-1] = arr[l-1]\n for i in range(l-2, -1,-1): \n right[i] = max(arr[i], arr[i] + right[i+1])\n\n res = float(\'-inf\')\n for i in range(l): \n if i == 0 : \n res = max(\n res, \n right[i], # no skip \n right[i+1] # skip the first \n ) \n elif i == l-1: \n res = max(\n res, \n left[i], # no skip\n left[i-1] # skip the rightmost element \n ) \n else: \n res = max(res, \n left[i-1] + right[i+1], # skip the ith element \n left[i-1] + right[i+1] + arr[i] # no skip \n )\n \n return res\n \n \n \n``` | 0 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
Python Solution | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n\n def is_all_negative():\n for num in arr:\n if num > 0:\n return False\n return True\n\n\n n = len(arr)\n \n if n==1:\n return arr[0]\n if is_all_negative():\n return max(arr)\n \n left_running_sum = [0 for _ in range(n)]\n right_running_sum = [0 for _ in range(n)]\n\n running_sum = 0\n for i, num in enumerate(arr):\n running_sum += num\n if running_sum < 0:\n running_sum = 0\n left_running_sum[i] = running_sum\n \n running_sum = 0\n for i in range(n-1, -1, -1):\n running_sum += arr[i]\n if running_sum < 0:\n running_sum = 0\n right_running_sum[i] = running_sum\n \n ans = 0\n for i in range(n):\n ans = max(ans, left_running_sum[i])\n\n if arr[i] < 0 and i>0 and i<n-1:\n curr_ignored_sub_arr_sum = left_running_sum[i-1] + right_running_sum[i+1] \n ans = max(ans, curr_ignored_sub_arr_sum)\n \n\n return ans\n\n``` | 0 | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null |
Python Solution | maximum-subarray-sum-with-one-deletion | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumSum(self, arr: List[int]) -> int:\n\n def is_all_negative():\n for num in arr:\n if num > 0:\n return False\n return True\n\n\n n = len(arr)\n \n if n==1:\n return arr[0]\n if is_all_negative():\n return max(arr)\n \n left_running_sum = [0 for _ in range(n)]\n right_running_sum = [0 for _ in range(n)]\n\n running_sum = 0\n for i, num in enumerate(arr):\n running_sum += num\n if running_sum < 0:\n running_sum = 0\n left_running_sum[i] = running_sum\n \n running_sum = 0\n for i in range(n-1, -1, -1):\n running_sum += arr[i]\n if running_sum < 0:\n running_sum = 0\n right_running_sum[i] = running_sum\n \n ans = 0\n for i in range(n):\n ans = max(ans, left_running_sum[i])\n\n if arr[i] < 0 and i>0 and i<n-1:\n curr_ignored_sub_arr_sum = left_running_sum[i-1] + right_running_sum[i+1] \n ans = max(ans, curr_ignored_sub_arr_sum)\n \n\n return ans\n\n``` | 0 | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. |
python3 Solution | make-array-strictly-increasing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n arr2.sort()\n @cache\n def f(i,prev):\n if i==len(arr1):\n return 0\n ans=inf\n if prev<arr1[i]:\n ans=f(i+1,arr1[i])\n \n k=bisect_right(arr2,prev)\n if k<len(arr2):\n ans=min(ans,1+f(i+1,arr2[k]))\n \n return ans\n ans=f(0,-inf)\n return ans if ans<inf else -1\n``` | 3 | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null |
python3 Solution | make-array-strictly-increasing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n arr2.sort()\n @cache\n def f(i,prev):\n if i==len(arr1):\n return 0\n ans=inf\n if prev<arr1[i]:\n ans=f(i+1,arr1[i])\n \n k=bisect_right(arr2,prev)\n if k<len(arr2):\n ans=min(ans,1+f(i+1,arr2[k]))\n \n return ans\n ans=f(0,-inf)\n return ans if ans<inf else -1\n``` | 3 | Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`. | Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates. |
Fastest Solution Yet | make-array-strictly-increasing | 0 | 1 | # Approach\n\nThe code first imports the `bisect` module, which provides a number of functions for working with sorted lists. The `arr2` array is then sorted and the unique elements are extracted using the `set()` function. The lengths of the two arrays are then stored in the variables `n1` and `n2`.\n\nA dictionary `d` is then created, which maps the number of operations needed to make `arr1` strictly increasing to the value of the last element that was swapped. The initial value of the dictionary is `{0: arr1[0]}`, which means that no operations are needed to make the first element of `arr1` increasing. If the first element of `arr2` is less than the first element of `arr1`, then the value `1` is added to the dictionary with the value of the first element of `arr2`.\n\nFor each element `x` in `arr1`, a new dictionary `new_d` is created. The values in `d` are then checked to see if they are less than `x`. If they are, then they are added to `new_d`. The values in `d` are also checked to see if they are in `arr2`. If they are, then the index of the value in `arr2` is found using the `bisect.bisect_right()` function. If the index is less than `n2`, then the value at the index is added to `new_d` if it is not already present.\n\nThe `d` dictionary is then updated with the values from `new_d`. This process is repeated for each element in `arr1`.\n\nIf the `d` dictionary is not empty, then the minimum number of operations needed to make `arr1` strictly increasing is returned. Otherwise, `-1` is returned.\n\nHere is a more detailed explanation of the code:\n```\nimport bisect\n```\n\n## Sort the arr2 array and extract the unique elements.\n```\narr2 = sorted(set(arr2))\n```\n\n## Get the lengths of the two arrays.\n```\nn1, n2 = len(arr1), len(arr2)\n```\n\n## Create a dictionary that maps the number of operations needed to make arr1 strictly increasing to the value of the last element that was swapped.\n```\nd = {0: arr1[0]}\nif arr2[0] < arr1[0]:\n d[1] = arr2[0]\n ``` \n\n## For each element in arr1, check if the values in d are less than it. If they are, add them to a new dictionary. Also check if the values in d are in arr2. If they are, find the index of the value in arr2 and add it to the new dictionary if it is not already present.\n```\nfor i in range(1, n1):\n new_d = {}\n x = arr1[i]\n for time, value in d.items():\n if value < x:\n new_d[time] = x\n for time, value in d.items():\n index = bisect.bisect_right(arr2, value)\n if index < n2:\n if time + 1 in new_d:\n new_d[time + 1] = min(new_d[time + 1], arr2[index])\n else:\n new_d[time + 1] = arr2[index]\n``` \n\n## Update the d dictionary with the values from the new dictionary.\n```\n d = new_d \n```\n\n## If the d dictionary is not empty, return the minimum number of operations needed to make arr1 strictly increasing. Otherwise, return -1.\n```\nif d:\n return min(d.keys())\nreturn -1\n```\n\n# Time Complexity\nThe time complexity of the code is O(n<sup>2</sup> log n), where n is the length of arr1. The first step of the algorithm is to sort arr2, which takes O(n log n) time. The second step is to iterate through arr1 and for each element, find the minimum number of swaps needed to make it strictly increasing. This can be done by using a dictionary to store the minimum number of swaps needed to reach each element in arr1.\nThe first loop iterates through arr1 once. The second loop iterates through the dictionary d once for each element in arr1. The bisect.bisect_right() function takes O(log n) time. Therefore, the total time complexity of the second step is O(n<sup>2</sup> log n).\nThe third and final step of the algorithm is to return the minimum number of swaps needed to make arr1 strictly increasing. This can be done by taking the minimum value from the dictionary d. The time complexity of this step is O(1).\n\nTherefore, the overall time complexity of the algorithm is O(n<sup>2</sup> log n).\n\n# Space Complexity\nThe space complexity of the code is O(n), where n is the length of the input arrays. This is because the code uses a dictionary (d) to store the minimum number of operations needed to make arr1 strictly increasing up to a certain point. The dictionary can store up to n entries, one for each element in arr1. Therefore, the space complexity is O(n).\n\nHere is a more detailed explanation of the space complexity:\n\n* The code first sorts arr2 and creates a dictionary (d) to store the minimum number of operations needed to make arr1 strictly increasing up to a certain point. The dictionary is initialized with one entry, {0: arr1[0]}.\n* The code then iterates through arr1, starting at index 1. For each element in arr1, the code checks if the element is less than the value stored in d for the current time. If it is, the code updates d to store the minimum number of operations needed to make arr1 strictly increasing up to the current point.\n* The code also checks if the element in arr1 is less than any of the elements in arr2. If it is, the code updates d to store the minimum number of operations needed to make arr1 strictly increasing up to the current point, by assigning the element in arr2 to the current time in d.\n* The code repeats this process for each element in arr1.\n* After the loop, the code checks if d is empty. If it is, then there is no way to make arr1 strictly increasing, so the code returns -1. Otherwise, the code returns the minimum number of operations stored in d.\n\nAs you can see, the code only uses a dictionary (d) to store the minimum number of operations needed to make arr1 strictly increasing up to a certain point. The dictionary can store up to n entries, one for each element in arr1. Therefore, the space complexity is O(n).\n\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n \n\n import bisect\n\n arr2 = sorted(set(arr2))\n n1, n2 = len(arr1), len(arr2)\n\n d = {0: arr1[0]} # swap time: value of last\n if arr2[0] < arr1[0]:\n d[1] = arr2[0]\n \n for i in range(1, n1):\n new_d = {}\n x = arr1[i]\n for time, value in d.items():\n if value < x:\n new_d[time] = x\n for time, value in d.items():\n index = bisect.bisect_right(arr2, value) \n if index < n2:\n if time + 1 in new_d:\n new_d[time + 1] = min(new_d[time + 1], arr2[index])\n else:\n new_d[time + 1] = arr2[index]\n \n d = new_d\n if d:\n return min(d.keys())\n return -1\n \n``` | 2 | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null |
Fastest Solution Yet | make-array-strictly-increasing | 0 | 1 | # Approach\n\nThe code first imports the `bisect` module, which provides a number of functions for working with sorted lists. The `arr2` array is then sorted and the unique elements are extracted using the `set()` function. The lengths of the two arrays are then stored in the variables `n1` and `n2`.\n\nA dictionary `d` is then created, which maps the number of operations needed to make `arr1` strictly increasing to the value of the last element that was swapped. The initial value of the dictionary is `{0: arr1[0]}`, which means that no operations are needed to make the first element of `arr1` increasing. If the first element of `arr2` is less than the first element of `arr1`, then the value `1` is added to the dictionary with the value of the first element of `arr2`.\n\nFor each element `x` in `arr1`, a new dictionary `new_d` is created. The values in `d` are then checked to see if they are less than `x`. If they are, then they are added to `new_d`. The values in `d` are also checked to see if they are in `arr2`. If they are, then the index of the value in `arr2` is found using the `bisect.bisect_right()` function. If the index is less than `n2`, then the value at the index is added to `new_d` if it is not already present.\n\nThe `d` dictionary is then updated with the values from `new_d`. This process is repeated for each element in `arr1`.\n\nIf the `d` dictionary is not empty, then the minimum number of operations needed to make `arr1` strictly increasing is returned. Otherwise, `-1` is returned.\n\nHere is a more detailed explanation of the code:\n```\nimport bisect\n```\n\n## Sort the arr2 array and extract the unique elements.\n```\narr2 = sorted(set(arr2))\n```\n\n## Get the lengths of the two arrays.\n```\nn1, n2 = len(arr1), len(arr2)\n```\n\n## Create a dictionary that maps the number of operations needed to make arr1 strictly increasing to the value of the last element that was swapped.\n```\nd = {0: arr1[0]}\nif arr2[0] < arr1[0]:\n d[1] = arr2[0]\n ``` \n\n## For each element in arr1, check if the values in d are less than it. If they are, add them to a new dictionary. Also check if the values in d are in arr2. If they are, find the index of the value in arr2 and add it to the new dictionary if it is not already present.\n```\nfor i in range(1, n1):\n new_d = {}\n x = arr1[i]\n for time, value in d.items():\n if value < x:\n new_d[time] = x\n for time, value in d.items():\n index = bisect.bisect_right(arr2, value)\n if index < n2:\n if time + 1 in new_d:\n new_d[time + 1] = min(new_d[time + 1], arr2[index])\n else:\n new_d[time + 1] = arr2[index]\n``` \n\n## Update the d dictionary with the values from the new dictionary.\n```\n d = new_d \n```\n\n## If the d dictionary is not empty, return the minimum number of operations needed to make arr1 strictly increasing. Otherwise, return -1.\n```\nif d:\n return min(d.keys())\nreturn -1\n```\n\n# Time Complexity\nThe time complexity of the code is O(n<sup>2</sup> log n), where n is the length of arr1. The first step of the algorithm is to sort arr2, which takes O(n log n) time. The second step is to iterate through arr1 and for each element, find the minimum number of swaps needed to make it strictly increasing. This can be done by using a dictionary to store the minimum number of swaps needed to reach each element in arr1.\nThe first loop iterates through arr1 once. The second loop iterates through the dictionary d once for each element in arr1. The bisect.bisect_right() function takes O(log n) time. Therefore, the total time complexity of the second step is O(n<sup>2</sup> log n).\nThe third and final step of the algorithm is to return the minimum number of swaps needed to make arr1 strictly increasing. This can be done by taking the minimum value from the dictionary d. The time complexity of this step is O(1).\n\nTherefore, the overall time complexity of the algorithm is O(n<sup>2</sup> log n).\n\n# Space Complexity\nThe space complexity of the code is O(n), where n is the length of the input arrays. This is because the code uses a dictionary (d) to store the minimum number of operations needed to make arr1 strictly increasing up to a certain point. The dictionary can store up to n entries, one for each element in arr1. Therefore, the space complexity is O(n).\n\nHere is a more detailed explanation of the space complexity:\n\n* The code first sorts arr2 and creates a dictionary (d) to store the minimum number of operations needed to make arr1 strictly increasing up to a certain point. The dictionary is initialized with one entry, {0: arr1[0]}.\n* The code then iterates through arr1, starting at index 1. For each element in arr1, the code checks if the element is less than the value stored in d for the current time. If it is, the code updates d to store the minimum number of operations needed to make arr1 strictly increasing up to the current point.\n* The code also checks if the element in arr1 is less than any of the elements in arr2. If it is, the code updates d to store the minimum number of operations needed to make arr1 strictly increasing up to the current point, by assigning the element in arr2 to the current time in d.\n* The code repeats this process for each element in arr1.\n* After the loop, the code checks if d is empty. If it is, then there is no way to make arr1 strictly increasing, so the code returns -1. Otherwise, the code returns the minimum number of operations stored in d.\n\nAs you can see, the code only uses a dictionary (d) to store the minimum number of operations needed to make arr1 strictly increasing up to a certain point. The dictionary can store up to n entries, one for each element in arr1. Therefore, the space complexity is O(n).\n\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n \n\n import bisect\n\n arr2 = sorted(set(arr2))\n n1, n2 = len(arr1), len(arr2)\n\n d = {0: arr1[0]} # swap time: value of last\n if arr2[0] < arr1[0]:\n d[1] = arr2[0]\n \n for i in range(1, n1):\n new_d = {}\n x = arr1[i]\n for time, value in d.items():\n if value < x:\n new_d[time] = x\n for time, value in d.items():\n index = bisect.bisect_right(arr2, value) \n if index < n2:\n if time + 1 in new_d:\n new_d[time + 1] = min(new_d[time + 1], arr2[index])\n else:\n new_d[time + 1] = arr2[index]\n \n d = new_d\n if d:\n return min(d.keys())\n return -1\n \n``` | 2 | Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`. | Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates. |
✅ 99% Clear code | Full Explanation | Similar idea from the hint | make-array-strictly-increasing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo make `arr1` strictly increasing, we need to consider two options for each element in `arr1`:\n1. Keep the current value from `arr1`.\n2. Replace the current value from `arr1` with a value from `arr2`.\n\nThe goal is to find the minimum number of operations (assignments) required to make `arr1` strictly increasing. To achieve this, we can use dynamic programming to keep track of the minimum steps needed for each value in `arr1` in the previous round.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a dictionary, `dp`, to store the minimum steps to reach a particular value in the previous round. Initialize it with a single key-value pair `{-1: 0}`. The `-1` represents an imaginary value that acts as the initial state.\n2. Sort `arr2` in non-decreasing order and remove duplicates.\n3. Iterate through each value, `arr1_val`, in `arr1`:\n - Initialize a new dictionary, `newDp`, to store the minimum steps for the next round. Use `defaultdict` from the `collections` module to set the default value of each key to infinity.\n - Iterate through each key-value pair, `val` and `steps`, in `dp`:\n - If `arr1_val` is greater than `val`, it means we can keep the current value from `arr1`. In this case, update `newDp[arr1_val]` to the minimum value between `newDp[arr1_val]` and `steps`.\n - Find the index, `i`, using the `bisect_right` function, to locate the position in `arr2` where we can find the next greater value than `val`.\n - If `i` is less than the length of `arr2`, it means there is a valid value in `arr2` to replace the current value from `arr1`. In this case, update `newDp[arr2[i]]` to the minimum value between `newDp[arr2[i]]` and `steps + 1`.\n - If `newDp` is empty, it means there is no way to make `arr1` strictly increasing. Return -1.\n - Update `dp` with the values from `newDp` for the next round.\n4. Return the minimum value among all the values in `dp`.\n# Complexity\n- Time complexity: O(n * m * log(m))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Explanation:\n- Sorting `arr2` takes O(m * log(m)) time.\n- The outer loop iterates through each element in `arr1`, resulting in O(n) iterations.\n- The inner loop iterates through each key-value pair in `dp`, resulting in a maximum of m iterations.\n- The `bisect_right` function used within the inner loop takes O(log(m)) time.\n- Overall, the time complexity is O(n * m * log(m)).\n\nThe space complexity of the solution is O(m) due to the usage of the `dp` dictionary to store the minimum steps for each value. The size of the dictionary `dp` is at most m since we consider each element in `arr2` once.\n\nIn addition to the space complexity, there is also some auxiliary space used for intermediate computations, such as sorting `arr2` and creating the deduplicated list. However, these do not contribute significantly to the overall space complexity compared to the size of `dp`.\n\nOverall, the solution has a time complexity of O(n * m * log(m)) and a space complexity of O(m).\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n # dp[val] stores the minimum steps to reach \'val\' in the previous round\n dp = {-1: 0}\n\n # Sort and remove duplicates from arr2\n arr2.sort()\n # arr2 = list(set(arr2))\n\n for arr1_val in arr1:\n # Initialize a new dictionary to store the minimum steps for the next round\n newDp = collections.defaultdict(lambda: math.inf)\n\n for val, steps in dp.items():\n # Keep the value \'arr1_val\' from arr1\n if arr1_val > val:\n newDp[arr1_val] = min(newDp[arr1_val], steps)\n\n # using values from arr2\n i = bisect_right(arr2, val)\n if i < len(arr2):\n newDp[arr2[i]] = min(newDp[arr2[i]], steps + 1)\n\n # If newDp is empty, it means there is no way to make arr1 strictly increasing\n if not newDp:\n return -1\n\n dp = newDp\n\n # Return the minimum steps required to make arr1 strictly increasing\n return min(dp.values())\n``` | 1 | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null |
✅ 99% Clear code | Full Explanation | Similar idea from the hint | make-array-strictly-increasing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo make `arr1` strictly increasing, we need to consider two options for each element in `arr1`:\n1. Keep the current value from `arr1`.\n2. Replace the current value from `arr1` with a value from `arr2`.\n\nThe goal is to find the minimum number of operations (assignments) required to make `arr1` strictly increasing. To achieve this, we can use dynamic programming to keep track of the minimum steps needed for each value in `arr1` in the previous round.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a dictionary, `dp`, to store the minimum steps to reach a particular value in the previous round. Initialize it with a single key-value pair `{-1: 0}`. The `-1` represents an imaginary value that acts as the initial state.\n2. Sort `arr2` in non-decreasing order and remove duplicates.\n3. Iterate through each value, `arr1_val`, in `arr1`:\n - Initialize a new dictionary, `newDp`, to store the minimum steps for the next round. Use `defaultdict` from the `collections` module to set the default value of each key to infinity.\n - Iterate through each key-value pair, `val` and `steps`, in `dp`:\n - If `arr1_val` is greater than `val`, it means we can keep the current value from `arr1`. In this case, update `newDp[arr1_val]` to the minimum value between `newDp[arr1_val]` and `steps`.\n - Find the index, `i`, using the `bisect_right` function, to locate the position in `arr2` where we can find the next greater value than `val`.\n - If `i` is less than the length of `arr2`, it means there is a valid value in `arr2` to replace the current value from `arr1`. In this case, update `newDp[arr2[i]]` to the minimum value between `newDp[arr2[i]]` and `steps + 1`.\n - If `newDp` is empty, it means there is no way to make `arr1` strictly increasing. Return -1.\n - Update `dp` with the values from `newDp` for the next round.\n4. Return the minimum value among all the values in `dp`.\n# Complexity\n- Time complexity: O(n * m * log(m))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Explanation:\n- Sorting `arr2` takes O(m * log(m)) time.\n- The outer loop iterates through each element in `arr1`, resulting in O(n) iterations.\n- The inner loop iterates through each key-value pair in `dp`, resulting in a maximum of m iterations.\n- The `bisect_right` function used within the inner loop takes O(log(m)) time.\n- Overall, the time complexity is O(n * m * log(m)).\n\nThe space complexity of the solution is O(m) due to the usage of the `dp` dictionary to store the minimum steps for each value. The size of the dictionary `dp` is at most m since we consider each element in `arr2` once.\n\nIn addition to the space complexity, there is also some auxiliary space used for intermediate computations, such as sorting `arr2` and creating the deduplicated list. However, these do not contribute significantly to the overall space complexity compared to the size of `dp`.\n\nOverall, the solution has a time complexity of O(n * m * log(m)) and a space complexity of O(m).\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n # dp[val] stores the minimum steps to reach \'val\' in the previous round\n dp = {-1: 0}\n\n # Sort and remove duplicates from arr2\n arr2.sort()\n # arr2 = list(set(arr2))\n\n for arr1_val in arr1:\n # Initialize a new dictionary to store the minimum steps for the next round\n newDp = collections.defaultdict(lambda: math.inf)\n\n for val, steps in dp.items():\n # Keep the value \'arr1_val\' from arr1\n if arr1_val > val:\n newDp[arr1_val] = min(newDp[arr1_val], steps)\n\n # using values from arr2\n i = bisect_right(arr2, val)\n if i < len(arr2):\n newDp[arr2[i]] = min(newDp[arr2[i]], steps + 1)\n\n # If newDp is empty, it means there is no way to make arr1 strictly increasing\n if not newDp:\n return -1\n\n dp = newDp\n\n # Return the minimum steps required to make arr1 strictly increasing\n return min(dp.values())\n``` | 1 | Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`. | Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates. |
[Pyhton3] [3D DP] top down/ memoization | make-array-strictly-increasing | 0 | 1 | # Intuition\n3 dimensional dp, one dimension for arr1 pointer, one for arr2 pointer and one is used a flag for previous element if it\'s from arr1 or arr2\n\n# Approach\nTop down memoization approach, dp(a,b,c): a for indicating the index we traversed for arr1 and b for arr2 and c for flagging if the previous element is from arr1 or arr2 (takes 0 or 1)\n\nfor example:\ndp(2,1,0) indicates that we are at 2 index (0 indexed) of arr1 and 1 index at arr2 and the previous element used is from arr1 i.e, arr1[1].\n\n# Complexity\n- Time complexity: n^2\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: n^2\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n @cache\n def dp(a,b,c):\n ans = math.inf\n if c: prev = arr2[b-1]\n else: prev = arr1[a-1]\n if a == len(arr1): return 0\n if prev < arr1[a]: ans = min(ans, dp(a+1,b,0))\n if b < len(arr2) and prev < arr2[b]: ans = min(ans, 1+dp(a+1,b+1,1))\n if b < len(arr2) and prev >= arr2[b]:ans = min(ans, dp(a,b+1,c))\n return ans\n\n arr2.sort()\n ans = dp(1,0,0)\n if arr2[0] < arr1[0]: ans = min(ans, 1+dp(1,1,1))\n if ans == math.inf: return -1\n return ans\n``` | 1 | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null |
[Pyhton3] [3D DP] top down/ memoization | make-array-strictly-increasing | 0 | 1 | # Intuition\n3 dimensional dp, one dimension for arr1 pointer, one for arr2 pointer and one is used a flag for previous element if it\'s from arr1 or arr2\n\n# Approach\nTop down memoization approach, dp(a,b,c): a for indicating the index we traversed for arr1 and b for arr2 and c for flagging if the previous element is from arr1 or arr2 (takes 0 or 1)\n\nfor example:\ndp(2,1,0) indicates that we are at 2 index (0 indexed) of arr1 and 1 index at arr2 and the previous element used is from arr1 i.e, arr1[1].\n\n# Complexity\n- Time complexity: n^2\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: n^2\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n @cache\n def dp(a,b,c):\n ans = math.inf\n if c: prev = arr2[b-1]\n else: prev = arr1[a-1]\n if a == len(arr1): return 0\n if prev < arr1[a]: ans = min(ans, dp(a+1,b,0))\n if b < len(arr2) and prev < arr2[b]: ans = min(ans, 1+dp(a+1,b+1,1))\n if b < len(arr2) and prev >= arr2[b]:ans = min(ans, dp(a,b+1,c))\n return ans\n\n arr2.sort()\n ans = dp(1,0,0)\n if arr2[0] < arr1[0]: ans = min(ans, 1+dp(1,1,1))\n if ans == math.inf: return -1\n return ans\n``` | 1 | Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`. | Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates. |
Code simpler than Editorial : With Explanation 😎✌🏼 | make-array-strictly-increasing | 0 | 1 | # Code\n```\nfrom typing import List\nimport bisect\n\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n # Sort arr2 in ascending order\n arr2.sort()\n\n n = len(arr1)\n INF = float(\'inf\')\n\n # Initialize a DP table with dimensions (n+1) x (n+1)\n # dp[i][j] represents the minimum value that can be placed at the end of an increasing subsequence\n # of length i, where j is the number of elements taken from arr2.\n dp = [[INF] * (n + 1) for _ in range(n + 1)]\n dp[0][0] = -INF\n\n for i in range(1, n + 1):\n for j in range(i + 1):\n # If arr1[i-1] is greater than the last element of the previous subsequence (dp[i-1][j]),\n # we can extend the subsequence without using an operation.\n if arr1[i - 1] > dp[i - 1][j]:\n dp[i][j] = min(dp[i][j], arr1[i - 1])\n\n # If j > 0, it means we have already used some elements from arr2.\n # In that case, we can try replacing the last element of the previous subsequence (dp[i-1][j-1])\n # with a smaller element from arr2 to make the subsequence longer.\n if j > 0:\n k = bisect.bisect_right(arr2, dp[i - 1][j - 1])\n if k < len(arr2):\n dp[i][j] = min(dp[i][j], arr2[k])\n\n # Find the minimum number of elements taken from arr2 to make arr1 strictly increasing.\n # If no solution is found, return -1.\n for j in range(n + 1):\n if dp[n][j] != INF:\n return j\n\n return -1\n\n```\n\n### *Kindly Upvote \u270C\uD83C\uDFFC* | 2 | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null |
Code simpler than Editorial : With Explanation 😎✌🏼 | make-array-strictly-increasing | 0 | 1 | # Code\n```\nfrom typing import List\nimport bisect\n\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n # Sort arr2 in ascending order\n arr2.sort()\n\n n = len(arr1)\n INF = float(\'inf\')\n\n # Initialize a DP table with dimensions (n+1) x (n+1)\n # dp[i][j] represents the minimum value that can be placed at the end of an increasing subsequence\n # of length i, where j is the number of elements taken from arr2.\n dp = [[INF] * (n + 1) for _ in range(n + 1)]\n dp[0][0] = -INF\n\n for i in range(1, n + 1):\n for j in range(i + 1):\n # If arr1[i-1] is greater than the last element of the previous subsequence (dp[i-1][j]),\n # we can extend the subsequence without using an operation.\n if arr1[i - 1] > dp[i - 1][j]:\n dp[i][j] = min(dp[i][j], arr1[i - 1])\n\n # If j > 0, it means we have already used some elements from arr2.\n # In that case, we can try replacing the last element of the previous subsequence (dp[i-1][j-1])\n # with a smaller element from arr2 to make the subsequence longer.\n if j > 0:\n k = bisect.bisect_right(arr2, dp[i - 1][j - 1])\n if k < len(arr2):\n dp[i][j] = min(dp[i][j], arr2[k])\n\n # Find the minimum number of elements taken from arr2 to make arr1 strictly increasing.\n # If no solution is found, return -1.\n for j in range(n + 1):\n if dp[n][j] != INF:\n return j\n\n return -1\n\n```\n\n### *Kindly Upvote \u270C\uD83C\uDFFC* | 2 | Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`. | Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates. |
Concise Code w/ Explanation | make-array-strictly-increasing | 0 | 1 | # Intuition\nOur inputs are `arr1` and `arr2`. We can treat (`arr1[i:]`, `arr2`) as subproblems, for index `0 <= i <= len(arr1)`.\n\nFor each index `i`, we can choose to do one of the following:\n* Replace `arr1[i]` with the first value in `arr2` that is strictly greater than `arr1[i - 1]` (if such value in `arr2` exists)\n* Keep `arr1[i]` untouched (if `arr1[i]` > `arr1[i - 1]`)\n\nNote that, **if** no value in `arr2` is strictly greater than `arr[i - 1]` **AND** `arr[i] <= arr[i - 1]`: no solution exists for this subproblem.\n\nAs we may have replaced `arr[i - 1]` with a value from `arr2` before we come to the current subproblem (`arr1[i:]`, `arr2`), we will maintain a variable `p` to indicate `arr[i - 1]`. `p` will be passed to the subproblems.\n\nTo find the first value in `arr2` that is strictly greater than `arr[i - 1]`, we can sort `arr2`, then perform binary search.\n\n> **Tip:** In Python, you can use `bisect_left` to find the index of such value. If `bisect_left(arr2, p + 1)` returns `len(arr2)`, then no value in `arr2` is strictly greater than `p`. (Note: we are using `p` to indicate `arr[i - 1]`, since `arr[i - 1]` may be changed)\n\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n n, m = len(arr1), len(arr2)\n arr2.sort()\n \n @cache\n def dfs(i: int, p: int) -> int:\n if i == n: return 0\n j = bisect_left(arr2, p + 1)\n return min(\n dfs(i + 1, arr2[j]) + 1 if j < m else inf,\n dfs(i + 1, arr1[i]) if i == 0 or arr1[i] > p else inf\n )\n\n res = dfs(0, min(arr2) - 1)\n return res if res < inf else -1\n\n```\n\n# Annotated Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n n, m = len(arr1), len(arr2)\n # Sorting arr2 to allow binary search later\n arr2.sort()\n \n @cache\n def dfs(i: int, p: int) -> int:\n # When i == len(arr1), we have the subproblem ([], arr2).\n # Since arr1 would be empty by definition, no replacements\n # will be needed.\n if i == n: return 0\n\n # This will return the index of the first value from arr2 that\n # is strictly greater than p (which refers to arr[i - 1] in\n # our case). When j == len(arr2), no such value exists in arr2.\n j = bisect_left(arr2, p + 1)\n\n return min(\n # Replace arr1[i] with arr2[j] if the afordmentioned\n # value exists in `arr2`.\n dfs(i + 1, arr2[j]) + 1 if j < m else inf,\n\n # Leave arr1[i] untouched only if we can do so:\n # that\'s only when arr[i] > p (refers to arr[i - 1]).\n dfs(i + 1, arr1[i]) if i == 0 or arr1[i] > p else inf\n )\n\n res = dfs(0, min(arr2) - 1)\n\n # When res == inf, we have no valid solution. Please see the\n # intuition section above.\n return res if res < inf else -1\n\n``` | 5 | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null |
Concise Code w/ Explanation | make-array-strictly-increasing | 0 | 1 | # Intuition\nOur inputs are `arr1` and `arr2`. We can treat (`arr1[i:]`, `arr2`) as subproblems, for index `0 <= i <= len(arr1)`.\n\nFor each index `i`, we can choose to do one of the following:\n* Replace `arr1[i]` with the first value in `arr2` that is strictly greater than `arr1[i - 1]` (if such value in `arr2` exists)\n* Keep `arr1[i]` untouched (if `arr1[i]` > `arr1[i - 1]`)\n\nNote that, **if** no value in `arr2` is strictly greater than `arr[i - 1]` **AND** `arr[i] <= arr[i - 1]`: no solution exists for this subproblem.\n\nAs we may have replaced `arr[i - 1]` with a value from `arr2` before we come to the current subproblem (`arr1[i:]`, `arr2`), we will maintain a variable `p` to indicate `arr[i - 1]`. `p` will be passed to the subproblems.\n\nTo find the first value in `arr2` that is strictly greater than `arr[i - 1]`, we can sort `arr2`, then perform binary search.\n\n> **Tip:** In Python, you can use `bisect_left` to find the index of such value. If `bisect_left(arr2, p + 1)` returns `len(arr2)`, then no value in `arr2` is strictly greater than `p`. (Note: we are using `p` to indicate `arr[i - 1]`, since `arr[i - 1]` may be changed)\n\n# Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n n, m = len(arr1), len(arr2)\n arr2.sort()\n \n @cache\n def dfs(i: int, p: int) -> int:\n if i == n: return 0\n j = bisect_left(arr2, p + 1)\n return min(\n dfs(i + 1, arr2[j]) + 1 if j < m else inf,\n dfs(i + 1, arr1[i]) if i == 0 or arr1[i] > p else inf\n )\n\n res = dfs(0, min(arr2) - 1)\n return res if res < inf else -1\n\n```\n\n# Annotated Code\n```\nclass Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n n, m = len(arr1), len(arr2)\n # Sorting arr2 to allow binary search later\n arr2.sort()\n \n @cache\n def dfs(i: int, p: int) -> int:\n # When i == len(arr1), we have the subproblem ([], arr2).\n # Since arr1 would be empty by definition, no replacements\n # will be needed.\n if i == n: return 0\n\n # This will return the index of the first value from arr2 that\n # is strictly greater than p (which refers to arr[i - 1] in\n # our case). When j == len(arr2), no such value exists in arr2.\n j = bisect_left(arr2, p + 1)\n\n return min(\n # Replace arr1[i] with arr2[j] if the afordmentioned\n # value exists in `arr2`.\n dfs(i + 1, arr2[j]) + 1 if j < m else inf,\n\n # Leave arr1[i] untouched only if we can do so:\n # that\'s only when arr[i] > p (refers to arr[i - 1]).\n dfs(i + 1, arr1[i]) if i == 0 or arr1[i] > p else inf\n )\n\n res = dfs(0, min(arr2) - 1)\n\n # When res == inf, we have no valid solution. Please see the\n # intuition section above.\n return res if res < inf else -1\n\n``` | 5 | Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number.
Return the _decimal value_ of the number in the linked list.
The **most significant bit** is at the head of the linked list.
**Example 1:**
**Input:** head = \[1,0,1\]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
**Example 2:**
**Input:** head = \[0\]
**Output:** 0
**Constraints:**
* The Linked List is not empty.
* Number of nodes will not exceed `30`.
* Each node's value is either `0` or `1`. | Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates. |
using Counter() | maximum-number-of-balloons | 0 | 1 | # Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n CountText = Counter(text)\n balloon = Counter("balloon")\n\n res = len(text)\n for c in balloon:\n res = min(res,CountText[c]//balloon[c])\n return res\n\n\n \n``` | 1 | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. |
using Counter() | maximum-number-of-balloons | 0 | 1 | # Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n CountText = Counter(text)\n balloon = Counter("balloon")\n\n res = len(text)\n for c in balloon:\n res = min(res,CountText[c]//balloon[c])\n return res\n\n\n \n``` | 1 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Python use Counter 2 lines (my first solution up plz :)) | maximum-number-of-balloons | 0 | 1 | # Approach\nUse Counter and don\'t worry about it\n\n# Complexity\n- Time complexity: O(n)\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n cnt = Counter(text)\n return min([cnt[\'b\'], cnt[\'a\'], cnt[\'n\'], cnt[\'l\'] // 2, cnt[\'o\'] // 2])\n\n``` | 7 | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. |
Python use Counter 2 lines (my first solution up plz :)) | maximum-number-of-balloons | 0 | 1 | # Approach\nUse Counter and don\'t worry about it\n\n# Complexity\n- Time complexity: O(n)\n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n cnt = Counter(text)\n return min([cnt[\'b\'], cnt[\'a\'], cnt[\'n\'], cnt[\'l\'] // 2, cnt[\'o\'] // 2])\n\n``` | 7 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Easiest Python O(n) Solution O(1) space | maximum-number-of-balloons | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI saw multiple solutions implementing hash map here, which was also the first thing I thought about but came to think of an easier way to do this. The main thing here is to realise is that you can create the word "balloon" only as along as you have all the characters. For example if you have 5 of b,a,l,l,o,o but only 2 n then you can only make 2 balloon since you won\'t have n for the next.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount the number of each letter in balloon, ie b,a,l,o,n for l and o take integer div by 2 since we need 2 characters per word\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)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n b = text.count(\'b\')\n a = text.count(\'a\')\n l = text.count(\'l\')//2\n o = text.count(\'o\')//2\n n = text.count(\'n\')\n \n return min(b,a,l,o,n)\n\n\n``` | 13 | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. |
Easiest Python O(n) Solution O(1) space | maximum-number-of-balloons | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI saw multiple solutions implementing hash map here, which was also the first thing I thought about but came to think of an easier way to do this. The main thing here is to realise is that you can create the word "balloon" only as along as you have all the characters. For example if you have 5 of b,a,l,l,o,o but only 2 n then you can only make 2 balloon since you won\'t have n for the next.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount the number of each letter in balloon, ie b,a,l,o,n for l and o take integer div by 2 since we need 2 characters per word\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)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n b = text.count(\'b\')\n a = text.count(\'a\')\n l = text.count(\'l\')//2\n o = text.count(\'o\')//2\n n = text.count(\'n\')\n \n return min(b,a,l,o,n)\n\n\n``` | 13 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Python Solution using Counter() | maximum-number-of-balloons | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n ctrText = Counter(text)\n cntB, cntA, cntN = ctrText[\'b\'], ctrText[\'a\'], ctrText[\'n\']\n cntL, cntO = ctrText[\'l\'] // 2, ctrText[\'o\'] // 2\n return min(cntB, cntA, cntL, cntO, cntN)\n``` | 1 | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. |
Python Solution using Counter() | maximum-number-of-balloons | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n ctrText = Counter(text)\n cntB, cntA, cntN = ctrText[\'b\'], ctrText[\'a\'], ctrText[\'n\']\n cntL, cntO = ctrText[\'l\'] // 2, ctrText[\'o\'] // 2\n return min(cntB, cntA, cntL, cntO, cntN)\n``` | 1 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Runtime: 100% | Memory Usage: 100% | One-Line [Python3] | maximum-number-of-balloons | 0 | 1 | ```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n return min(text.count(\'b\'), text.count(\'a\'), text.count(\'l\') // 2, text.count(\'o\') // 2, text.count(\'n\'))\n``` | 31 | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. |
Runtime: 100% | Memory Usage: 100% | One-Line [Python3] | maximum-number-of-balloons | 0 | 1 | ```\nclass Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n return min(text.count(\'b\'), text.count(\'a\'), text.count(\'l\') // 2, text.count(\'o\') // 2, text.count(\'n\'))\n``` | 31 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
[Python3] 1-liner | maximum-number-of-balloons | 0 | 1 | ```\nclass Solution:\n def maxNumberOfBalloons(self, t: str) -> int:\n return min(t.count(\'b\'), t.count(\'a\'), t.count(\'l\') // 2, t.count(\'o\') // 2, t.count(\'n\'))\n```\n* For fun\n```\nclass Solution:\n def maxNumberOfBalloons(self, t: str) -> int:\n return min(t.count(c) // int(cnt) for c, cnt in zip(\'balon\', \'11221\'))\n```\n@lee215\'s\n```\nclass Solution:\n def maxNumberOfBalloons(self, t: str) -> int:\n return min(t.count(c) // \'balloon\'.count(c) for c in \'balon\')\n``` | 26 | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. |
[Python3] 1-liner | maximum-number-of-balloons | 0 | 1 | ```\nclass Solution:\n def maxNumberOfBalloons(self, t: str) -> int:\n return min(t.count(\'b\'), t.count(\'a\'), t.count(\'l\') // 2, t.count(\'o\') // 2, t.count(\'n\'))\n```\n* For fun\n```\nclass Solution:\n def maxNumberOfBalloons(self, t: str) -> int:\n return min(t.count(c) // int(cnt) for c, cnt in zip(\'balon\', \'11221\'))\n```\n@lee215\'s\n```\nclass Solution:\n def maxNumberOfBalloons(self, t: str) -> int:\n return min(t.count(c) // \'balloon\'.count(c) for c in \'balon\')\n``` | 26 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababcaab ", maxLetters = 2, minSize = 3, maxSize = 4
**Output:** 2
**Explanation:** Substring "aab " has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
**Example 2:**
**Input:** s = "aaaa ", maxLetters = 1, minSize = 3, maxSize = 3
**Output:** 2
**Explanation:** Substring "aaa " occur 2 times in the string. It can overlap.
**Constraints:**
* `1 <= s.length <= 105`
* `1 <= maxLetters <= 26`
* `1 <= minSize <= maxSize <= min(26, s.length)`
* `s` consists of only lowercase English letters. | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
PYTHON SOL | RECURSION AND STACK SOL | DETAILED EXPLANATION WITH PICTRUE | | reverse-substrings-between-each-pair-of-parentheses | 0 | 1 | # PICTURE EXPLANATION\n\n\n\n\n\n\n# RECURSION BASED CODE\n```\nclass Solution:\n def reverseParentheses(self, s: str) -> str:\n def solve(string):\n n = len(string)\n word = ""\n i = 0\n while i <n:\n if string[i] == \'(\':\n new = ""\n count = 0\n while True:\n count += 1 if string[i] == \'(\' else -1 if string[i] == \')\' else 0\n if count == 0: break\n new += string[i]\n i += 1\n i += 1\n word += solve(new[1:])\n else:\n word += string[i]\n i += 1\n return word[::-1]\n return solve(s)[::-1]\n \n```\n\n# STACK BASED CODE \n```\nclass Solution:\n def reverseParentheses(self, s: str) -> str:\n stack = []\n for i in s:\n if i == \')\':\n tmp = ""\n while stack[-1] != \'(\':\n tmp += stack.pop()\n stack.pop()\n for j in tmp: stack.append(j)\n else:\n stack.append(i)\n return "".join(stack)\n``` | 6 | You are given a string `s` that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should **not** contain any brackets.
**Example 1:**
**Input:** s = "(abcd) "
**Output:** "dcba "
**Example 2:**
**Input:** s = "(u(love)i) "
**Output:** "iloveu "
**Explanation:** The substring "love " is reversed first, then the whole string is reversed.
**Example 3:**
**Input:** s = "(ed(et(oc))el) "
**Output:** "leetcode "
**Explanation:** First, we reverse the substring "oc ", then "etco ", and finally, the whole string.
**Constraints:**
* `1 <= s.length <= 2000`
* `s` only contains lower case English characters and parentheses.
* It is guaranteed that all parentheses are balanced. | Try to model the problem as a graph problem. The given graph is a tree. The problem is reduced to finding the lowest common ancestor of two nodes in a tree. |
PYTHON SOL | RECURSION AND STACK SOL | DETAILED EXPLANATION WITH PICTRUE | | reverse-substrings-between-each-pair-of-parentheses | 0 | 1 | # PICTURE EXPLANATION\n\n\n\n\n\n\n# RECURSION BASED CODE\n```\nclass Solution:\n def reverseParentheses(self, s: str) -> str:\n def solve(string):\n n = len(string)\n word = ""\n i = 0\n while i <n:\n if string[i] == \'(\':\n new = ""\n count = 0\n while True:\n count += 1 if string[i] == \'(\' else -1 if string[i] == \')\' else 0\n if count == 0: break\n new += string[i]\n i += 1\n i += 1\n word += solve(new[1:])\n else:\n word += string[i]\n i += 1\n return word[::-1]\n return solve(s)[::-1]\n \n```\n\n# STACK BASED CODE \n```\nclass Solution:\n def reverseParentheses(self, s: str) -> str:\n stack = []\n for i in s:\n if i == \')\':\n tmp = ""\n while stack[-1] != \'(\':\n tmp += stack.pop()\n stack.pop()\n for j in tmp: stack.append(j)\n else:\n stack.append(i)\n return "".join(stack)\n``` | 6 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of the boxes you can open after opening the `ith` box.
* `containedBoxes[i]` is a list of the boxes you found inside the `ith` box.
You are given an integer array `initialBoxes` that contains the labels of the boxes you initially have. You can take all the candies in **any open box** and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return _the maximum number of candies you can get following the rules above_.
**Example 1:**
**Input:** status = \[1,0,1,0\], candies = \[7,5,4,100\], keys = \[\[\],\[\],\[1\],\[\]\], containedBoxes = \[\[1,2\],\[3\],\[\],\[\]\], initialBoxes = \[0\]
**Output:** 16
**Explanation:** You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.
Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.
In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.
Total number of candies collected = 7 + 4 + 5 = 16 candy.
**Example 2:**
**Input:** status = \[1,0,0,0,0,0\], candies = \[1,1,1,1,1,1\], keys = \[\[1,2,3,4,5\],\[\],\[\],\[\],\[\],\[\]\], containedBoxes = \[\[1,2,3,4,5\],\[\],\[\],\[\],\[\],\[\]\], initialBoxes = \[0\]
**Output:** 6
**Explanation:** You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.
The total number of candies will be 6.
**Constraints:**
* `n == status.length == candies.length == keys.length == containedBoxes.length`
* `1 <= n <= 1000`
* `status[i]` is either `0` or `1`.
* `1 <= candies[i] <= 1000`
* `0 <= keys[i].length <= n`
* `0 <= keys[i][j] < n`
* All values of `keys[i]` are **unique**.
* `0 <= containedBoxes[i].length <= n`
* `0 <= containedBoxes[i][j] < n`
* All values of `containedBoxes[i]` are unique.
* Each box is contained in one box at most.
* `0 <= initialBoxes.length <= n`
* `0 <= initialBoxes[i] < n` | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
[Python3] Kadane Algorithm | k-concatenation-maximum-sum | 0 | 1 | # Intuition\nLongest continuos sum of sub-array containing negative number -> Kadane algorithm\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe can iterate all over the arr `k` times and do kadane in it. It will work perfectly but not smart enough to pass all test cases. You will meet TLE in some cases. Even Kadane is smart but this way can be considerer brute-force with ones who\'ve already knew about Kadane.\n\nKadane is a greedy algorithm but with this cases we can do it more greedily to avoid iterate the arr `k` times.\nTo do it there are 2 cases that can return the max sum that we should consider:\n- Taking the whole arr k-th times and sum it.\n- Taking 1 semgment of sub-array that length is smaller than length arr * k\n- Then we should find the maximum between 2 cases.\n\nWhy it should work:\n- first of all we take all array if and only if sum of an array is positive (think it greedily). If it is negative we cannot take it we can only take segment of sub-array to get the max. With this we just need to calculate the sum of `arr` and sum it `k` times.\n- Consider this example: `arr` = `[0,0,3,9,-2,-5,4]` and `k` = 5. You can see the `sum` of `arr` is `9` so the max sum is 9 * 5 = 45 (correct answer).\n- What about this cases: `arr` = `[-5,-2,0,0,3,9,-2,-5,4]` and `k` = 5. `sum` of `arr` is `2` but the sum is not 2 * 5 like before. it is 9 + 2 * 4 = 17. How to find that we see that if we choose to take the whole array we always have to take the next `k-1` sub-array and max end part of the 1st array. The max end part of 1st sub-array can be find by kadane and you can find it `9` that why we have `9 + 2 * 4`\n- You may say that the maximum sum get from kadane for the first array does not come from the ending sub-array of the first array to make it continuos with the left but it does since we apply this equation with non-negative sum of array.\n- There are also a case the sum of whole sub-array is smaller than the sum of segment of sub-array. You can think about that if sum of array is positive but small and `k` is small too -> for example sum array is 1 and k is 2 -> if we apply the above equation the answer will be 2 It is failed in this case. `arr` = `[-1,1,2,3,-8,4]` and `k` = `2`. `sum` of `arr` is `1` which is positive so if we take all elements the `max_sum` is 1 * 2 = 2. However if we take only subarray the `max_sum` will be bigger. let see this array repeat 2 times will be `[-1,1,2,3,-8,4,-1,1,2,3,-8,4]` -> if we take sub-array from the 1st index (0-based index) to the 9th index the sum will be:\n1 + 2 + 3 - 8 + 4 - 1 + 1 + 2 + 3 = 7. And yeah `7` is the correct answer in this case\n- Thus we only need to care about 2 cases as I said which can minimize a lot of calulation.\n- For the case getting sub-array. It can be from only one array or it can come from 2 consecutive array. With k=1 we can only check from only 1 array that is why I use `min(k, 2)`\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)$$ -->\n\n# Code\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n s, mod = sum(arr), 10 ** 9 + 7\n n = len(arr)\n\n def kadane(l: int) -> int:\n cur_s = max_s = 0\n for i in range(l):\n num = arr[i % n]\n cur_s = max(0, cur_s + num)\n max_s = max(max_s, cur_s)\n return max_s\n\n if s > 0: return max((kadane(n) + s * (k - 1)), kadane(n * min(k, 2))) % mod\n``` | 3 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104` | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
[Python3] Kadane Algorithm | k-concatenation-maximum-sum | 0 | 1 | # Intuition\nLongest continuos sum of sub-array containing negative number -> Kadane algorithm\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe can iterate all over the arr `k` times and do kadane in it. It will work perfectly but not smart enough to pass all test cases. You will meet TLE in some cases. Even Kadane is smart but this way can be considerer brute-force with ones who\'ve already knew about Kadane.\n\nKadane is a greedy algorithm but with this cases we can do it more greedily to avoid iterate the arr `k` times.\nTo do it there are 2 cases that can return the max sum that we should consider:\n- Taking the whole arr k-th times and sum it.\n- Taking 1 semgment of sub-array that length is smaller than length arr * k\n- Then we should find the maximum between 2 cases.\n\nWhy it should work:\n- first of all we take all array if and only if sum of an array is positive (think it greedily). If it is negative we cannot take it we can only take segment of sub-array to get the max. With this we just need to calculate the sum of `arr` and sum it `k` times.\n- Consider this example: `arr` = `[0,0,3,9,-2,-5,4]` and `k` = 5. You can see the `sum` of `arr` is `9` so the max sum is 9 * 5 = 45 (correct answer).\n- What about this cases: `arr` = `[-5,-2,0,0,3,9,-2,-5,4]` and `k` = 5. `sum` of `arr` is `2` but the sum is not 2 * 5 like before. it is 9 + 2 * 4 = 17. How to find that we see that if we choose to take the whole array we always have to take the next `k-1` sub-array and max end part of the 1st array. The max end part of 1st sub-array can be find by kadane and you can find it `9` that why we have `9 + 2 * 4`\n- You may say that the maximum sum get from kadane for the first array does not come from the ending sub-array of the first array to make it continuos with the left but it does since we apply this equation with non-negative sum of array.\n- There are also a case the sum of whole sub-array is smaller than the sum of segment of sub-array. You can think about that if sum of array is positive but small and `k` is small too -> for example sum array is 1 and k is 2 -> if we apply the above equation the answer will be 2 It is failed in this case. `arr` = `[-1,1,2,3,-8,4]` and `k` = `2`. `sum` of `arr` is `1` which is positive so if we take all elements the `max_sum` is 1 * 2 = 2. However if we take only subarray the `max_sum` will be bigger. let see this array repeat 2 times will be `[-1,1,2,3,-8,4,-1,1,2,3,-8,4]` -> if we take sub-array from the 1st index (0-based index) to the 9th index the sum will be:\n1 + 2 + 3 - 8 + 4 - 1 + 1 + 2 + 3 = 7. And yeah `7` is the correct answer in this case\n- Thus we only need to care about 2 cases as I said which can minimize a lot of calulation.\n- For the case getting sub-array. It can be from only one array or it can come from 2 consecutive array. With k=1 we can only check from only 1 array that is why I use `min(k, 2)`\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)$$ -->\n\n# Code\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n s, mod = sum(arr), 10 ** 9 + 7\n n = len(arr)\n\n def kadane(l: int) -> int:\n cur_s = max_s = 0\n for i in range(l):\n num = arr[i % n]\n cur_s = max(0, cur_s + num)\n max_s = max(max_s, cur_s)\n return max_s\n\n if s > 0: return max((kadane(n) + s * (k - 1)), kadane(n * min(k, 2))) % mod\n``` | 3 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105` | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Python 3 || 2-7 lines, two versions, w/ example || T/M: 99% / 12% | k-concatenation-maximum-sum | 0 | 1 | \nSame algorithm used by most of the other posted solutions.\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n\n if max(arr)<= 0 : return 0 # arr = [-5,4,7,-2]\n sm, ct, mx, = sum(arr), 0, 0 # sm = 4\n # arr.extend(arr) = [-5,4,7,-2,-5,4,7,-2]\n if k > 1: arr.extend(arr) # \n # n = [-5, 2, 4, 6,-5, 2, 4, 6]\n for n in arr: # ct = [ 0, 4,11, 9, 4, 8,15,13]\n ct = max(ct + n, 0) # mx = [ 0, 4,11,11,11,11,15,15]\n mx = max(mx, ct) # \n # 15 + (3-2)*4*(3 > 1)*(4 > 0)\n # 15 + 1*4 * True*True = 19 <-- return\n return (mx + (k-2) * sm * (k > 1) * (sm > 0)) % 1000000007\n```\nHere\'s the two-line version, using `accumulate`.\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n \n acc = list(accumulate(chain(*[arr]*(2-(k==1))),\n lambda x,y: max(0,x+y), initial = 0))\n \n return (max(acc) + (k-2)*sum(arr)*(sum(arr)>0)*(k>1))%1000000007\n```\n[https://leetcode.com/problems/k-concatenation-maximum-sum/submissions/875659809/](http://)\n[https://leetcode.com/problems/k-concatenation-maximum-sum/submissions/875654833/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1). | 5 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104` | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
Python 3 || 2-7 lines, two versions, w/ example || T/M: 99% / 12% | k-concatenation-maximum-sum | 0 | 1 | \nSame algorithm used by most of the other posted solutions.\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n\n if max(arr)<= 0 : return 0 # arr = [-5,4,7,-2]\n sm, ct, mx, = sum(arr), 0, 0 # sm = 4\n # arr.extend(arr) = [-5,4,7,-2,-5,4,7,-2]\n if k > 1: arr.extend(arr) # \n # n = [-5, 2, 4, 6,-5, 2, 4, 6]\n for n in arr: # ct = [ 0, 4,11, 9, 4, 8,15,13]\n ct = max(ct + n, 0) # mx = [ 0, 4,11,11,11,11,15,15]\n mx = max(mx, ct) # \n # 15 + (3-2)*4*(3 > 1)*(4 > 0)\n # 15 + 1*4 * True*True = 19 <-- return\n return (mx + (k-2) * sm * (k > 1) * (sm > 0)) % 1000000007\n```\nHere\'s the two-line version, using `accumulate`.\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n \n acc = list(accumulate(chain(*[arr]*(2-(k==1))),\n lambda x,y: max(0,x+y), initial = 0))\n \n return (max(acc) + (k-2)*sum(arr)*(sum(arr)>0)*(k>1))%1000000007\n```\n[https://leetcode.com/problems/k-concatenation-maximum-sum/submissions/875659809/](http://)\n[https://leetcode.com/problems/k-concatenation-maximum-sum/submissions/875654833/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1). | 5 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105` | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
A short and sweet Python solution with a not so short and not so sweet explanation | k-concatenation-maximum-sum | 0 | 1 | ```python\nfrom math import inf as oo\n\n\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n total = sum(arr)\n kadanes = self.maxSubArraySum(arr)\n if (k < 2): return kadanes%(10**9+7)\n if (total > 0): return (kadanes + (k-1)*total)%(10**9+7)\n stitchedKadanes = self.maxSubArraySum(arr*2)\n return stitchedKadanes%(10**9+7)\n \n \n def maxSubArraySum(self, a):\n size = len(a)\n max_so_far = -oo\n max_ending_here = 0\n \n for i in a:\n max_ending_here += i\n if max_ending_here < 0: max_ending_here=0\n max_so_far = max(max_so_far, max_ending_here)\n\n return max_so_far\n```\n\nOk here we go, the first thing to note is Kadane\'s Algorithm. I literally yoinked it from ***.org. It\'s a pretty easy to memorize algorithm that is useful here because it can find a maximum sum of a contiguous subarray. That\'s the entire point of this problem. Now, if we didn\'t have memory contraints, we could have done this: `return max(0, self.maxSubArraySum(arr*k)`, which would copy the array k times, and send it over to Kadane\'s algorithm to find the largest subarray sum in `n*k` time. However `n <= 10**5` and `k <= 10**5`, so `n*k == 10**10` number of elements are way too many elements to store. Even if these were simply ints you would need at least 38GB of *free* RAM to store that many elements. The second option is to just modify kadane\'s with a little bit of modular arithmetic:\n```python\ndef kConcatenationMaxSum(self, a: List[int], k: int) -> int:\n size = len(a)\n max_so_far = -oo\n max_ending_here = 0\n\n for i in range(size*k): \n max_ending_here += a[i%size]\n if max_ending_here < 0: max_ending_here=0\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n```\n\nBut now we get to discuss runtime complexity. Again, this algorithm runs in `n*k` time, so that can be as long as `10**10`. If you want, try running this on your own:\n\n```python\nfrom time import time as t\nfrom math import inf as oo\n\n\ndef kConcatenationMaxSum(a, k):\n size = len(a)\n max_so_far = -oo\n max_ending_here = 0\n\n for i in range(size*k): \n max_ending_here += a[i%size]\n if max_ending_here < 0: max_ending_here=0\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n\n\nl = list(range(10**5))\nfor i in range(6):\n num = 10**i\n start = t()\n kConcatenationMaxSum(l, num)\n print(t()-start)\n```\n\nGiven a list of `10**5` elements, it\'ll run `kConcatenationMaxSum` it\'ll do a for looping testing k = 10\\*\\*0, 10\\*\\*1, 10\\*\\*2, 10\\*\\*3, 10\\*\\*4, and 10\\*\\*5, and print the time it took to run, if you\'re patient enough to wait that is. Regardless though, I don\'t think LeetCode will give you enough time and we can do better anyway.\n\nSo let\'s start with the case where `k=1`\nWhen k = 1, we don\'t have to do any copying, so we know that the sum Kadane\'s returns will be our maximum sum.\n\nLet\'s move on to all the other cases where `k >= 2`.\n\nWe have two more cases, first: `total > 0`\n`total` in this case is the sum of the entire input array. For this case, where `total > 0`, let\'s look at this example:\n```python\narr = [-1,-2,8,12,3,9,-2,-1]\nk = 2\n```\nThe sum of `arr` is 26. So `total = 26 > 0`.\nLet\'s find our kadane\'s array: `kadanesArr = [8,12,3,9]`. Note that `kadanesSum = sum(kadanesArr) = 32\nNow let\'s extend copy our array so that it matches `k`:\n```python\narrK2 = [-1,-2,8,12,3,9,-2,-1,-1,-2,8,12,3,9,-2,-1]\n```\nNow let\'s find our kadane\'s array here: `[8,12,3,9,-2,-1,-1,-2,8,12,3,9]`\nLet\'s break that into two arrays: `subArr1 = [8,12,3,9]` and `subArr2 = [-2,-1,-1,-2,8,12,3,9]`\nFinally, let\'s rearrange `subArr2`: `[-1,-2,8,12,3,9,-2,-1]` Notice that now `arr == subArr2`! Which means `sum(subArr2) == sum(arr)`. Also, notice that `subArr1 == kadanesArr`.\nSo if we put all that together, that means *every element between our first kadane\'s array and our last kadane\'s array on the kth array copy will increase our sum*. So in this case, every element from our **first** 8 to our **last** 9 is useful, let\'s pretend k is 3 instead of 2 and extend our array one last time to drive home the point:\n```python\narrK3 = [-1,-2,8,12,3,9,-2,-1,-1,-2,8,12,3,9,-2,-1,-1,-2,8,12,3,9,-2,-1]\n```\nIf we use our logic we\'ve uncovered, then every element from our first 8 at position 2, to our last 9 at position 22 is useful, and the sum of this subarray from position 2 through 22 then is 84. Let\'s break out our subarray from position 8 to position 22 into 3 sub arrays:\n```python\nsubarrA = [8,12,3,9]\nsubarrB = [-2,-1,-1,-2,8,12,3,9]\nsubarrC = [-2,-1,-1,-2,8,12,3,9]\n```\nAgain, notice `sum(subarrA) == kadanesSum`, and `sum(subarrB) == sum(subarrC) == sum(arr) == total`. so in this case then, `sum(subarrA) + sum(subarrB) + sum(subarrC) == kadanesSum + total + total == kadanesSum + 2*total == kadanesSum + (k-1)*total == 84`. Perfect!\n\nFinally, the last case: `total <= 0`\nThere\'s an observation to be made here, Let\'s look at an example which I will purposefully obfuscate numbers:\n```python\narrTotNotPositive = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\nnewK = 3\n```\nLet\'s say our kadane\'s array is: `greekKadanesArr = [\u03B4,\u03B5]`\nand our `greekKadanesSum = \u03A3`\nLet\'s say that `sum(arrTotNotPositive) == greekTotal == 0`\nThen we know that if we tried: `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]` we\'d simply get `\u03A3`, because `greekKadanesSum + greekTotal == \u03A3 + 0 == \u03A3`. So what if we tried only a piece of the second array instead? `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4]` Notice here that it\'s still just `arrTotNotPositive + [\u03B4]`, so the sum is `\u03A3 + \u03B4`. However, I can guarantee that this is less than `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]`, why? Because `sum([\u03B4,\u03B5])` is guaranteed to be the largest subarray sum by kadanes, so therefore, `\u03B4 + \u03B5 > \u03B4` or else kadanes would not have included `\u03B5`. Therefore, `\u03A3 + \u03B4 + \u03B5 > \u03A3 + \u03B4`. So moving on, let\'s drop one more, `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3]`, this is just `arrTotNotPositive` so therefore this total is just `greekTotal == 0`. Again, let\'s drop one more, `[\u03B4,\u03B5] + [\u03B1,\u03B2]`. Finally, we\'re somewhere interesting. Because this is `greekKadanesSum + sum([\u03B1,\u03B2])`. We don\'t know if `sum([\u03B1,\u03B2])` is positive or not. But we can find out real easily, by making a copy of k, and sending through kadane\'s, by calling `stitchedKadanes = maxSubArraySum([\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5])`. If `stitchedKadanes != kadanes`, it obviously means that either `greekKadanesSum + sum([\u03B1,\u03B2]) > greekKadanesSum` or `greekKadanesSum + \u03B1 > greekKadanesSum`, since we\'ve covered all the other cases. Let\'s just choose one to work with for this example, `stitchedKadanes = greekKadanesSum + sum([\u03B1,\u03B2])`. Here, let\'s remember that `newK = 3`, however let\'s remember that `greekTotal == 0` as well, so let\'s look at our `arrTotNotPositive` after 3 copies:\n```python\narrTotNotPositiveK3 = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\n```\nSo if we ran Kadane\'s on `arrTotNotPositiveK3`, we\'d get this:\n```python\ngreekK3 = [\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2]\n```\nLet\'s break `greekK3` into subarrays again. \n```python\nsubGreekA = [\u03B4,\u03B5] => \u03A3\nsubGreekB = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5] => 0\nsubGreekC = [\u03B1,\u03B2] => sum([\u03B1,\u03B2])\n```\nNotice the sum total, it\'s `\u03A3 + 0 + sum([\u03B1,\u03B2]) == \u03A3 + sum([\u03B1,\u03B2]) == stitchedKadanes`. Therefore, no matter what `newK` is, for how many times we copy `arrTotNotPositive`, it will always just be `stitchedKadanes + 0*(newK-1)`.\nLet\'s keep using this example:\n```python\narrTotNotPositive = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\nnewK = 3\n```\nand these stay the same:\nkadane\'s array is: `greekKadanesArr = [\u03B4,\u03B5]`\nand `greekKadanesSum = \u03A3`\nbut now,\nLet\'s say that `sum(arrTotNotPositive) == greekNegTotal < 0`\nSo let\'s first start by trying to add one whole copy to our greekKadanesArr again: `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]` Then we know this is `\u03A3 + greekNegTotal < \u03A3` because `greekNegTotal < 0`. Let\'s try dropping one again resulting in : `sum([\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4]) == sum([\u03B4,\u03B5,\u03B1,\u03B2,\u03B3] + [\u03B4]) == sum([\u03B1,\u03B2,\u03B3,\u03B4,\u03B5] + [\u03B4]) == greekNegTotal + \u03B4`. Once again, `greekNegTotal + \u03B4 < greekNegTotal + \u03B4 + \u03B5`, because we know that `\u03B4 < \u03B4 + \u03B5`. Drop one more, `sum([\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3])` and we just get `greekNegTotal` which is obviously less than `\u03A3` because Kadane\'s only returns subarray sums >= 0 (at least the way this one is written). One more time, `sum([\u03B4,\u03B5] + [\u03B1,\u03B2])`, and notice that we can determine if this is larger than `\u03A3` with `stitchedKadanes = maxSubArraySum([\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5])`. We\'ll pretend again that this returned `[\u03B4,\u03B5,\u03B1,\u03B2]`. Now let\'s look at `newK = 3` again. Here\'s a reminder of `arrTotNotPositiveK3`\n```python\narrTotNotPositiveK3 = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\n```\nLet\'s break down this array directly:\n```python\ngarbage = [\u03B1,\u03B2,\u03B3]\nsubK3A = [\u03B4,\u03B5,\u03B1,\u03B2] => stitchedKadanes\nsubK3B = [\u03B3,\u03B4,\u03B5,\u03B1,\u03B2] => greekNegTotal\nsubK3C = [\u03B3,\u03B4,\u03B5] => The rest of the array\n```\nWe\'re ignoring `garbage` because its part of our very first copy of our `arrTotNotPositive`, since we performed Kadane\'s on the very first copy, we know that adding any more elements from `garbage` to kadane\'s is only going to make lower the sum of our normal kadane\'s. Following is `subK3A`, which is just the subarray that `stitchedKadanes` returned, so we know this is the subarray that creates the maximum subarray. Next, we have `subK3B`, Notice that it\'s just a repeat of our entire array again, so it\'s sum is `greekNegTotal`, and since that is less than zero, we don\'t want to add it to our `stitchedKadanes` sum because it\'s just going to drop the sum of our stitched kadane\'s. Since we don\'t add it, we can\'t reach `subK3C` because we would no longer be contiguous. Meaning any copy of our input array past this point isn\'t going to be touched either. Therefore, if `total <= 0`, the observation to be made is that *you will never need more than two copies of the input array*. With that knowledge, you can apply Kadane\'s to the array because it\'s bounded by `2n`.\n\nLet me know if this helps you. I\'m trying to get better at my explanations, so feel free to leave a comment with your constructive criticism. | 26 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104` | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
A short and sweet Python solution with a not so short and not so sweet explanation | k-concatenation-maximum-sum | 0 | 1 | ```python\nfrom math import inf as oo\n\n\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n total = sum(arr)\n kadanes = self.maxSubArraySum(arr)\n if (k < 2): return kadanes%(10**9+7)\n if (total > 0): return (kadanes + (k-1)*total)%(10**9+7)\n stitchedKadanes = self.maxSubArraySum(arr*2)\n return stitchedKadanes%(10**9+7)\n \n \n def maxSubArraySum(self, a):\n size = len(a)\n max_so_far = -oo\n max_ending_here = 0\n \n for i in a:\n max_ending_here += i\n if max_ending_here < 0: max_ending_here=0\n max_so_far = max(max_so_far, max_ending_here)\n\n return max_so_far\n```\n\nOk here we go, the first thing to note is Kadane\'s Algorithm. I literally yoinked it from ***.org. It\'s a pretty easy to memorize algorithm that is useful here because it can find a maximum sum of a contiguous subarray. That\'s the entire point of this problem. Now, if we didn\'t have memory contraints, we could have done this: `return max(0, self.maxSubArraySum(arr*k)`, which would copy the array k times, and send it over to Kadane\'s algorithm to find the largest subarray sum in `n*k` time. However `n <= 10**5` and `k <= 10**5`, so `n*k == 10**10` number of elements are way too many elements to store. Even if these were simply ints you would need at least 38GB of *free* RAM to store that many elements. The second option is to just modify kadane\'s with a little bit of modular arithmetic:\n```python\ndef kConcatenationMaxSum(self, a: List[int], k: int) -> int:\n size = len(a)\n max_so_far = -oo\n max_ending_here = 0\n\n for i in range(size*k): \n max_ending_here += a[i%size]\n if max_ending_here < 0: max_ending_here=0\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n```\n\nBut now we get to discuss runtime complexity. Again, this algorithm runs in `n*k` time, so that can be as long as `10**10`. If you want, try running this on your own:\n\n```python\nfrom time import time as t\nfrom math import inf as oo\n\n\ndef kConcatenationMaxSum(a, k):\n size = len(a)\n max_so_far = -oo\n max_ending_here = 0\n\n for i in range(size*k): \n max_ending_here += a[i%size]\n if max_ending_here < 0: max_ending_here=0\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n\n\nl = list(range(10**5))\nfor i in range(6):\n num = 10**i\n start = t()\n kConcatenationMaxSum(l, num)\n print(t()-start)\n```\n\nGiven a list of `10**5` elements, it\'ll run `kConcatenationMaxSum` it\'ll do a for looping testing k = 10\\*\\*0, 10\\*\\*1, 10\\*\\*2, 10\\*\\*3, 10\\*\\*4, and 10\\*\\*5, and print the time it took to run, if you\'re patient enough to wait that is. Regardless though, I don\'t think LeetCode will give you enough time and we can do better anyway.\n\nSo let\'s start with the case where `k=1`\nWhen k = 1, we don\'t have to do any copying, so we know that the sum Kadane\'s returns will be our maximum sum.\n\nLet\'s move on to all the other cases where `k >= 2`.\n\nWe have two more cases, first: `total > 0`\n`total` in this case is the sum of the entire input array. For this case, where `total > 0`, let\'s look at this example:\n```python\narr = [-1,-2,8,12,3,9,-2,-1]\nk = 2\n```\nThe sum of `arr` is 26. So `total = 26 > 0`.\nLet\'s find our kadane\'s array: `kadanesArr = [8,12,3,9]`. Note that `kadanesSum = sum(kadanesArr) = 32\nNow let\'s extend copy our array so that it matches `k`:\n```python\narrK2 = [-1,-2,8,12,3,9,-2,-1,-1,-2,8,12,3,9,-2,-1]\n```\nNow let\'s find our kadane\'s array here: `[8,12,3,9,-2,-1,-1,-2,8,12,3,9]`\nLet\'s break that into two arrays: `subArr1 = [8,12,3,9]` and `subArr2 = [-2,-1,-1,-2,8,12,3,9]`\nFinally, let\'s rearrange `subArr2`: `[-1,-2,8,12,3,9,-2,-1]` Notice that now `arr == subArr2`! Which means `sum(subArr2) == sum(arr)`. Also, notice that `subArr1 == kadanesArr`.\nSo if we put all that together, that means *every element between our first kadane\'s array and our last kadane\'s array on the kth array copy will increase our sum*. So in this case, every element from our **first** 8 to our **last** 9 is useful, let\'s pretend k is 3 instead of 2 and extend our array one last time to drive home the point:\n```python\narrK3 = [-1,-2,8,12,3,9,-2,-1,-1,-2,8,12,3,9,-2,-1,-1,-2,8,12,3,9,-2,-1]\n```\nIf we use our logic we\'ve uncovered, then every element from our first 8 at position 2, to our last 9 at position 22 is useful, and the sum of this subarray from position 2 through 22 then is 84. Let\'s break out our subarray from position 8 to position 22 into 3 sub arrays:\n```python\nsubarrA = [8,12,3,9]\nsubarrB = [-2,-1,-1,-2,8,12,3,9]\nsubarrC = [-2,-1,-1,-2,8,12,3,9]\n```\nAgain, notice `sum(subarrA) == kadanesSum`, and `sum(subarrB) == sum(subarrC) == sum(arr) == total`. so in this case then, `sum(subarrA) + sum(subarrB) + sum(subarrC) == kadanesSum + total + total == kadanesSum + 2*total == kadanesSum + (k-1)*total == 84`. Perfect!\n\nFinally, the last case: `total <= 0`\nThere\'s an observation to be made here, Let\'s look at an example which I will purposefully obfuscate numbers:\n```python\narrTotNotPositive = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\nnewK = 3\n```\nLet\'s say our kadane\'s array is: `greekKadanesArr = [\u03B4,\u03B5]`\nand our `greekKadanesSum = \u03A3`\nLet\'s say that `sum(arrTotNotPositive) == greekTotal == 0`\nThen we know that if we tried: `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]` we\'d simply get `\u03A3`, because `greekKadanesSum + greekTotal == \u03A3 + 0 == \u03A3`. So what if we tried only a piece of the second array instead? `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4]` Notice here that it\'s still just `arrTotNotPositive + [\u03B4]`, so the sum is `\u03A3 + \u03B4`. However, I can guarantee that this is less than `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]`, why? Because `sum([\u03B4,\u03B5])` is guaranteed to be the largest subarray sum by kadanes, so therefore, `\u03B4 + \u03B5 > \u03B4` or else kadanes would not have included `\u03B5`. Therefore, `\u03A3 + \u03B4 + \u03B5 > \u03A3 + \u03B4`. So moving on, let\'s drop one more, `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3]`, this is just `arrTotNotPositive` so therefore this total is just `greekTotal == 0`. Again, let\'s drop one more, `[\u03B4,\u03B5] + [\u03B1,\u03B2]`. Finally, we\'re somewhere interesting. Because this is `greekKadanesSum + sum([\u03B1,\u03B2])`. We don\'t know if `sum([\u03B1,\u03B2])` is positive or not. But we can find out real easily, by making a copy of k, and sending through kadane\'s, by calling `stitchedKadanes = maxSubArraySum([\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5])`. If `stitchedKadanes != kadanes`, it obviously means that either `greekKadanesSum + sum([\u03B1,\u03B2]) > greekKadanesSum` or `greekKadanesSum + \u03B1 > greekKadanesSum`, since we\'ve covered all the other cases. Let\'s just choose one to work with for this example, `stitchedKadanes = greekKadanesSum + sum([\u03B1,\u03B2])`. Here, let\'s remember that `newK = 3`, however let\'s remember that `greekTotal == 0` as well, so let\'s look at our `arrTotNotPositive` after 3 copies:\n```python\narrTotNotPositiveK3 = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\n```\nSo if we ran Kadane\'s on `arrTotNotPositiveK3`, we\'d get this:\n```python\ngreekK3 = [\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2]\n```\nLet\'s break `greekK3` into subarrays again. \n```python\nsubGreekA = [\u03B4,\u03B5] => \u03A3\nsubGreekB = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5] => 0\nsubGreekC = [\u03B1,\u03B2] => sum([\u03B1,\u03B2])\n```\nNotice the sum total, it\'s `\u03A3 + 0 + sum([\u03B1,\u03B2]) == \u03A3 + sum([\u03B1,\u03B2]) == stitchedKadanes`. Therefore, no matter what `newK` is, for how many times we copy `arrTotNotPositive`, it will always just be `stitchedKadanes + 0*(newK-1)`.\nLet\'s keep using this example:\n```python\narrTotNotPositive = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\nnewK = 3\n```\nand these stay the same:\nkadane\'s array is: `greekKadanesArr = [\u03B4,\u03B5]`\nand `greekKadanesSum = \u03A3`\nbut now,\nLet\'s say that `sum(arrTotNotPositive) == greekNegTotal < 0`\nSo let\'s first start by trying to add one whole copy to our greekKadanesArr again: `[\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]` Then we know this is `\u03A3 + greekNegTotal < \u03A3` because `greekNegTotal < 0`. Let\'s try dropping one again resulting in : `sum([\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3,\u03B4]) == sum([\u03B4,\u03B5,\u03B1,\u03B2,\u03B3] + [\u03B4]) == sum([\u03B1,\u03B2,\u03B3,\u03B4,\u03B5] + [\u03B4]) == greekNegTotal + \u03B4`. Once again, `greekNegTotal + \u03B4 < greekNegTotal + \u03B4 + \u03B5`, because we know that `\u03B4 < \u03B4 + \u03B5`. Drop one more, `sum([\u03B4,\u03B5] + [\u03B1,\u03B2,\u03B3])` and we just get `greekNegTotal` which is obviously less than `\u03A3` because Kadane\'s only returns subarray sums >= 0 (at least the way this one is written). One more time, `sum([\u03B4,\u03B5] + [\u03B1,\u03B2])`, and notice that we can determine if this is larger than `\u03A3` with `stitchedKadanes = maxSubArraySum([\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5])`. We\'ll pretend again that this returned `[\u03B4,\u03B5,\u03B1,\u03B2]`. Now let\'s look at `newK = 3` again. Here\'s a reminder of `arrTotNotPositiveK3`\n```python\narrTotNotPositiveK3 = [\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5,\u03B1,\u03B2,\u03B3,\u03B4,\u03B5]\n```\nLet\'s break down this array directly:\n```python\ngarbage = [\u03B1,\u03B2,\u03B3]\nsubK3A = [\u03B4,\u03B5,\u03B1,\u03B2] => stitchedKadanes\nsubK3B = [\u03B3,\u03B4,\u03B5,\u03B1,\u03B2] => greekNegTotal\nsubK3C = [\u03B3,\u03B4,\u03B5] => The rest of the array\n```\nWe\'re ignoring `garbage` because its part of our very first copy of our `arrTotNotPositive`, since we performed Kadane\'s on the very first copy, we know that adding any more elements from `garbage` to kadane\'s is only going to make lower the sum of our normal kadane\'s. Following is `subK3A`, which is just the subarray that `stitchedKadanes` returned, so we know this is the subarray that creates the maximum subarray. Next, we have `subK3B`, Notice that it\'s just a repeat of our entire array again, so it\'s sum is `greekNegTotal`, and since that is less than zero, we don\'t want to add it to our `stitchedKadanes` sum because it\'s just going to drop the sum of our stitched kadane\'s. Since we don\'t add it, we can\'t reach `subK3C` because we would no longer be contiguous. Meaning any copy of our input array past this point isn\'t going to be touched either. Therefore, if `total <= 0`, the observation to be made is that *you will never need more than two copies of the input array*. With that knowledge, you can apply Kadane\'s to the array because it\'s bounded by `2n`.\n\nLet me know if this helps you. I\'m trying to get better at my explanations, so feel free to leave a comment with your constructive criticism. | 26 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105` | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Python 1-Liner Solution | k-concatenation-maximum-sum | 0 | 1 | # Code\n```\n\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n return (max(list(accumulate(chain(*[arr]*(2-(k==1))),\n lambda x,y: max(0,x+y), initial = 0))) + (k-2)*sum(arr)*(sum(arr)>0)*(k>1))%1000000007\n``` | 1 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104` | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
Python 1-Liner Solution | k-concatenation-maximum-sum | 0 | 1 | # Code\n```\n\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n return (max(list(accumulate(chain(*[arr]*(2-(k==1))),\n lambda x,y: max(0,x+y), initial = 0))) + (k-2)*sum(arr)*(sum(arr)>0)*(k>1))%1000000007\n``` | 1 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105` | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
python 3 || Kadane's Algorithim || O(n)/O(1) | k-concatenation-maximum-sum | 0 | 1 | ```\nclass Solution:\n def kConcatenationMaxSum(self, nums: List[int], k: int) -> int:\n def maxSum(k):\n res = cur = 0\n for _ in range(k):\n for num in nums:\n cur = max(cur + num, num)\n res = max(res, cur)\n \n return res\n \n return (max(0, k - 2) * max(0, sum(nums)) + maxSum(min(2, k))) % (10 ** 9 + 7) | 0 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104` | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
python 3 || Kadane's Algorithim || O(n)/O(1) | k-concatenation-maximum-sum | 0 | 1 | ```\nclass Solution:\n def kConcatenationMaxSum(self, nums: List[int], k: int) -> int:\n def maxSum(k):\n res = cur = 0\n for _ in range(k):\n for num in nums:\n cur = max(cur + num, num)\n res = max(res, cur)\n \n return res\n \n return (max(0, k - 2) * max(0, sum(nums)) + maxSum(min(2, k))) % (10 ** 9 + 7) | 0 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105` | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Consider all cases, with kadane for the basic case | k-concatenation-maximum-sum | 0 | 1 | # Code\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n max_so_far = 0\n max_ending_here = 0\n maxpre = 0\n currpre = 0\n for a in arr:\n currpre += a\n maxpre = max(currpre,maxpre)\n max_ending_here += a\n if max_so_far < max_ending_here:\n max_so_far = max_ending_here\n if max_ending_here < 0: max_ending_here = 0\n maxsuf = 0\n currsuf = 0\n for a in arr[::-1]:\n currsuf += a\n maxsuf = max(maxsuf,currsuf)\n\n \n s = sum(arr)\n if k == 1: return max_so_far\n return max([s*k, max_so_far, maxsuf + maxpre + (k-2)*s, maxsuf + maxpre]) % (10**9+7)\n\n``` | 0 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104` | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
Consider all cases, with kadane for the basic case | k-concatenation-maximum-sum | 0 | 1 | # Code\n```\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n max_so_far = 0\n max_ending_here = 0\n maxpre = 0\n currpre = 0\n for a in arr:\n currpre += a\n maxpre = max(currpre,maxpre)\n max_ending_here += a\n if max_so_far < max_ending_here:\n max_so_far = max_ending_here\n if max_ending_here < 0: max_ending_here = 0\n maxsuf = 0\n currsuf = 0\n for a in arr[::-1]:\n currsuf += a\n maxsuf = max(maxsuf,currsuf)\n\n \n s = sum(arr)\n if k == 1: return max_so_far\n return max([s*k, max_so_far, maxsuf + maxpre + (k-2)*s, maxsuf + maxpre]) % (10**9+7)\n\n``` | 0 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest element to the right of index 0 is index 1 (18).
- index 1 --> the greatest element to the right of index 1 is index 4 (6).
- index 2 --> the greatest element to the right of index 2 is index 4 (6).
- index 3 --> the greatest element to the right of index 3 is index 4 (6).
- index 4 --> the greatest element to the right of index 4 is index 5 (1).
- index 5 --> there are no elements to the right of index 5, so we put -1.
**Example 2:**
**Input:** arr = \[400\]
**Output:** \[-1\]
**Explanation:** There are no elements to the right of index 0.
**Constraints:**
* `1 <= arr.length <= 104`
* `1 <= arr[i] <= 105` | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.