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 |
---|---|---|---|---|---|---|---|
DFS/Greedy unique solution | number-of-ways-to-reconstruct-a-tree | 0 | 1 | # Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def checkWays(self, pairs):\n nodes, graph, degree = set(), defaultdict(set), defaultdict(int)\n\n for i, j in pairs:\n nodes |= {i, j}\n graph[i].add(j)\n graph[j].add(i)\n degree[i] += 1\n degree[j] += 1\n\n if max(degree.values()) < len(nodes) - 1:\n return 0\n\n def has_different_parents(n):\n for nn in graph[n]:\n if degree[n] >= degree[nn]:\n neighbor = graph[nn]\n if neighbor - {n} - graph[n]:\n return True\n return False\n\n for n in nodes:\n if degree[n] < len(nodes) - 1:\n if has_different_parents(n):\n return 0\n\n if any(degree[n] == degree[nn] for n in nodes for nn in graph[n]):\n return 2\n\n return 1\n``` | 0 | You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and:
* There are no duplicates.
* `xi < yi`
Let `ways` be the number of rooted trees that satisfy the following conditions:
* The tree consists of nodes whose values appeared in `pairs`.
* A pair `[xi, yi]` exists in `pairs` **if and only if** `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`.
* **Note:** the tree does not have to be a binary tree.
Two ways are considered to be different if there is at least one node that has different parents in both ways.
Return:
* `0` if `ways == 0`
* `1` if `ways == 1`
* `2` if `ways > 1`
A **rooted tree** is a tree that has a single root node, and all edges are oriented to be outgoing from the root.
An **ancestor** of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.
**Example 1:**
**Input:** pairs = \[\[1,2\],\[2,3\]\]
**Output:** 1
**Explanation:** There is exactly one valid rooted tree, which is shown in the above figure.
**Example 2:**
**Input:** pairs = \[\[1,2\],\[2,3\],\[1,3\]\]
**Output:** 2
**Explanation:** There are multiple valid rooted trees. Three of them are shown in the above figures.
**Example 3:**
**Input:** pairs = \[\[1,2\],\[2,3\],\[2,4\],\[1,5\]\]
**Output:** 0
**Explanation:** There are no valid rooted trees.
**Constraints:**
* `1 <= pairs.length <= 105`
* `1 <= xi < yi <= 500`
* The elements in `pairs` are unique. | Try to put at least one box in the house pushing it from either side. Once you put one box to the house, you can solve the problem with the same logic used to solve version I. You have a warehouse open from the left only and a warehouse open from the right only. |
DFS/Greedy unique solution | number-of-ways-to-reconstruct-a-tree | 0 | 1 | # Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def checkWays(self, pairs):\n nodes, graph, degree = set(), defaultdict(set), defaultdict(int)\n\n for i, j in pairs:\n nodes |= {i, j}\n graph[i].add(j)\n graph[j].add(i)\n degree[i] += 1\n degree[j] += 1\n\n if max(degree.values()) < len(nodes) - 1:\n return 0\n\n def has_different_parents(n):\n for nn in graph[n]:\n if degree[n] >= degree[nn]:\n neighbor = graph[nn]\n if neighbor - {n} - graph[n]:\n return True\n return False\n\n for n in nodes:\n if degree[n] < len(nodes) - 1:\n if has_different_parents(n):\n return 0\n\n if any(degree[n] == degree[nn] for n in nodes for nn in graph[n]):\n return 2\n\n return 1\n``` | 0 | There are `m` boys and `n` girls in a class attending an upcoming party.
You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` girl to the party. A boy can invite at most **one girl**, and a girl can accept at most **one invitation** from a boy.
Return _the **maximum** possible number of accepted invitations._
**Example 1:**
**Input:** grid = \[\[1,1,1\],
\[1,0,1\],
\[0,0,1\]\]
**Output:** 3
**Explanation:** The invitations are sent as follows:
- The 1st boy invites the 2nd girl.
- The 2nd boy invites the 1st girl.
- The 3rd boy invites the 3rd girl.
**Example 2:**
**Input:** grid = \[\[1,0,1,0\],
\[1,0,0,0\],
\[0,0,1,0\],
\[1,1,1,0\]\]
**Output:** 3
**Explanation:** The invitations are sent as follows:
-The 1st boy invites the 3rd girl.
-The 2nd boy invites the 1st girl.
-The 3rd boy invites no one.
-The 4th boy invites the 2nd girl.
**Constraints:**
* `grid.length == m`
* `grid[i].length == n`
* `1 <= m, n <= 200`
* `grid[i][j]` is either `0` or `1`. | Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes. |
Python (Simple Maths) | number-of-ways-to-reconstruct-a-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 checkWays(self, pairs):\n nodes, graph, degree = set(), defaultdict(set), defaultdict(int)\n\n for i,j in pairs:\n nodes |= {i,j}\n graph[i].add(j)\n graph[j].add(i)\n degree[i] += 1\n degree[j] += 1\n\n if max(degree.values()) < len(nodes)-1: return 0\n\n for n in nodes:\n if degree[n] < len(nodes)-1:\n neighbor = set()\n for nn in graph[n]:\n if degree[n] >= degree[nn]: neighbor |= graph[nn]\n if neighbor - {n} - graph[n]: return 0\n\n for n in nodes:\n if any(degree[n] == degree[nn] for nn in graph[n]): return 2\n\n return 1\n\n\n \n\n\n\n\n\n\n\n\n \n\n\n \n\n\n\n``` | 0 | You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and:
* There are no duplicates.
* `xi < yi`
Let `ways` be the number of rooted trees that satisfy the following conditions:
* The tree consists of nodes whose values appeared in `pairs`.
* A pair `[xi, yi]` exists in `pairs` **if and only if** `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`.
* **Note:** the tree does not have to be a binary tree.
Two ways are considered to be different if there is at least one node that has different parents in both ways.
Return:
* `0` if `ways == 0`
* `1` if `ways == 1`
* `2` if `ways > 1`
A **rooted tree** is a tree that has a single root node, and all edges are oriented to be outgoing from the root.
An **ancestor** of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.
**Example 1:**
**Input:** pairs = \[\[1,2\],\[2,3\]\]
**Output:** 1
**Explanation:** There is exactly one valid rooted tree, which is shown in the above figure.
**Example 2:**
**Input:** pairs = \[\[1,2\],\[2,3\],\[1,3\]\]
**Output:** 2
**Explanation:** There are multiple valid rooted trees. Three of them are shown in the above figures.
**Example 3:**
**Input:** pairs = \[\[1,2\],\[2,3\],\[2,4\],\[1,5\]\]
**Output:** 0
**Explanation:** There are no valid rooted trees.
**Constraints:**
* `1 <= pairs.length <= 105`
* `1 <= xi < yi <= 500`
* The elements in `pairs` are unique. | Try to put at least one box in the house pushing it from either side. Once you put one box to the house, you can solve the problem with the same logic used to solve version I. You have a warehouse open from the left only and a warehouse open from the right only. |
Python (Simple Maths) | number-of-ways-to-reconstruct-a-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 checkWays(self, pairs):\n nodes, graph, degree = set(), defaultdict(set), defaultdict(int)\n\n for i,j in pairs:\n nodes |= {i,j}\n graph[i].add(j)\n graph[j].add(i)\n degree[i] += 1\n degree[j] += 1\n\n if max(degree.values()) < len(nodes)-1: return 0\n\n for n in nodes:\n if degree[n] < len(nodes)-1:\n neighbor = set()\n for nn in graph[n]:\n if degree[n] >= degree[nn]: neighbor |= graph[nn]\n if neighbor - {n} - graph[n]: return 0\n\n for n in nodes:\n if any(degree[n] == degree[nn] for nn in graph[n]): return 2\n\n return 1\n\n\n \n\n\n\n\n\n\n\n\n \n\n\n \n\n\n\n``` | 0 | There are `m` boys and `n` girls in a class attending an upcoming party.
You are given an `m x n` integer matrix `grid`, where `grid[i][j]` equals `0` or `1`. If `grid[i][j] == 1`, then that means the `ith` boy can invite the `jth` girl to the party. A boy can invite at most **one girl**, and a girl can accept at most **one invitation** from a boy.
Return _the **maximum** possible number of accepted invitations._
**Example 1:**
**Input:** grid = \[\[1,1,1\],
\[1,0,1\],
\[0,0,1\]\]
**Output:** 3
**Explanation:** The invitations are sent as follows:
- The 1st boy invites the 2nd girl.
- The 2nd boy invites the 1st girl.
- The 3rd boy invites the 3rd girl.
**Example 2:**
**Input:** grid = \[\[1,0,1,0\],
\[1,0,0,0\],
\[0,0,1,0\],
\[1,1,1,0\]\]
**Output:** 3
**Explanation:** The invitations are sent as follows:
-The 1st boy invites the 3rd girl.
-The 2nd boy invites the 1st girl.
-The 3rd boy invites no one.
-The 4th boy invites the 2nd girl.
**Constraints:**
* `grid.length == m`
* `grid[i].length == n`
* `1 <= m, n <= 200`
* `grid[i][j]` is either `0` or `1`. | Think inductively. The first step is to get the root. Obviously, the root should be in pairs with all the nodes. If there isn't exactly one such node, then there are 0 ways. The number of pairs involving a node must be less than or equal to that number of its parent. Actually, if it's equal, then there is not exactly 1 way, because they can be swapped. Recursively, given a set of nodes, get the node with the most pairs, then this must be a root and have no parents in the current set of nodes. |
[Python/Java/CPP/C++] Easy Solution with Explanation [ACCEPTED] | decode-xored-array | 1 | 1 | \n\n**Explanation**\n**a XOR b = c**, we know the values of **a** and **c**. we use the formula to find **b** -> **a XOR c = b** \n**Complexity**\n\nTime ```O(N)```\nSpace ```O(10)```\n\n**Python:**\n```\ndef decode(self, encoded: List[int], first: int) -> List[int]:\n r = [first]\n for i in encoded:\n r.append(r[-1]^i)\n return r\n```\n\n\n**JAVA** \n```\npublic int[] decode(int[] encoded, int first) {\n int[] res = new int[encoded.length+1];\n res[0] = first;\n for(int i = 0; i < encoded.length; i++)\n res[i+1] = res[i] ^ encoded[i];\n return res;\n }\n```\n\n**C++**\n\n```\nvector<int> decode(vector<int>& encoded, int first) {\n vector<int> res;\n res.push_back(first);\n for(int i = 0; i < encoded.size(); i++)\n res.push_back(res[i] ^ encoded[i]);\n return res;\n }\n\n``` | 41 | There is a **hidden** integer array `arr` that consists of `n` non-negative integers.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`.
You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`.
Return _the original array_ `arr`. It can be proved that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[1,2,3\], first = 1
**Output:** \[1,0,2,1\]
**Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\]
**Example 2:**
**Input:** encoded = \[6,2,7,3\], first = 4
**Output:** \[4,2,0,7,4\]
**Constraints:**
* `2 <= n <= 104`
* `encoded.length == n - 1`
* `0 <= encoded[i] <= 105`
* `0 <= first <= 105` | Simulate the process but donβt move the pointer beyond the main folder. Simulate the process but donβt move the pointer beyond the main folder. |
[Python/Java/CPP/C++] Easy Solution with Explanation [ACCEPTED] | decode-xored-array | 1 | 1 | \n\n**Explanation**\n**a XOR b = c**, we know the values of **a** and **c**. we use the formula to find **b** -> **a XOR c = b** \n**Complexity**\n\nTime ```O(N)```\nSpace ```O(10)```\n\n**Python:**\n```\ndef decode(self, encoded: List[int], first: int) -> List[int]:\n r = [first]\n for i in encoded:\n r.append(r[-1]^i)\n return r\n```\n\n\n**JAVA** \n```\npublic int[] decode(int[] encoded, int first) {\n int[] res = new int[encoded.length+1];\n res[0] = first;\n for(int i = 0; i < encoded.length; i++)\n res[i+1] = res[i] ^ encoded[i];\n return res;\n }\n```\n\n**C++**\n\n```\nvector<int> decode(vector<int>& encoded, int first) {\n vector<int> res;\n res.push_back(first);\n for(int i = 0; i < encoded.size(); i++)\n res.push_back(res[i] ^ encoded[i]);\n return res;\n }\n\n``` | 41 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
Easy Solution: Explained! | decode-xored-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n result = []\n for i in range(0, len(encoded)+1):\n if(i == 0):\n result.append(0^first)\n else:\n result.append(encoded[i-1]^result[i-1])\n return result\n\n\'\'\'\nAccording to the property of XOR we know that if c = a ^ b, we can get back a or b if you have other value. \ni.e:\na = c ^ b\nb = c ^ a\nAnd order need not necessarily be the same\n\nSo in this question, we can write the above property as:\nencoded[i] = arr[i] ^ arr[i+1]\n\nWe have encoded array in our hands, and we want the resultant, so simply interchange them:\nresult[0] = first\nresult[i+1] = result[i] ^ encoded[i]\n\'\'\'\n``` | 3 | There is a **hidden** integer array `arr` that consists of `n` non-negative integers.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`.
You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`.
Return _the original array_ `arr`. It can be proved that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[1,2,3\], first = 1
**Output:** \[1,0,2,1\]
**Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\]
**Example 2:**
**Input:** encoded = \[6,2,7,3\], first = 4
**Output:** \[4,2,0,7,4\]
**Constraints:**
* `2 <= n <= 104`
* `encoded.length == n - 1`
* `0 <= encoded[i] <= 105`
* `0 <= first <= 105` | Simulate the process but donβt move the pointer beyond the main folder. Simulate the process but donβt move the pointer beyond the main folder. |
Easy Solution: Explained! | decode-xored-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n result = []\n for i in range(0, len(encoded)+1):\n if(i == 0):\n result.append(0^first)\n else:\n result.append(encoded[i-1]^result[i-1])\n return result\n\n\'\'\'\nAccording to the property of XOR we know that if c = a ^ b, we can get back a or b if you have other value. \ni.e:\na = c ^ b\nb = c ^ a\nAnd order need not necessarily be the same\n\nSo in this question, we can write the above property as:\nencoded[i] = arr[i] ^ arr[i+1]\n\nWe have encoded array in our hands, and we want the resultant, so simply interchange them:\nresult[0] = first\nresult[i+1] = result[i] ^ encoded[i]\n\'\'\'\n``` | 3 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
python solution O(N) | decode-xored-array | 0 | 1 | Time and Space Complexcity O(N)\n```\nclass Solution:\n def decode(self, A: List[int], first: int) -> List[int]:\n ans=[first]\n n=len(A)\n for i in range(n):\n a=ans[-1]^A[i]\n ans.append(a)\n return ans\n \n``` | 1 | There is a **hidden** integer array `arr` that consists of `n` non-negative integers.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`.
You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`.
Return _the original array_ `arr`. It can be proved that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[1,2,3\], first = 1
**Output:** \[1,0,2,1\]
**Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\]
**Example 2:**
**Input:** encoded = \[6,2,7,3\], first = 4
**Output:** \[4,2,0,7,4\]
**Constraints:**
* `2 <= n <= 104`
* `encoded.length == n - 1`
* `0 <= encoded[i] <= 105`
* `0 <= first <= 105` | Simulate the process but donβt move the pointer beyond the main folder. Simulate the process but donβt move the pointer beyond the main folder. |
python solution O(N) | decode-xored-array | 0 | 1 | Time and Space Complexcity O(N)\n```\nclass Solution:\n def decode(self, A: List[int], first: int) -> List[int]:\n ans=[first]\n n=len(A)\n for i in range(n):\n a=ans[-1]^A[i]\n ans.append(a)\n return ans\n \n``` | 1 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
Python - 1 Liner (List Comprehension with Assignment Expresion) | decode-xored-array | 0 | 1 | ```\nclass Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]\n``` | 18 | There is a **hidden** integer array `arr` that consists of `n` non-negative integers.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`.
You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`.
Return _the original array_ `arr`. It can be proved that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[1,2,3\], first = 1
**Output:** \[1,0,2,1\]
**Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\]
**Example 2:**
**Input:** encoded = \[6,2,7,3\], first = 4
**Output:** \[4,2,0,7,4\]
**Constraints:**
* `2 <= n <= 104`
* `encoded.length == n - 1`
* `0 <= encoded[i] <= 105`
* `0 <= first <= 105` | Simulate the process but donβt move the pointer beyond the main folder. Simulate the process but donβt move the pointer beyond the main folder. |
Python - 1 Liner (List Comprehension with Assignment Expresion) | decode-xored-array | 0 | 1 | ```\nclass Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]\n``` | 18 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
PYTHON|C Linear Time Complexity and O(1) space complexity | swapping-nodes-in-a-linked-list | 0 | 1 | # Intuition\nIterate list two times first to get the first index to change second to get the seocnd index while searching for first index we can traverse to get the length also then in second traverse using length find the index number for second element and get to that element. \nJust swap these two values.\n\n# Approach\n1. Initialize two pointers, first_idx and second_idx, to the head of the linked list.\n2. Initialize a variable, len, to 0.\n3. Move the first_idx pointer k-1 times to reach the kth node.\n4. Decrement the value of k by 1.\n5. Iterate over the linked list with the second_idx pointer until the end, incrementing len by 1 each time.\n6. Update the value of len to len - k + 1.\n7. Reset the second_idx pointer to the head of the linked list.\n8. Move the second_idx pointer len times to reach the (len - k + 1)th node.\n9. Swap the values of second_idx->val and first_idx->val.\n10. Return the head of the linked list.\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```c []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nvoid swap(int *ptr1, int *ptr2){\n int temp;\n temp = *ptr1;\n *ptr1 = *ptr2;\n *ptr2 = temp;\n}\nstruct ListNode* swapNodes(struct ListNode* head, int k){\n int n = k-1;\n int len = 0;\n struct ListNode *first_idx = head;\n while(n){\n first_idx = first_idx->next;\n n--;\n len++;\n }\n struct ListNode *second_idx;\n for(second_idx = first_idx; second_idx->next; second_idx = second_idx->next, len++);\n len = len-k+1;\n second_idx = head;\n for(int i=0; i<len; i++){\n second_idx = second_idx->next;\n }\n swap(&second_idx->val, &first_idx->val);\n return head;\n}\n```\n\n```python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n i = k-1\n temp = head\n lens = 0\n while(i and temp.next):\n temp = temp.next\n i -= 1\n lens += 1\n \n t2 = temp\n\n while(t2.next):\n t2 = t2.next\n lens += 1\n\n togo = lens-k+1\n t3 = head \n for i in range(togo):\n t3 = t3.next\n \n t3.val, temp.val = temp.val, t3.val \n\n return head\n```\n\n\nNOTE: \uD83D\uDE05 The python implementation is poorly written with inappropriate variable names.\n\n\n\n | 1 | You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100` | Think simulation Note that the number of turns will never be more than 50 / 4 * n |
PYTHON|C Linear Time Complexity and O(1) space complexity | swapping-nodes-in-a-linked-list | 0 | 1 | # Intuition\nIterate list two times first to get the first index to change second to get the seocnd index while searching for first index we can traverse to get the length also then in second traverse using length find the index number for second element and get to that element. \nJust swap these two values.\n\n# Approach\n1. Initialize two pointers, first_idx and second_idx, to the head of the linked list.\n2. Initialize a variable, len, to 0.\n3. Move the first_idx pointer k-1 times to reach the kth node.\n4. Decrement the value of k by 1.\n5. Iterate over the linked list with the second_idx pointer until the end, incrementing len by 1 each time.\n6. Update the value of len to len - k + 1.\n7. Reset the second_idx pointer to the head of the linked list.\n8. Move the second_idx pointer len times to reach the (len - k + 1)th node.\n9. Swap the values of second_idx->val and first_idx->val.\n10. Return the head of the linked list.\n\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```c []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nvoid swap(int *ptr1, int *ptr2){\n int temp;\n temp = *ptr1;\n *ptr1 = *ptr2;\n *ptr2 = temp;\n}\nstruct ListNode* swapNodes(struct ListNode* head, int k){\n int n = k-1;\n int len = 0;\n struct ListNode *first_idx = head;\n while(n){\n first_idx = first_idx->next;\n n--;\n len++;\n }\n struct ListNode *second_idx;\n for(second_idx = first_idx; second_idx->next; second_idx = second_idx->next, len++);\n len = len-k+1;\n second_idx = head;\n for(int i=0; i<len; i++){\n second_idx = second_idx->next;\n }\n swap(&second_idx->val, &first_idx->val);\n return head;\n}\n```\n\n```python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n i = k-1\n temp = head\n lens = 0\n while(i and temp.next):\n temp = temp.next\n i -= 1\n lens += 1\n \n t2 = temp\n\n while(t2.next):\n t2 = t2.next\n lens += 1\n\n togo = lens-k+1\n t3 = head \n for i in range(togo):\n t3 = t3.next\n \n t3.val, temp.val = temp.val, t3.val \n\n return head\n```\n\n\nNOTE: \uD83D\uDE05 The python implementation is poorly written with inappropriate variable names.\n\n\n\n | 1 | You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times. | We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list |
Solution | swapping-nodes-in-a-linked-list | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n ListNode* swapNodes(ListNode* head, int k) {\n ListNode* temp=head;\n ListNode* first=head;\n ListNode* second=head;\n int count=0,i=k-1;\n while (temp!=NULL)\n {\n if(i==0)\n {\n first=temp;\n }\n temp=temp->next;\n count++;\n i--;\n }\n temp=head;\n while (count-k>0)\n {\n second=second->next;\n count--;\n }\n if (k==1)\n {\n swap(second->val,head->val);\n return head;\n }\n swap(first->val ,second->val);\n return head;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n\n dummNode = ListNode(-1)\n dummNode.next = head\n firstPointer = dummNode\n for i in range(k):\n firstPointer = firstPointer.next\n firstKth = firstPointer\n secondPointer = dummNode\n\n while(firstPointer):\n firstPointer = firstPointer.next\n secondPointer = secondPointer.next\n \n temp = secondPointer.val\n secondPointer.val = firstKth.val\n firstKth.val = temp\n return dummNode.next\n```\n\n```Java []\nclass Solution {\n public ListNode swapNodes(ListNode head, int k) {\n ListNode node1 = head;\n ListNode node2 = head;\n k -= 1;\n while(k-- > 0) node1 = node1.next;\n ListNode ref = node1;\n while(node1.next != null) {\n node1 = node1.next;\n node2 = node2.next;\n }\n int temp = node2.val;\n node2.val = ref.val;\n ref.val = temp;\n return head;\n }\n}\n```\n | 1 | You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100` | Think simulation Note that the number of turns will never be more than 50 / 4 * n |
Solution | swapping-nodes-in-a-linked-list | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n ListNode* swapNodes(ListNode* head, int k) {\n ListNode* temp=head;\n ListNode* first=head;\n ListNode* second=head;\n int count=0,i=k-1;\n while (temp!=NULL)\n {\n if(i==0)\n {\n first=temp;\n }\n temp=temp->next;\n count++;\n i--;\n }\n temp=head;\n while (count-k>0)\n {\n second=second->next;\n count--;\n }\n if (k==1)\n {\n swap(second->val,head->val);\n return head;\n }\n swap(first->val ,second->val);\n return head;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n\n dummNode = ListNode(-1)\n dummNode.next = head\n firstPointer = dummNode\n for i in range(k):\n firstPointer = firstPointer.next\n firstKth = firstPointer\n secondPointer = dummNode\n\n while(firstPointer):\n firstPointer = firstPointer.next\n secondPointer = secondPointer.next\n \n temp = secondPointer.val\n secondPointer.val = firstKth.val\n firstKth.val = temp\n return dummNode.next\n```\n\n```Java []\nclass Solution {\n public ListNode swapNodes(ListNode head, int k) {\n ListNode node1 = head;\n ListNode node2 = head;\n k -= 1;\n while(k-- > 0) node1 = node1.next;\n ListNode ref = node1;\n while(node1.next != null) {\n node1 = node1.next;\n node2 = node2.next;\n }\n int temp = node2.val;\n node2.val = ref.val;\n ref.val = temp;\n return head;\n }\n}\n```\n | 1 | You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times. | We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list |
Python short and clean. Functional programming. | swapping-nodes-in-a-linked-list | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the number of nodes in the linkedlist`\n\n# Code\nImperative:\n```python\nclass Solution:\n def swapNodes(self, head: ListNode | None, k: int) -> ListNode | None:\n sentinal_head = i = j = ListNode(next=head)\n \n for _ in range(k - 1): j = j.next\n k_begin = j\n \n j = j.next\n while j and j.next: i, j = i.next, j.next\n k_end = i\n\n b, e = k_begin.next, k_end.next\n k_begin.next, k_end.next = e, b\n b.next, e.next = e.next, b.next\n \n return sentinal_head.next\n\n\n```\n\nFunctional:\n```python\nclass Solution:\n def swapNodes(self, head: ListNode | None, k: int) -> ListNode | None:\n \n def iter_ll(ll: ListNode | None) -> Iterator[ListNode]:\n while ll: yield ll; ll = ll.next\n \n T = TypeVar(\'T\')\n def last(xs: Iterable[T]) -> T:\n return reduce(lambda _, x: x, xs)\n \n sentinal_head = ListNode(next=head)\n xs, ys = iter_ll(sentinal_head), iter_ll(sentinal_head)\n\n k_begin = next(islice(ys, k - 1, None))\n k_end = last(zip(xs, ys))[0]\n\n b, e = k_begin.next, k_end.next\n k_begin.next, k_end.next = e, b\n b.next, e.next = e.next, b.next\n \n return sentinal_head.next\n\n``` | 2 | You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100` | Think simulation Note that the number of turns will never be more than 50 / 4 * n |
Python short and clean. Functional programming. | swapping-nodes-in-a-linked-list | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the number of nodes in the linkedlist`\n\n# Code\nImperative:\n```python\nclass Solution:\n def swapNodes(self, head: ListNode | None, k: int) -> ListNode | None:\n sentinal_head = i = j = ListNode(next=head)\n \n for _ in range(k - 1): j = j.next\n k_begin = j\n \n j = j.next\n while j and j.next: i, j = i.next, j.next\n k_end = i\n\n b, e = k_begin.next, k_end.next\n k_begin.next, k_end.next = e, b\n b.next, e.next = e.next, b.next\n \n return sentinal_head.next\n\n\n```\n\nFunctional:\n```python\nclass Solution:\n def swapNodes(self, head: ListNode | None, k: int) -> ListNode | None:\n \n def iter_ll(ll: ListNode | None) -> Iterator[ListNode]:\n while ll: yield ll; ll = ll.next\n \n T = TypeVar(\'T\')\n def last(xs: Iterable[T]) -> T:\n return reduce(lambda _, x: x, xs)\n \n sentinal_head = ListNode(next=head)\n xs, ys = iter_ll(sentinal_head), iter_ll(sentinal_head)\n\n k_begin = next(islice(ys, k - 1, None))\n k_end = last(zip(xs, ys))[0]\n\n b, e = k_begin.next, k_end.next\n k_begin.next, k_end.next = e, b\n b.next, e.next = e.next, b.next\n \n return sentinal_head.next\n\n``` | 2 | You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times. | We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list |
Python simple solution beats 99.55% with explanation & key takeaway explained! O(n) time, O(1) space | swapping-nodes-in-a-linked-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet n be the length of the array. Such that m = n - k\nk + m = n: We need to find linklist index at -k. Therefore, it\'s translate to n - k index. Therefore, m is the position. \n\n***\nKey takeaway: m = n - k\n***\n\n\n\nPLZ UPVOTE OR ANYA WILL CRY :(\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n cur = head\n for _ in range (k - 1):\n cur = cur.next\n first = cur\n sec = head\n while cur.next:\n cur = cur.next\n sec = sec.next\n first.val , sec.val = sec.val, first.val\n return head\n \n``` | 2 | You are given the `head` of a linked list, and an integer `k`.
Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= k <= n <= 105`
* `0 <= Node.val <= 100` | Think simulation Note that the number of turns will never be more than 50 / 4 * n |
Python simple solution beats 99.55% with explanation & key takeaway explained! O(n) time, O(1) space | swapping-nodes-in-a-linked-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet n be the length of the array. Such that m = n - k\nk + m = n: We need to find linklist index at -k. Therefore, it\'s translate to n - k index. Therefore, m is the position. \n\n***\nKey takeaway: m = n - k\n***\n\n\n\nPLZ UPVOTE OR ANYA WILL CRY :(\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n cur = head\n for _ in range (k - 1):\n cur = cur.next\n first = cur\n sec = head\n while cur.next:\n cur = cur.next\n sec = sec.next\n first.val , sec.val = sec.val, first.val\n return head\n \n``` | 2 | You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times. | We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list |
Python 3 | DFS, Greedy O(N) | Explanations | minimize-hamming-distance-after-swap-operations | 0 | 1 | ### Explanation\n- First, build a graph\n- Then, traverse each index `i`\n\t- If `i` is not visited, then DFS on it and its neighbors, ultimately\n\t\t- `d[i]` will be a **counter** in type of `defaultdict()`, which represents the neighbors\' values & their frequencies\n\t\t- for any direct/indirect neighbor `nei` of `i`, `d[nei] == i`\n\t- If `i` is visited, ignore\n- Finally, iterator over `target` and counting hamming distance in a greedy way, i.e.\n\t- If it\'s possible to make `source[i] == target[i]` then do it and decrement the **counter**\n\t- If not possible, then `ans += 1`\n- Note: Each connected indices cluster will have it own **counter**, only the `d[i]` keeps a copy of this **counter**, where `i` is the smallest index of a connected indices cluster. e.g. Given\n\t- Source: [1,2,3,4]\n\t- Target: [2,1,4,5]\n\t- allowedSwaps: [[0,1],[2,3]]\n\t- then \n\t`d = {`\n\t\t\t`\t0: defaultdict(<class \'int\'>, {1: 1, 2: 1}), `\n\t\t\t`\t1: 0, `\n\t\t\t`\t2: defaultdict(<class \'int\'>, {3: 1, 4: 1}), `\n\t\t\t`\t3: 2`\n\t`}`\n- Time complexity: `O(N)`. Iterate over `source` with DFS will takes `O(N)` (because you only visited each index once), and also `O(N)` when iterate over `target`. \n- Check out the comment in code blocks for more detail\n### Implementation\n<iframe src="https://leetcode.com/playground/dxroAYZU/shared" frameBorder="0" width="950" height="700"></iframe>\n | 3 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Python 3 | DFS, Greedy O(N) | Explanations | minimize-hamming-distance-after-swap-operations | 0 | 1 | ### Explanation\n- First, build a graph\n- Then, traverse each index `i`\n\t- If `i` is not visited, then DFS on it and its neighbors, ultimately\n\t\t- `d[i]` will be a **counter** in type of `defaultdict()`, which represents the neighbors\' values & their frequencies\n\t\t- for any direct/indirect neighbor `nei` of `i`, `d[nei] == i`\n\t- If `i` is visited, ignore\n- Finally, iterator over `target` and counting hamming distance in a greedy way, i.e.\n\t- If it\'s possible to make `source[i] == target[i]` then do it and decrement the **counter**\n\t- If not possible, then `ans += 1`\n- Note: Each connected indices cluster will have it own **counter**, only the `d[i]` keeps a copy of this **counter**, where `i` is the smallest index of a connected indices cluster. e.g. Given\n\t- Source: [1,2,3,4]\n\t- Target: [2,1,4,5]\n\t- allowedSwaps: [[0,1],[2,3]]\n\t- then \n\t`d = {`\n\t\t\t`\t0: defaultdict(<class \'int\'>, {1: 1, 2: 1}), `\n\t\t\t`\t1: 0, `\n\t\t\t`\t2: defaultdict(<class \'int\'>, {3: 1, 4: 1}), `\n\t\t\t`\t3: 2`\n\t`}`\n- Time complexity: `O(N)`. Iterate over `source` with DFS will takes `O(N)` (because you only visited each index once), and also `O(N)` when iterate over `target`. \n- Check out the comment in code blocks for more detail\n### Implementation\n<iframe src="https://leetcode.com/playground/dxroAYZU/shared" frameBorder="0" width="950" height="700"></iframe>\n | 3 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Fancy Union-Find Approach | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code\n```\nclass UnionFind:\n def __init__(self):\n self.par = {}\n \n def union(self, el1, el2):\n self.par[self.find(el2)] = self.find(el1)\n \n\n def find(self, el):\n p = self.par.get(el, el)\n if p != el:\n p = self.par[el] = self.find(p)\n \n return p\n\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind()\n for i1, i2 in allowedSwaps:\n uf.union(i1, i2)\n \n cntrs = {}\n for i, num in enumerate(source):\n p = uf.find(i)\n cntr = cntrs.setdefault(p, {})\n cntr[num] = cntr.get(num, 0) + 1\n \n for i, num in enumerate(target):\n p = uf.find(i)\n if num in cntrs[p] and cntrs[p][num] > 0:\n cntrs[p][num] -= 1\n \n return sum(cnt for cntr in cntrs.values() for cnt in cntr.values())\n``` | 0 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Fancy Union-Find Approach | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code\n```\nclass UnionFind:\n def __init__(self):\n self.par = {}\n \n def union(self, el1, el2):\n self.par[self.find(el2)] = self.find(el1)\n \n\n def find(self, el):\n p = self.par.get(el, el)\n if p != el:\n p = self.par[el] = self.find(p)\n \n return p\n\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind()\n for i1, i2 in allowedSwaps:\n uf.union(i1, i2)\n \n cntrs = {}\n for i, num in enumerate(source):\n p = uf.find(i)\n cntr = cntrs.setdefault(p, {})\n cntr[num] = cntr.get(num, 0) + 1\n \n for i, num in enumerate(target):\n p = uf.find(i)\n if num in cntrs[p] and cntrs[p][num] > 0:\n cntrs[p][num] -= 1\n \n return sum(cnt for cntr in cntrs.values() for cnt in cntr.values())\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Simple and clear python3 solutions | 1040 ms - faster than 90.82% solutions | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Complexity\n- Time complexity: $$O(n + m \\cdot \\alpha(2 \\cdot 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\nwhere `n = source.length`, `m = allowedSwaps.length`, $\\alpha(n)$ is inverse Ackermann function ([wiki](https://en.wikipedia.org/wiki/Ackermann_function#Inverse))\n\n# Code\n``` python3 []\nclass DJS:\n def __init__(self):\n self._d = {}\n \n def try_make_set(self, a):\n if a not in self._d:\n self._d[a] = a\n \n def find(self, a):\n aa = self._d[a]\n if aa != a:\n self._d[a] = self.find(aa)\n return self._d[a]\n \n def union(self, a, b):\n aa = self.find(a)\n bb = self.find(b)\n if aa != bb:\n self._d[aa] = bb\n \n def get_groups(self):\n result = defaultdict(list)\n for a, aa in self._d.items():\n aaa = self.find(aa)\n result[aaa].append(a)\n return result.values()\n\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n djs = DJS()\n for u, v in allowedSwaps:\n djs.try_make_set(u)\n djs.try_make_set(v)\n djs.union(u, v)\n \n groups = djs.get_groups()\n\n def calc_in_group(indexes):\n s = Counter(source[i] for i in indexes)\n t = Counter(target[i] for i in indexes)\n\n good = 0\n for value, s_cnt in s.items():\n t_cnt = t[value]\n good += min(s_cnt, t_cnt)\n return len(indexes) - good\n\n result = 0\n indexes_in_groups = set()\n for g in groups:\n indexes_in_groups.update(g)\n \n # calculate the Hamming distance within a group\n result += calc_in_group(g)\n\n # calculate Hamming distance outside groups\n for i, (a, b) in enumerate(zip(source, target)):\n if i not in indexes_in_groups:\n if a != b:\n result += 1\n return result\n\n``` | 0 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Simple and clear python3 solutions | 1040 ms - faster than 90.82% solutions | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Complexity\n- Time complexity: $$O(n + m \\cdot \\alpha(2 \\cdot 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\nwhere `n = source.length`, `m = allowedSwaps.length`, $\\alpha(n)$ is inverse Ackermann function ([wiki](https://en.wikipedia.org/wiki/Ackermann_function#Inverse))\n\n# Code\n``` python3 []\nclass DJS:\n def __init__(self):\n self._d = {}\n \n def try_make_set(self, a):\n if a not in self._d:\n self._d[a] = a\n \n def find(self, a):\n aa = self._d[a]\n if aa != a:\n self._d[a] = self.find(aa)\n return self._d[a]\n \n def union(self, a, b):\n aa = self.find(a)\n bb = self.find(b)\n if aa != bb:\n self._d[aa] = bb\n \n def get_groups(self):\n result = defaultdict(list)\n for a, aa in self._d.items():\n aaa = self.find(aa)\n result[aaa].append(a)\n return result.values()\n\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n djs = DJS()\n for u, v in allowedSwaps:\n djs.try_make_set(u)\n djs.try_make_set(v)\n djs.union(u, v)\n \n groups = djs.get_groups()\n\n def calc_in_group(indexes):\n s = Counter(source[i] for i in indexes)\n t = Counter(target[i] for i in indexes)\n\n good = 0\n for value, s_cnt in s.items():\n t_cnt = t[value]\n good += min(s_cnt, t_cnt)\n return len(indexes) - good\n\n result = 0\n indexes_in_groups = set()\n for g in groups:\n indexes_in_groups.update(g)\n \n # calculate the Hamming distance within a group\n result += calc_in_group(g)\n\n # calculate Hamming distance outside groups\n for i, (a, b) in enumerate(zip(source, target)):\n if i not in indexes_in_groups:\n if a != b:\n result += 1\n return result\n\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python UnionFind | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Intuition\nThe idea is that if (0, 1) is exchangeable and (0, 2) is exchangeable,\nthen any apair in (0, 1, 2) can be exchangeble.\n\nThis means, we could build connected components where\neach component is a list of indices that can be exchangeable with any of them.\n\nIn Union find terms, we simply iterate through each allowedSwaps,\nand do a union on the indices in the pair.\n\nAt the end of the union of all the pairs,\nwe will get connected components of indices that\ncan be exchangeable with each other.\n\n\n\n# Code\n```\nclass UnionFind:\n \n def __init__(self, n): \n self.root = list(range(n))\n \n def union(self, x, y): \n self.root[self.find(x)] = self.find(y)\n \n def find(self, x):\n if x != self.root[x]: \n self.root[x] = self.find(self.root[x])\n return self.root[x]\n \n \nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind(len(source))\n for x, y in allowedSwaps: \n uf.union(x, y)\n m = defaultdict(set) # key is the component, value is the set of indices in same component\n for i in range(len(source)):\n m[uf.find(i)].add(i)\n ans = 0\n for indices in m.values():\n A = [source[i] for i in indices]\n B = [target[i] for i in indices]\n ans += sum((Counter(A) - Counter(B)).values())\n return ans\n \n``` | 0 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Python UnionFind | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Intuition\nThe idea is that if (0, 1) is exchangeable and (0, 2) is exchangeable,\nthen any apair in (0, 1, 2) can be exchangeble.\n\nThis means, we could build connected components where\neach component is a list of indices that can be exchangeable with any of them.\n\nIn Union find terms, we simply iterate through each allowedSwaps,\nand do a union on the indices in the pair.\n\nAt the end of the union of all the pairs,\nwe will get connected components of indices that\ncan be exchangeable with each other.\n\n\n\n# Code\n```\nclass UnionFind:\n \n def __init__(self, n): \n self.root = list(range(n))\n \n def union(self, x, y): \n self.root[self.find(x)] = self.find(y)\n \n def find(self, x):\n if x != self.root[x]: \n self.root[x] = self.find(self.root[x])\n return self.root[x]\n \n \nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind(len(source))\n for x, y in allowedSwaps: \n uf.union(x, y)\n m = defaultdict(set) # key is the component, value is the set of indices in same component\n for i in range(len(source)):\n m[uf.find(i)].add(i)\n ans = 0\n for indices in m.values():\n A = [source[i] for i in indices]\n B = [target[i] for i in indices]\n ans += sum((Counter(A) - Counter(B)).values())\n return ans\n \n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python3 Connected Subgraph - Runtime 100% | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Approach\nSince we can swaps as many times as possible, swaps can be seen a connected subgraphs. For example if we can swap [0,1] and [1,2], we can also swap [0, 2]. This means {0, 1, 2} is a connected subgraph where any of the values can be swapped in any of the indexes in that subgraph.\n\nSo the idea is that we first construct connected subgraphs. Then we can compare the values of those subgraphs from the source and target to get mininmum hamming distances. This turns the problem basically into set comparisons on the subgraphs.\n\n# Code\n```\n# Leetcode 1722. Minimize Hamming Distance After Swap Operations\n# https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/\n\nfrom typing import List\nfrom collections import defaultdict, deque\nfrom itertools import combinations\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: \n\n # Construct graph\n graph = defaultdict(set)\n for a, b in allowedSwaps:\n graph[a].add(b)\n graph[b].add(a)\n \n # Graph search - connected sections of graph based on swaps\n # For each connected section of graph, find min ham possible\n # Add all hams together\n\n subgraphs = []\n seen = set()\n for a in graph:\n if a in seen:\n continue\n # else bfs from a\n subgraph = set([a])\n q = deque([a])\n while q:\n node = q.popleft()\n seen.add(node)\n subgraph.add(node)\n for next in graph[node]:\n if next not in seen:\n q.append(next)\n \n subgraphs.append(subgraph)\n \n # For each subgraph, find min hamming distance\n total_ham = 0\n for g in subgraphs:\n diffs = defaultdict(int)\n for i in g:\n diffs[source[i]] += 1\n diffs[target[i]] -= 1\n \n # hamm distance\n ham = 0\n for d in diffs:\n ham += abs(diffs[d])\n total_ham += ham // 2\n \n for i in range(len(source)):\n if i not in seen and source[i] != target[i]:\n total_ham += 1\n \n return total_ham\n\n``` | 0 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Python3 Connected Subgraph - Runtime 100% | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Approach\nSince we can swaps as many times as possible, swaps can be seen a connected subgraphs. For example if we can swap [0,1] and [1,2], we can also swap [0, 2]. This means {0, 1, 2} is a connected subgraph where any of the values can be swapped in any of the indexes in that subgraph.\n\nSo the idea is that we first construct connected subgraphs. Then we can compare the values of those subgraphs from the source and target to get mininmum hamming distances. This turns the problem basically into set comparisons on the subgraphs.\n\n# Code\n```\n# Leetcode 1722. Minimize Hamming Distance After Swap Operations\n# https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/\n\nfrom typing import List\nfrom collections import defaultdict, deque\nfrom itertools import combinations\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: \n\n # Construct graph\n graph = defaultdict(set)\n for a, b in allowedSwaps:\n graph[a].add(b)\n graph[b].add(a)\n \n # Graph search - connected sections of graph based on swaps\n # For each connected section of graph, find min ham possible\n # Add all hams together\n\n subgraphs = []\n seen = set()\n for a in graph:\n if a in seen:\n continue\n # else bfs from a\n subgraph = set([a])\n q = deque([a])\n while q:\n node = q.popleft()\n seen.add(node)\n subgraph.add(node)\n for next in graph[node]:\n if next not in seen:\n q.append(next)\n \n subgraphs.append(subgraph)\n \n # For each subgraph, find min hamming distance\n total_ham = 0\n for g in subgraphs:\n diffs = defaultdict(int)\n for i in g:\n diffs[source[i]] += 1\n diffs[target[i]] -= 1\n \n # hamm distance\n ham = 0\n for d in diffs:\n ham += abs(diffs[d])\n total_ham += ham // 2\n \n for i in range(len(source)):\n if i not in seen and source[i] != target[i]:\n total_ham += 1\n \n return total_ham\n\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python3 || DSU Algorithm | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor all the swaps operations run union find search. Which will components on the the indexes which can be swapped within themselves.\n\nNow, for each index find its parent (find operation of parent) and create a hashmap for all the values which we can get from a parent.\n\nThen all we need to do is traverse on target array, find its parent based on index. Now, This target element if present in hash of elements for that parent then its good (reduce the value by 1 from map) otherwise this value will be different.\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n\n n = len(source)\n parent = [i for i in range(n)]\n rank = [0] * n\n\n for i, j in allowedSwaps:\n self.union(i, j, parent, rank)\n \n map = {}\n\n for i in range(n):\n value = source[i]\n root = self.find(i, parent)\n if root not in map:\n map[root] = defaultdict(int)\n map[root][value] += 1\n\n ans = 0\n for i in range(n):\n value = target[i]\n root = self.find(i, parent)\n value_hash = map[root]\n if(value in value_hash and value_hash[value] > 0):\n value_hash[value] -= 1\n else:\n ans += 1\n return ans\n\n\n def find(self, x, parent):\n if(x != parent[x]):\n parent[x] = self.find(parent[x], parent)\n return parent[x]\n \n def union(self, x, y, parent, rank):\n\n root_x = self.find(x, parent)\n root_y = self.find(y, parent)\n\n if(root_x == root_y):\n return\n \n rank_x = rank[root_x]\n rank_y = rank[root_y]\n\n if(rank_x > rank_y):\n parent[root_y] = root_x\n elif(rank_x < rank_y):\n parent[root_x] = root_y\n else:\n parent[root_y] = root_x\n rank[root_x] += 1\n``` | 0 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Python3 || DSU Algorithm | minimize-hamming-distance-after-swap-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor all the swaps operations run union find search. Which will components on the the indexes which can be swapped within themselves.\n\nNow, for each index find its parent (find operation of parent) and create a hashmap for all the values which we can get from a parent.\n\nThen all we need to do is traverse on target array, find its parent based on index. Now, This target element if present in hash of elements for that parent then its good (reduce the value by 1 from map) otherwise this value will be different.\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n\n n = len(source)\n parent = [i for i in range(n)]\n rank = [0] * n\n\n for i, j in allowedSwaps:\n self.union(i, j, parent, rank)\n \n map = {}\n\n for i in range(n):\n value = source[i]\n root = self.find(i, parent)\n if root not in map:\n map[root] = defaultdict(int)\n map[root][value] += 1\n\n ans = 0\n for i in range(n):\n value = target[i]\n root = self.find(i, parent)\n value_hash = map[root]\n if(value in value_hash and value_hash[value] > 0):\n value_hash[value] -= 1\n else:\n ans += 1\n return ans\n\n\n def find(self, x, parent):\n if(x != parent[x]):\n parent[x] = self.find(parent[x], parent)\n return parent[x]\n \n def union(self, x, y, parent, rank):\n\n root_x = self.find(x, parent)\n root_y = self.find(y, parent)\n\n if(root_x == root_y):\n return\n \n rank_x = rank[root_x]\n rank_y = rank[root_y]\n\n if(rank_x > rank_y):\n parent[root_y] = root_x\n elif(rank_x < rank_y):\n parent[root_x] = root_y\n else:\n parent[root_y] = root_x\n rank[root_x] += 1\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python Union Find Solution 90 % Faster | minimize-hamming-distance-after-swap-operations | 0 | 1 | My code initializes the parent dictionary, which maps each index to itself, and the rank list, which stores the ranks of the parent elements in the union-find algorithm.\n\nThe find function implements path compression in the union-find algorithm. It iterativaley finds the root parent of an element and updates the parent of each visited element to point directly to the root.\n\nThe union function performs the union operation of two groups based on their ranks. It compares the ranks of the parent elements and updates the parent accordingly.\n\nThe code iterates through the allowed swaps and performs the union operation on the respective indices, effectively grouping the indices that are allowed to be swapped together.\n\nThe swappable_indices dictionary is created to store the indices that can be swapped for each group. It is populated by iterating over the source array indices and grouping them based on their parent element (using the find function).\n\nThe code initializes the ans variable to keep track of the minimum Hamming distance.\n\nFor each group of indices in swappable_indices, the code collects the corresponding elements from the source and target arrays.\n\nTwo defaultdicts, source_count and target_count, are used to count the occurrences of each element in the respective groups.\n\nThe code compares the element counts between the source and target groups. If the count in the source group is higher than the count in the target group, it means there are excess elements that need to be swapped. The difference in counts is added to the ans variable.\n\nFinally, the code returns the minimum Hamming distance (ans).\n\nIn summary, the code uses the union-find algorithm to group swappable indices together. It collects the swappable indices efficiently using a dictionary and checks the element equality with a time complexity of O(n). By counting the occurrences of elements in the source and target groups, it determines the excess elements that need to be swapped and calculates the minimum Hamming distance accordingly.\n```\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n\n parent=defaultdict(int)\n for i in range(len(source)):\n parent[i]=i\n rank=[0 for i in range(len(source))]\n def find(x):\n root=x\n while root!=parent[root]:\n root=parent[root]\n \n while x!=root:\n temp=parent[x]\n parent[x]=root\n x=temp\n return root\n \n def union(x,y):\n parentX=find(x)\n parentY=find(y)\n if parentX==parentY:return\n \n if rank[parentX]==rank[parentY]:\n rank[parentX]+=1\n if rank[parentX]>rank[parentY]:\n parent[parentY]=parentX\n else:\n parent[parentX]=parentY\n for index1, index2 in allowedSwaps:\n union(index1, index2)\n\n swappable_indices = defaultdict(list)\n for i in range(len(source)):\n swappable_indices[find(i)].append(i)\n\n ans = 0\n for indices in swappable_indices.values():\n source_group = [source[i] for i in indices]\n target_group = [target[i] for i in indices]\n source_count = defaultdict(int)\n target_count = defaultdict(int)\n\n for num in source_group:\n source_count[num] += 1\n for num in target_group:\n target_count[num] += 1\n\n for num, count in source_count.items():\n diff = count - target_count[num]\n if diff > 0:\n ans += diff\n\n return ans\n``` | 0 | You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` **(0-indexed)** of array `source`. Note that you can swap elements at a specific pair of indices **multiple** times and in **any** order.
The **Hamming distance** of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` **(0-indexed)**.
Return _the **minimum Hamming distance** of_ `source` _and_ `target` _after performing **any** amount of swap operations on array_ `source`_._
**Example 1:**
**Input:** source = \[1,2,3,4\], target = \[2,1,4,5\], allowedSwaps = \[\[0,1\],\[2,3\]\]
**Output:** 1
**Explanation:** source can be transformed the following way:
- Swap indices 0 and 1: source = \[2,1,3,4\]
- Swap indices 2 and 3: source = \[2,1,4,3\]
The Hamming distance of source and target is 1 as they differ in 1 position: index 3.
**Example 2:**
**Input:** source = \[1,2,3,4\], target = \[1,3,2,4\], allowedSwaps = \[\]
**Output:** 2
**Explanation:** There are no allowed swaps.
The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.
**Example 3:**
**Input:** source = \[5,1,2,4,3\], target = \[1,5,4,2,3\], allowedSwaps = \[\[0,4\],\[4,2\],\[1,3\],\[1,4\]\]
**Output:** 0
**Constraints:**
* `n == source.length == target.length`
* `1 <= n <= 105`
* `1 <= source[i], target[i] <= 105`
* `0 <= allowedSwaps.length <= 105`
* `allowedSwaps[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Create a tree structure of the family. Without deaths, the order of inheritance is simply a pre-order traversal of the tree. Mark the dead family members tree nodes and don't include them in the final order. |
Python Union Find Solution 90 % Faster | minimize-hamming-distance-after-swap-operations | 0 | 1 | My code initializes the parent dictionary, which maps each index to itself, and the rank list, which stores the ranks of the parent elements in the union-find algorithm.\n\nThe find function implements path compression in the union-find algorithm. It iterativaley finds the root parent of an element and updates the parent of each visited element to point directly to the root.\n\nThe union function performs the union operation of two groups based on their ranks. It compares the ranks of the parent elements and updates the parent accordingly.\n\nThe code iterates through the allowed swaps and performs the union operation on the respective indices, effectively grouping the indices that are allowed to be swapped together.\n\nThe swappable_indices dictionary is created to store the indices that can be swapped for each group. It is populated by iterating over the source array indices and grouping them based on their parent element (using the find function).\n\nThe code initializes the ans variable to keep track of the minimum Hamming distance.\n\nFor each group of indices in swappable_indices, the code collects the corresponding elements from the source and target arrays.\n\nTwo defaultdicts, source_count and target_count, are used to count the occurrences of each element in the respective groups.\n\nThe code compares the element counts between the source and target groups. If the count in the source group is higher than the count in the target group, it means there are excess elements that need to be swapped. The difference in counts is added to the ans variable.\n\nFinally, the code returns the minimum Hamming distance (ans).\n\nIn summary, the code uses the union-find algorithm to group swappable indices together. It collects the swappable indices efficiently using a dictionary and checks the element equality with a time complexity of O(n). By counting the occurrences of elements in the source and target groups, it determines the excess elements that need to be swapped and calculates the minimum Hamming distance accordingly.\n```\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n\n parent=defaultdict(int)\n for i in range(len(source)):\n parent[i]=i\n rank=[0 for i in range(len(source))]\n def find(x):\n root=x\n while root!=parent[root]:\n root=parent[root]\n \n while x!=root:\n temp=parent[x]\n parent[x]=root\n x=temp\n return root\n \n def union(x,y):\n parentX=find(x)\n parentY=find(y)\n if parentX==parentY:return\n \n if rank[parentX]==rank[parentY]:\n rank[parentX]+=1\n if rank[parentX]>rank[parentY]:\n parent[parentY]=parentX\n else:\n parent[parentX]=parentY\n for index1, index2 in allowedSwaps:\n union(index1, index2)\n\n swappable_indices = defaultdict(list)\n for i in range(len(source)):\n swappable_indices[find(i)].append(i)\n\n ans = 0\n for indices in swappable_indices.values():\n source_group = [source[i] for i in indices]\n target_group = [target[i] for i in indices]\n source_count = defaultdict(int)\n target_count = defaultdict(int)\n\n for num in source_group:\n source_count[num] += 1\n for num in target_group:\n target_count[num] += 1\n\n for num, count in source_count.items():\n diff = count - target_count[num]\n if diff > 0:\n ans += diff\n\n return ans\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
[Python3] backtracking | find-minimum-time-to-finish-all-jobs | 0 | 1 | **Algo**\nHere, we simply try out all possibilities but eliminate those that are apparently a waste of time. \n\n**Implementation**\n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n jobs.sort(reverse=True)\n \n def fn(i):\n """Assign jobs to worker and find minimum time."""\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] > time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans \n```\n\n**Updated** \nI was previously using `time[kk-1] > time[kk]` as the criterion to prune the backtracking tree which turns out to be incorrect. The condition is updated to `time[kk-1] != time[kk]`. In the meantime, the initial sorting was removed as it is useless. \n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \n def fn(i):\n """Assign jobs to worker and find minimum time."""\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] != time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans \n``` | 6 | You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.
There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**.
_Return the **minimum** possible **maximum working time** of any assignment._
**Example 1:**
**Input:** jobs = \[3,2,3\], k = 3
**Output:** 3
**Explanation:** By assigning each person one job, the maximum time is 3.
**Example 2:**
**Input:** jobs = \[1,2,4,7,8\], k = 2
**Output:** 11
**Explanation:** Assign the jobs the following way:
Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
Worker 2: 4, 7 (working time = 4 + 7 = 11)
The maximum working time is 11.
**Constraints:**
* `1 <= k <= jobs.length <= 12`
* `1 <= jobs[i] <= 107` | Think brute force When is a subset of requests okay? |
[Python3] backtracking | find-minimum-time-to-finish-all-jobs | 0 | 1 | **Algo**\nHere, we simply try out all possibilities but eliminate those that are apparently a waste of time. \n\n**Implementation**\n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n jobs.sort(reverse=True)\n \n def fn(i):\n """Assign jobs to worker and find minimum time."""\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] > time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans \n```\n\n**Updated** \nI was previously using `time[kk-1] > time[kk]` as the criterion to prune the backtracking tree which turns out to be incorrect. The condition is updated to `time[kk-1] != time[kk]`. In the meantime, the initial sorting was removed as it is useless. \n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \n def fn(i):\n """Assign jobs to worker and find minimum time."""\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] != time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans \n``` | 6 | You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream.
The **MKAverage** can be calculated using these steps:
1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.
2. Remove the smallest `k` elements and the largest `k` elements from the container.
3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**.
Implement the `MKAverage` class:
* `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`.
* `void addElement(int num)` Inserts a new element `num` into the stream.
* `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**.
**Example 1:**
**Input**
\[ "MKAverage ", "addElement ", "addElement ", "calculateMKAverage ", "addElement ", "calculateMKAverage ", "addElement ", "addElement ", "addElement ", "calculateMKAverage "\]
\[\[3, 1\], \[3\], \[1\], \[\], \[10\], \[\], \[5\], \[5\], \[5\], \[\]\]
**Output**
\[null, null, null, -1, null, 3, null, null, null, 5\]
**Explanation**
`MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5`
**Constraints:**
* `3 <= m <= 105`
* `1 <= k*2 < m`
* `1 <= num <= 105`
* At most `105` calls will be made to `addElement` and `calculateMKAverage`. | We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks |
Python implementation of the theoretically optimal O(3^N) solution | find-minimum-time-to-finish-all-jobs | 0 | 1 | Here\'s an implementation in python of the theoretically optimal solution in O(3^N). All the other posted python solutions at this time are not theoretically optimal and just implement backtracking with different pruning techniques to fit the time limit.\n\nI struggled a bit to get the solution to fit into the time limit as well (despite earlier versions being theorically optimal). The most helpful optimizations were:\n1. Precompute the 2^N costs of assigning a set of jobs to any worker (aka `worker_cost` below).\n2. Use `worker_state = (worker_state - 1) & state` trick to iterate through the eligible substates for a given state. The intuition behind this trick is that `worker_state - 1` will flip the rightmost bit of 1 to 0 and all the following 0 bits to 1 (and keep preceding bits unchanged). By applying the `&` operation against the original `state` we keep just the following bits which are valid as part of `state` (`& state` ensures we select a subset of bits of `state` for the substate `worker_state`).\n\n```\nclass Solution: \n def minimumTimeRequired(self, jobs: List[int], num_workers: int) -> int:\n n = len(jobs)\n worker_cost = [0] * (1 << n)\n for state in range(1 << n):\n for i in range(n):\n if state & (1 << i):\n worker_cost[state] += jobs[i]\n \n @functools.cache\n def compute_time(state: int, curr_workers: int) -> int:\n if curr_workers == 1:\n return worker_cost[state]\n \n best = float("inf")\n worker_state = state\n while worker_state:\n if worker_cost[worker_state] < best:\n best = min(best, max(compute_time(state ^ worker_state, curr_workers - 1), worker_cost[worker_state]))\n worker_state = (worker_state - 1) & state\n \n return best\n \n return compute_time((1 << n) - 1, num_workers)\n``` | 2 | You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.
There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**.
_Return the **minimum** possible **maximum working time** of any assignment._
**Example 1:**
**Input:** jobs = \[3,2,3\], k = 3
**Output:** 3
**Explanation:** By assigning each person one job, the maximum time is 3.
**Example 2:**
**Input:** jobs = \[1,2,4,7,8\], k = 2
**Output:** 11
**Explanation:** Assign the jobs the following way:
Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
Worker 2: 4, 7 (working time = 4 + 7 = 11)
The maximum working time is 11.
**Constraints:**
* `1 <= k <= jobs.length <= 12`
* `1 <= jobs[i] <= 107` | Think brute force When is a subset of requests okay? |
Python implementation of the theoretically optimal O(3^N) solution | find-minimum-time-to-finish-all-jobs | 0 | 1 | Here\'s an implementation in python of the theoretically optimal solution in O(3^N). All the other posted python solutions at this time are not theoretically optimal and just implement backtracking with different pruning techniques to fit the time limit.\n\nI struggled a bit to get the solution to fit into the time limit as well (despite earlier versions being theorically optimal). The most helpful optimizations were:\n1. Precompute the 2^N costs of assigning a set of jobs to any worker (aka `worker_cost` below).\n2. Use `worker_state = (worker_state - 1) & state` trick to iterate through the eligible substates for a given state. The intuition behind this trick is that `worker_state - 1` will flip the rightmost bit of 1 to 0 and all the following 0 bits to 1 (and keep preceding bits unchanged). By applying the `&` operation against the original `state` we keep just the following bits which are valid as part of `state` (`& state` ensures we select a subset of bits of `state` for the substate `worker_state`).\n\n```\nclass Solution: \n def minimumTimeRequired(self, jobs: List[int], num_workers: int) -> int:\n n = len(jobs)\n worker_cost = [0] * (1 << n)\n for state in range(1 << n):\n for i in range(n):\n if state & (1 << i):\n worker_cost[state] += jobs[i]\n \n @functools.cache\n def compute_time(state: int, curr_workers: int) -> int:\n if curr_workers == 1:\n return worker_cost[state]\n \n best = float("inf")\n worker_state = state\n while worker_state:\n if worker_cost[worker_state] < best:\n best = min(best, max(compute_time(state ^ worker_state, curr_workers - 1), worker_cost[worker_state]))\n worker_state = (worker_state - 1) & state\n \n return best\n \n return compute_time((1 << n) - 1, num_workers)\n``` | 2 | You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream.
The **MKAverage** can be calculated using these steps:
1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.
2. Remove the smallest `k` elements and the largest `k` elements from the container.
3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**.
Implement the `MKAverage` class:
* `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`.
* `void addElement(int num)` Inserts a new element `num` into the stream.
* `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**.
**Example 1:**
**Input**
\[ "MKAverage ", "addElement ", "addElement ", "calculateMKAverage ", "addElement ", "calculateMKAverage ", "addElement ", "addElement ", "addElement ", "calculateMKAverage "\]
\[\[3, 1\], \[3\], \[1\], \[\], \[10\], \[\], \[5\], \[5\], \[5\], \[\]\]
**Output**
\[null, null, null, -1, null, 3, null, null, null, 5\]
**Explanation**
`MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5`
**Constraints:**
* `3 <= m <= 105`
* `1 <= k*2 < m`
* `1 <= num <= 105`
* At most `105` calls will be made to `addElement` and `calculateMKAverage`. | We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks |
Branch & Bound + Greedy beats %98 | find-minimum-time-to-finish-all-jobs | 0 | 1 | # Intuition\nThis is a NP-complete problem. We can use Branch & Bound algorithm to solve it. However, a naive implementation will have TLE error for some test cases.\n\nInitially, I use the sum of all jobs\' time as upper bound. Due to the TLE, I sorted the jobs in decending order. It helped a little, but still cause TLE. Thanks to @lee215, avoiding assigning the first job to different free workers (if a[j] == 0: break) helps a lot. Thanks to @votrubac, this optimization can be further generalized as skipping iterations for elements with the same value in array a.\n\nThere is another optimization we can do with the upper bound. Initially, I thought this problem could be solved by using greedy algorithm. However, greedy algo doesn\'t always generate the optimal solution, but its result can be used as upper bound. With this bound the solution was accepted and beats 98% python submissions.\n\nIf you like my approach please upvote, thanks!\n\n# Code\n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n def branchAndBound(i: int):\n nonlocal r\n if i == n:\n r = min(r, max(a))\n return\n visited = set()\n for j in range(k):\n if a[j] in visited:\n continue\n visited.add(a[j])\n if a[j] + jobs[i] >= r:\n continue\n a[j] += jobs[i]\n branchAndBound(i+1)\n a[j] -= jobs[i]\n\n n = len(jobs)\n if n <= k:\n return max(jobs)\n\n # use greed algorithm to get upper bound\n jobs.sort(reverse=True)\n a = list(jobs[:k])\n for job in jobs[k:]:\n m0 = min(a)\n i = a.index(m0)\n a[i] += job\n r = max(a)\n\n a = [0] * k\n branchAndBound(0)\n return r\n``` | 0 | You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.
There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**.
_Return the **minimum** possible **maximum working time** of any assignment._
**Example 1:**
**Input:** jobs = \[3,2,3\], k = 3
**Output:** 3
**Explanation:** By assigning each person one job, the maximum time is 3.
**Example 2:**
**Input:** jobs = \[1,2,4,7,8\], k = 2
**Output:** 11
**Explanation:** Assign the jobs the following way:
Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
Worker 2: 4, 7 (working time = 4 + 7 = 11)
The maximum working time is 11.
**Constraints:**
* `1 <= k <= jobs.length <= 12`
* `1 <= jobs[i] <= 107` | Think brute force When is a subset of requests okay? |
Branch & Bound + Greedy beats %98 | find-minimum-time-to-finish-all-jobs | 0 | 1 | # Intuition\nThis is a NP-complete problem. We can use Branch & Bound algorithm to solve it. However, a naive implementation will have TLE error for some test cases.\n\nInitially, I use the sum of all jobs\' time as upper bound. Due to the TLE, I sorted the jobs in decending order. It helped a little, but still cause TLE. Thanks to @lee215, avoiding assigning the first job to different free workers (if a[j] == 0: break) helps a lot. Thanks to @votrubac, this optimization can be further generalized as skipping iterations for elements with the same value in array a.\n\nThere is another optimization we can do with the upper bound. Initially, I thought this problem could be solved by using greedy algorithm. However, greedy algo doesn\'t always generate the optimal solution, but its result can be used as upper bound. With this bound the solution was accepted and beats 98% python submissions.\n\nIf you like my approach please upvote, thanks!\n\n# Code\n```\nclass Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n def branchAndBound(i: int):\n nonlocal r\n if i == n:\n r = min(r, max(a))\n return\n visited = set()\n for j in range(k):\n if a[j] in visited:\n continue\n visited.add(a[j])\n if a[j] + jobs[i] >= r:\n continue\n a[j] += jobs[i]\n branchAndBound(i+1)\n a[j] -= jobs[i]\n\n n = len(jobs)\n if n <= k:\n return max(jobs)\n\n # use greed algorithm to get upper bound\n jobs.sort(reverse=True)\n a = list(jobs[:k])\n for job in jobs[k:]:\n m0 = min(a)\n i = a.index(m0)\n a[i] += job\n r = max(a)\n\n a = [0] * k\n branchAndBound(0)\n return r\n``` | 0 | You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream.
The **MKAverage** can be calculated using these steps:
1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.
2. Remove the smallest `k` elements and the largest `k` elements from the container.
3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**.
Implement the `MKAverage` class:
* `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`.
* `void addElement(int num)` Inserts a new element `num` into the stream.
* `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**.
**Example 1:**
**Input**
\[ "MKAverage ", "addElement ", "addElement ", "calculateMKAverage ", "addElement ", "calculateMKAverage ", "addElement ", "addElement ", "addElement ", "calculateMKAverage "\]
\[\[3, 1\], \[3\], \[1\], \[\], \[10\], \[\], \[5\], \[5\], \[5\], \[\]\]
**Output**
\[null, null, null, -1, null, 3, null, null, null, 5\]
**Explanation**
`MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5`
**Constraints:**
* `3 <= m <= 105`
* `1 <= k*2 < m`
* `1 <= num <= 105`
* At most `105` calls will be made to `addElement` and `calculateMKAverage`. | We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks |
4 optimizations that can be made. Beats 99.53% in runtime | find-minimum-time-to-finish-all-jobs | 0 | 1 | \n\n# Approach\nThis can be done by as a brute-force search with early termination. We find that the naive solution will TLE and certain optimisations are necessary.\n\nThis solution acts as a summary of the optimisations I found and collated here. In particular, I will talk about 4 of these optimisations.\n\n1. The first job has to always be assigned to someone, so why not just immediately assign it to the first worker. This reduces the search space from $2^n$ to $2^{n-1}$ as we only have to assign the remaining $n-1$ tasks.\n2. Determine an upperbound of the time taken. With an upperbound in time, we can terminate the search earlier. So how can we find such an upperbound? A greedy approach comes to mind. We can repeatedly assign jobs with decreasing job times to the worker with the least amount of time.\n3. As we perform search, we can prune our search by ensuring at no point in the search does our maxtime exceed our current best time. \n4. As explained very well by **lichuan199010** in his solution found [here](https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/solutions/1009817/one-branch-cutting-trick-to-solve-three-leetcode-questions/), we can also remember that we have tried to add a job to an earlier worker with the same time, and hence its futile to redo the search, allowing us to skip the worker.\n\nDo try to implement these 4 optimisations and you will find a drastic decrease in your runtime. \n\nYou can find the python code below.\n\n# Code\n```\nclass Solution:\n def search(self, i, jobs, curr):\n if i >= len(jobs):\n self.ans = min(self.ans, max(curr))\n return\n seen = set()\n for wi in range(len(curr)):\n if curr[wi] in seen:\n continue\n seen.add(curr[wi])\n curr[wi] += jobs[i]\n if max(curr) < self.ans:\n self.search(i+1, jobs, curr)\n curr[wi] -= jobs[i]\n \n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n # 4 Optimisations to be made\n # -> Upperbound with greedy fill, early exit\n # -> If we added current job to a worker of same size before, skip\n # -> If exceed ans, dont go any further\n # -> Someone has to take the first job, assign it to first person\n jobs.sort(reverse=True)\n greedy = [0] * k\n for j in jobs:\n m = greedy[0]\n heapq.heappushpop(greedy, m+j)\n self.ans = max(greedy)\n curr = [0] * k\n curr[0] = jobs[0]\n self.search(1, jobs, curr)\n return self.ans\n```\n | 0 | You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job.
There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the **maximum working time** of any worker is **minimized**.
_Return the **minimum** possible **maximum working time** of any assignment._
**Example 1:**
**Input:** jobs = \[3,2,3\], k = 3
**Output:** 3
**Explanation:** By assigning each person one job, the maximum time is 3.
**Example 2:**
**Input:** jobs = \[1,2,4,7,8\], k = 2
**Output:** 11
**Explanation:** Assign the jobs the following way:
Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
Worker 2: 4, 7 (working time = 4 + 7 = 11)
The maximum working time is 11.
**Constraints:**
* `1 <= k <= jobs.length <= 12`
* `1 <= jobs[i] <= 107` | Think brute force When is a subset of requests okay? |
4 optimizations that can be made. Beats 99.53% in runtime | find-minimum-time-to-finish-all-jobs | 0 | 1 | \n\n# Approach\nThis can be done by as a brute-force search with early termination. We find that the naive solution will TLE and certain optimisations are necessary.\n\nThis solution acts as a summary of the optimisations I found and collated here. In particular, I will talk about 4 of these optimisations.\n\n1. The first job has to always be assigned to someone, so why not just immediately assign it to the first worker. This reduces the search space from $2^n$ to $2^{n-1}$ as we only have to assign the remaining $n-1$ tasks.\n2. Determine an upperbound of the time taken. With an upperbound in time, we can terminate the search earlier. So how can we find such an upperbound? A greedy approach comes to mind. We can repeatedly assign jobs with decreasing job times to the worker with the least amount of time.\n3. As we perform search, we can prune our search by ensuring at no point in the search does our maxtime exceed our current best time. \n4. As explained very well by **lichuan199010** in his solution found [here](https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/solutions/1009817/one-branch-cutting-trick-to-solve-three-leetcode-questions/), we can also remember that we have tried to add a job to an earlier worker with the same time, and hence its futile to redo the search, allowing us to skip the worker.\n\nDo try to implement these 4 optimisations and you will find a drastic decrease in your runtime. \n\nYou can find the python code below.\n\n# Code\n```\nclass Solution:\n def search(self, i, jobs, curr):\n if i >= len(jobs):\n self.ans = min(self.ans, max(curr))\n return\n seen = set()\n for wi in range(len(curr)):\n if curr[wi] in seen:\n continue\n seen.add(curr[wi])\n curr[wi] += jobs[i]\n if max(curr) < self.ans:\n self.search(i+1, jobs, curr)\n curr[wi] -= jobs[i]\n \n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n # 4 Optimisations to be made\n # -> Upperbound with greedy fill, early exit\n # -> If we added current job to a worker of same size before, skip\n # -> If exceed ans, dont go any further\n # -> Someone has to take the first job, assign it to first person\n jobs.sort(reverse=True)\n greedy = [0] * k\n for j in jobs:\n m = greedy[0]\n heapq.heappushpop(greedy, m+j)\n self.ans = max(greedy)\n curr = [0] * k\n curr[0] = jobs[0]\n self.search(1, jobs, curr)\n return self.ans\n```\n | 0 | You are given two integers, `m` and `k`, and a stream of integers. You are tasked to implement a data structure that calculates the **MKAverage** for the stream.
The **MKAverage** can be calculated using these steps:
1. If the number of the elements in the stream is less than `m` you should consider the **MKAverage** to be `-1`. Otherwise, copy the last `m` elements of the stream to a separate container.
2. Remove the smallest `k` elements and the largest `k` elements from the container.
3. Calculate the average value for the rest of the elements **rounded down to the nearest integer**.
Implement the `MKAverage` class:
* `MKAverage(int m, int k)` Initializes the **MKAverage** object with an empty stream and the two integers `m` and `k`.
* `void addElement(int num)` Inserts a new element `num` into the stream.
* `int calculateMKAverage()` Calculates and returns the **MKAverage** for the current stream **rounded down to the nearest integer**.
**Example 1:**
**Input**
\[ "MKAverage ", "addElement ", "addElement ", "calculateMKAverage ", "addElement ", "calculateMKAverage ", "addElement ", "addElement ", "addElement ", "calculateMKAverage "\]
\[\[3, 1\], \[3\], \[1\], \[\], \[10\], \[\], \[5\], \[5\], \[5\], \[\]\]
**Output**
\[null, null, null, -1, null, 3, null, null, null, 5\]
**Explanation**
`MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be [3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be [5]. // The average of [5] equals 5/1 = 5, return 5`
**Constraints:**
* `3 <= m <= 105`
* `1 <= k*2 < m`
* `1 <= num <= 105`
* At most `105` calls will be made to `addElement` and `calculateMKAverage`. | We can select a subset of tasks and assign it to a worker then solve the subproblem on the remaining tasks |
Simple solution with HashMap in Python3 | number-of-rectangles-that-can-form-the-largest-square | 0 | 1 | # Intuition\nHere we have:\n- list of `rectangles` with height and width\n- our goal is to find **maximized count** of rects **we can cut**, to have a **perfect square** \n\nAt each step we should somehow **cut** all of the rects to find a `maxLen`.\n\nFor this problem we\'re going to use **HashMap** to track **frequency** of **max possible length of size of a square**.\n\nDefinitely, we **can\'t** choose a maximum size of a **rect**, since we only **cut** (and not **extend**) sides.\n\nThus, at each step **we should consider the least length** of a particular rectangle.\n\n# Approach\n1. define `rects` to be a **HashMap**\n2. iterate over `rectangles` and find minimum sides for each rect, then increase a frequency\n3. define `ans` and `maxFreq` to iterate over all enumerated `rects` and update `ans`, if `maxFreq` at a particular step is **more**, than previous one.\n4. return `ans`\n\n# Complexity\n- Time complexity: **O(N + K)**, for twice-iterating over `rectangles` and `rects`\n\n- Space complexity: **O(K)**, since we store `rects`\n\n# Code\n```\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n rects = defaultdict(int)\n\n for a, b in rectangles:\n rects[min(a, b)] += 1\n\n ans = 0\n maxFreq = 0\n\n for k, v in rects.items():\n if k > maxFreq:\n maxFreq = k\n ans = v\n\n return ans\n``` | 1 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi` | Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). |
With basic of python code | number-of-rectangles-that-can-form-the-largest-square | 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\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n result=[]\n for i in rectangles:\n result.append(min(i))\n c=Counter(result)\n larg=max(c.keys())\n return c[larg]\n \n``` | 1 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi` | Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). |
Python - Runtime O(N) and O(1) space [ACCEPTED] | number-of-rectangles-that-can-form-the-largest-square | 0 | 1 | This can be done just by tracking the max length and its count.\n\n```\ndef countGoodRectangles(rectangles):\n\tmax_len = float(\'-inf\')\n\tcount = 0\n\tfor item in rectangles:\n\t\tmin_len = min(item)\n\t\tif min_len == max_len:\n\t\t\tcount += 1\n\t\telif min_len > max_len:\n\t\t\tmax_len = min_len\n\t\t\tcount = 1\n\n\treturn count | 18 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi` | Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). |
[python|| O(N)] | number-of-rectangles-that-can-form-the-largest-square | 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- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n max_len = float(\'-inf\')\n count = 0\n for item in rectangles:\n min_len = min(item)\n if min_len == max_len:\n count += 1\n elif min_len > max_len:\n max_len = min_len\n count = 1\n\n return count\n``` | 2 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi` | Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). |
β
β SIMPLE PYTHON3 SOLUTION β
βeasy to understand | number-of-rectangles-that-can-form-the-largest-square | 0 | 1 | ***UPVOTE*** if it is helpful\n``` \nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n c = []\n count = 0\n for i in rectangles:\n c.append(min(i))\n ans = max(c)\n for j in range(len(c)):\n if c[j] == ans:\n count = count+1\n return count\n``` | 0 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi` | Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). |
Python easy solution | number-of-rectangles-that-can-form-the-largest-square | 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. -->\nGei min in each rectangles pair as max side, then sort and get the count of max rectangle\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 countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n largest_squars = [min(x) for x in rectangles]\n largest_squars.sort()\n return largest_squars.count(largest_squars[-1])\n \n``` | 0 | You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`.
You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`.
Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles.
Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`.
**Example 1:**
**Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\]
**Output:** 3
**Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\].
The largest possible square is of length 5, and you can get it out of 3 rectangles.
**Example 2:**
**Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\]
**Output:** 3
**Constraints:**
* `1 <= rectangles.length <= 1000`
* `rectangles[i].length == 2`
* `1 <= li, wi <= 109`
* `li != wi` | Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint). |
[Python3] freq table | tuple-with-same-product | 0 | 1 | **Algo**\nUse a nested loop to scan possible `x*y` and keep a frequency table. When a product has been seen before, update `ans` with counting before the current occurrence. Return `8*ans`. \n\n**Implementation**\n```\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n ans = 0\n freq = {}\n for i in range(len(nums)):\n for j in range(i+1, len(nums)): \n key = nums[i] * nums[j]\n ans += freq.get(key, 0)\n freq[key] = 1 + freq.get(key, 0)\n return 8*ans\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N^2)` | 34 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
[PYTHON3] [0 LINER] [FASTER THAN 100.00%] [NO ITERTOOLS] [ENTIRE FILE IS 2 LINES] Fast 0-liner | tuple-with-same-product | 0 | 1 | ```\nclass Solution:\n tupleSameProduct = lambda _, nums: sum(count*(count-1) for _, count in Counter([nums[i] * nums[j] for j in range(1, len(nums)) for i in range(len(nums) - 1) if j > i]).items()) * 4\n``` | 1 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
Simple Python3 | 6 Lines | Detailed Explanation | tuple-with-same-product | 0 | 1 | Logic:\na * b = c * d; there are 8 permutations of tuples for every (a,b,c,d) that satisfy this i.e (a,b,c,d), (a,b,d,c), (b,a,c,d), (b,a,d,c), (c,d,a,b), (c,d,b,a), (d,c,a,b), (d,c,b,a). So for every two pairs (a,b) and (c,d) that have the same product, we have 8 tuples and hence whenever we find a tuple (a,b) we check how many other (c,d) are present with the same product, for each of these same product (c,d) there are 8 tuples. Hence 8 * number of tuples that have the same product.\n\n```\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n count, ans, n = collections.Counter(), 0, len(nums)\n for i in range(n):\n for j in range(i+1, n):\n ans += 8 * count[nums[i]*nums[j]]\n count[nums[i]*nums[j]] += 1\n return ans\n ``` | 14 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
[Python, Java] Elegant & Short | Counter | tuple-with-same-product | 0 | 1 | # Complexity\n- Time complexity: $$O(n^{2})$$\n- Space complexity: $$O(n^{2})$$\n\n# Code\n\n\n```python []\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n n = len(nums)\n\n products = Counter(\n nums[i] * nums[j]\n for i in range(n)\n for j in range(i + 1, n)\n )\n\n return sum(4 * cnt * (cnt - 1) for cnt in products.values() if cnt > 1)\n\n```\n```java []\nimport java.util.HashMap;\nimport java.util.Map;\n\nclass Solution {\n public int tupleSameProduct(int[] nums) {\n Map<Integer, Integer> map = new HashMap<>();\n\n for (int i = 0; i < nums.length - 1; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n int product = nums[i] * nums[j];\n map.put(product, map.getOrDefault(product, 0) + 1);\n }\n }\n\n return map.values().stream().reduce(0, (tupleCount, count) -> tupleCount + 4 * count * (count - 1));\n }\n}\n```\n | 2 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
[Python] Hashmap with explanation | tuple-with-same-product | 0 | 1 | \nFor example: [1,2,4,5,10]\n\nwe traverse the array:\n2 = nums[0] * nums[1]\n4 = nums[0] * nums[2]\n5 = nums[0] * nums[3]\n10 = nums[0] * nums[4] # (1,10)\n8 = nums[1] * nums[2]\n10 = nums[1] * nums[3] # (2,5)\n20 = nums[1] * nums[4] # (2,10)\n20 = nums[2] * nums[3] # (4,5)\n40 = nums[2] * nums[4]\n50 = nums[3] * nums[4]\n \nThe dictionary will be:\n{2: 1, 4: 1, 5: 1, 10: 2, 8: 1, 20: 2, 40: 1, 50: 1}\nwhich means we have:\n10 => (1,10) and (2,5) \n20 => (2,10) and (4,5)\n\nThere are 16 valids tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,4,5)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n\nSo, for (a,b) and (c,d), there will be 8 valid tuples.\n\nQuestion: what if we have more than two ways to get the same product, how many valid tuples do we have? \ne.g. 20 => (2,10) and (4,5) and (1,20)\n\nNext step, use the formula of combination: `n * (n-1) / 2`\n\nFor example:\n[2,3,4,6,8,12]\n=> {6: 1, 8: 1, 12: 2, 16: 1, 24: 3, 18: 1, 36: 1, 32: 1, 48: 2, 72: 1, 96: 1}\n=> 12:2, 24:3, 48:2\n12:2 => (a,b)(c,d) => 2 * (2-1)//2 * 8 = 8\n24:3 => (e,f)(g,h)(m,n) => 3* (3-1)//2 * 8 = 24\n48:2 => (p,q)(r,s) => 2 * (2-1)//2 * 8 = 8\n=> 8+24+8 = 40\n\n\n```\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n product_count = collections.defaultdict(int)\n n = len(nums)\n for i in range(n-1):\n for j in range(i+1, n):\n product = nums[i] * nums[j]\n product_count[product] += 1\n res = 0\n for k, v in product_count.items():\n if v > 1:\n res += (v*(v-1)//2) * (2**3)\n return res\n\t\t\n``` | 10 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
Python O(N^2) [ACCEPTED] 100% better | tuple-with-same-product | 0 | 1 | The idea is to count the no. of time the product occurred, its already mentioned in the question no. are disctinct, we just need to the all the combinations.\n\nFor a,b,c,d there can be 8 combinations, lets take (a,b) as 1 and (c,d) as 2 so there it can be written as "12" or "21" so 2 ways and then the 1- which is ab can also be written as "ab" or "ba" so again 2 ways and likewise for cd. So the max unique combination for a tuple (a,b,c,d) can be 2x2x2 = 8.\n\nOnce we have a count of the no. of products we can find the combination.\n\n```\ndef tupleSameProduct(nums):\n product_dict = {}\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n product = nums[i] * nums[j]\n if product in product_dict:\n product_dict[product] += 1\n else:\n product_dict[product] = 1\n \n return sum([4*v*(v-1) for v in product_dict.values() if v >= 2]) | 5 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
simple fast python | tuple-with-same-product | 0 | 1 | each pair creates 8 results. \nwe index each possible pair permutation with their product \n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n prods = defaultdict(int)\n l = len(nums)\n count = 0 \n for i in range(l): \n for j in range(i+1, l): \n p = nums[i] * nums[j]\n if p in prods : \n count += prods[p] * 8 \n prods[p] += 1 \n return count\n``` | 0 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
python3 math + hashmap | tuple-with-same-product | 0 | 1 | \n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n d = defaultdict(int)\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n d[nums[i]*nums[j]]+=1\n \n ans = 0\n for k in d.values():\n ans += 8*(k*(k-1)//2)\n return ans\n``` | 0 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
Python - one line | tuple-with-same-product | 0 | 1 | # Intuition\n"Distinct numbers" is the main insight here. This allows us to skip checking for same indices in matching pairs.\nSo just count same value occurence for different pairs.\nmultiply combination every pair with every other pair (n*(n-1), *triangular number* can be used here).\nThat number has to be multiplied with 4, why? consider this pairs a,b,c,d, they can be permuted to stay same in 4 different ways\n(a,b) (c,d)\n(b,a) (c,d)\n(a,b) (d,c)\n(b,a) (d,c)\n\n# Complexity\n\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def tupleSameProduct(self, A):\n return sum(4*v*(v-1) for v in Counter(A[i]*A[j] for i in range(len(A)) for j in range(i)).values() if v>1)\n \n\n\n \n``` | 0 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
python code | tuple-with-same-product | 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 tupleSameProduct(self, nums: List[int]) -> int:\n # step 1 calculate the num of pairs \n # step 2 formula (n*n-1)/2 for finding combinations\n # step 3 each combination have 8 ways\n dic={}\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n v=nums[i]*nums[j]\n if v not in dic:\n dic[v]=1\n else:\n dic[v]+=1\n print(dic)# dic[i] is number of pairs\n res=0\n for i in dic:\n if dic[i]>1:\n res+=((dic[i]*(dic[i]-1))//2)*8\n return res\n``` | 0 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
Easy to understand solution. | tuple-with-same-product | 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: Enlighten me!\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: Nevermind!\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n\n memo = {}\n\n Count = 0\n\n for i in combinations(nums, 2):\n product = i[0]*i[1]\n\n if product not in memo:\n memo[product] = i\n\n else:\n memo[product] += i \n Count += 4*(len(memo[product])-2)\n \n return Count\n\n``` | 0 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
[Python 3] Two-line Pythonic solution, beats 100%, O(n^2) | tuple-with-same-product | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Instead of finding each combination of $(a, b, c, d)$, look for the number of possible pairs of products $p = q$ where $p = a \\times b$ and $q = c \\times d$, and multiply by the number of permutations of $a$ and $b$ and $c$ and $d$.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Use `combinations()` to get all unique pairs $(a, b)$ in sorted order with no repeated elements, and use `Counter()` to count the occurrences of the products $p = a \\times b$ of these pairs.\n- Each of the $n$ occurrences of a product $p$ corresponds to a unique, non-overlapping pair, so the number of possible ordered pairs of products $(a, b)$ and $(c, d)$ where $a \\times b = c \\times d = p$ is $n * (n - 1)$.\n- Since each pair $(b, a)$ and $(d, c)$ is as valid as $(a, b)$ and $(c, d)$, we need to multiply the above by $2 * 2 = 4$ to account for the possible orderings of each pair. \n\n# Complexity\n- Time complexity: $O(n^2)$\n- Space complexity: $O(n^2)$\n\n# Code\n```\nclass Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n counts = Counter(a * b for a, b in combinations(nums, 2))\n return sum(4 * (n - 1) * n for n in counts.values() if n > 1)\n``` | 0 | Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._
**Example 1:**
**Input:** nums = \[2,3,4,6\]
**Output:** 8
**Explanation:** There are 8 valid tuples:
(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)
(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)
**Example 2:**
**Input:** nums = \[1,2,4,5,10\]
**Output:** 16
**Explanation:** There are 16 valid tuples:
(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)
(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)
(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)
(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* All elements in `nums` are **distinct**. | The constraints are small enough to consider every possible coordinate and calculate its quality. |
γVideoγGive me 10 minutes - how we think about a solution | largest-submatrix-with-rearrangements | 1 | 1 | # Intuition\nUsing sort for width.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/odAv92zWKqs\n\nThese days, many people watch my video more than 70% of whole time, which is good to my channel reputation. Thank you!\n\nI\'m creating this video or post with the goal of ensuring that viewers, whether they read the post or watch the video, won\'t waste their time. I\'m confident that if you spend 10 minutes watching the video, you\'ll grasp the understanding of this problem.\n\n\u25A0 Timeline of the video\n\n`0:05` How we can move columns\n`1:09` Calculate height\n`2:48` Calculate width\n`4:10` Let\'s make sure it works\n`5:40` Demonstrate how it works\n`7:44` Coding\n`9:59` Time Complexity and Space Complexity\n`10:35` Summary of the algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,225\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n## How we think about a solution\n\nWe should return the largest square in the metrix. Simply formula is\n\n```\nheight * width\n```\nLet\'s think about this.\n```\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\n```\nSince we can rearrange the matrix by entire columns, we can consider entire columns as a height.\n\n### How can we rearrange the matrix?\n\nFor example, we can move entire columns at index 2 to left.\n```\n \u2193 \u2193\n[0,0,1] [0,1,0]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [1,1,0]\n```\nWe can\'t move part of columns like this.\n```\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [1,1,0]\u2190\n```\n### Calculate height at each column.\n```\nAt column index 0\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [2,0,1]\n\nmatrix[0][0] is 0 height.\nmatrix[1][0] is 1 height.\nmatrix[2][0] is 2 height.(= from matrix[1][0] to matrix[2][0])\n```\n```\nAt column index 1\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1] \n[2,0,1] [2,0,1]\n\nmatrix[0][1] is 0 height.\nmatrix[1][1] is 1 height.\nmatrix[2][1] is 0 height.\n```\n```\nAt column index 2\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,2] \n[2,0,1] [2,0,3]\n\nmatrix[0][2] is 1 height.\nmatrix[1][2] is 2 height. (= from matrix[0][2] to matrix[1][2])\nmatrix[2][2] is 3 height. (= from matrix[0][2] to matrix[2][2])\n```\nIn the end\n```\nOriginal\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,2]\n[1,0,1]. [2,0,3]\n```\nIn my solution code, we iterate through each row one by one, then calculate heights. It\'s not difficult. When current number is `1`, add height from above row to current place. You can check it later in my solution code.\n\n### Calculate width at each row.\n\nNext, we need to think about width. We know that if each number is greater than `0`, it means that there is at least `1` in each position, so we can consider non zero position as `1` length for width.\n\nSince we can rearrange the matrix by entire columns, we can sort each row to move zero position to small index(left side).\n\nIn the solution code, we sort each row one by one but image of entire matrix after sorting is like this.\n```\n[0,0,1] [0,0,1]\n[1,1,2] \u2192 [1,1,2]\n[2,0,3] [0,2,3]\n```\nAfter sorting, all zeros in each row move to left side, that means we have some numbers on the right side, so we can consider right side as part of width.\n\nCalculation of each postion\nHeight is each number.\nWidth is length of row - current column index\n```\n[0,0,1]\n[1,1,2]\n[0,2,3]\n\n h w a\nmatrix[0][0]: 0 3 0\nmatrix[0][1]: 0 2 0\nmatrix[0][2]: 1 1 1\nmatrix[1][0]: 1 3 3\nmatrix[1][1]: 1 2 3\nmatrix[1][2]: 2 1 3\nmatrix[2][0]: 0 3 3\nmatrix[2][1]: 2 2 4\nmatrix[2][2]: 3 1 4\n\nh: height\nw: width\na: max area so far\n```\n```\nOutput: 4\n```\n### Are you sure sorting works?\n \nSomebody is wondering "Are you sure sorting works?"\n\nLet\'s focus on `[0,2,3]`. This means at `column index 1`, there is `2` heights and at `column index 2`(different column index from `column index 1`), there are `3` heights.\n\nSo we are sure that we can create this matrix.\n```\n[0,0,1] \n[1,1,1]\n[0,1,1]\n \u2191 \u2191\n 2 3\n```\nThat\'s why at `matrix[2][1]`, we calculate `2`(= height from `matrix[1][1]` to `matrix[2][1]`) * `2`(= width from `matrix[2][1]` to `matrix[2][2]`).\n\nSorting enables the creation of heights from right to left in descending order. In other words, we are sure after `column index 1`, we have `at least 2 height or more`(in this case, we have `3 heights`), so definitely we can calculate size of the square(in this case, `2 * 2`).\n\nThank you sorting algorithm!\nLet\'s wrap up the coding part quickly and grab a beer! lol\n\n---\n\n\n\n### Algorithm Overview:\n\n1. Calculate Heights:\n2. Calculate Maximum Area:\n\n### Detailed Explanation:\n\n1. **Calculate Heights:**\n```python\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row, col = len(matrix), len(matrix[0])\n\n # Calculate Heights for Each Column\n for i in range(1, row):\n for j in range(col):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n```\n\n**Explanation:**\n- This part iterates through each row (starting from the second row) and each column.\n- If the current element is 1 (`matrix[i][j] == 1`), it adds the value from the previous row to the current element.\n- This creates a cumulative sum of heights for each column, forming a "height matrix."\n\n\n2. **Calculate Maximum Area:**\n\n```python\n res = 0\n\n # Calculate Maximum Area\n for i in range(row):\n # Sort the heights in ascending order\n matrix[i].sort()\n\n # Iterate through the sorted heights\n for j in range(col):\n height = matrix[i][j]\n width = col - j\n\n # Calculate the area using the current height and remaining width\n res = max(res, height * width)\n```\n\n**Explanation:**\n- This part initializes `res` to 0, which will store the maximum area.\n- It then iterates through each row of the matrix.\n- For each row, it sorts the heights in ascending order. This is crucial for calculating the maximum area.\n- It iterates through the sorted heights and calculates the area for each height and its corresponding width.\n- The maximum area is updated in the variable `res` if a larger area is found.\n\n\n---\n\n\n\n# Complexity\n- Time complexity: $$O(row * col * log(col))$$\nSort each row and each row has length of col.\n\n- Space complexity: $$O(log col)$$ or $$O(col)$$\nExcept matrix. The sort() operation on the heights array utilizes a temporary working space, which can be estimated as $$O(log col)$$ or $$O(col)$$ in the worst case.\n\n```python []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row, col = len(matrix), len(matrix[0])\n\n # Calculate heights for each column\n for i in range(1, row):\n for j in range(col):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n\n res = 0\n for i in range(row):\n # Sort the heights in ascending order\n matrix[i].sort()\n\n # Iterate through the sorted heights\n for j in range(col):\n height = matrix[i][j]\n width = col - j\n res = max(res, height * width)\n\n return res\n```\n```javascript []\nvar largestSubmatrix = function(matrix) {\n const row = matrix.length;\n const col = matrix[0].length;\n\n // Calculate heights for each column\n for (let i = 1; i < row; i++) {\n for (let j = 0; j < col; j++) {\n if (matrix[i][j] === 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n let res = 0;\n for (let i = 0; i < row; i++) {\n // Sort the heights in ascending order\n matrix[i].sort((a, b) => a - b);\n\n // Iterate through the sorted heights\n for (let j = 0; j < col; j++) {\n const height = matrix[i][j];\n const width = col - j;\n res = Math.max(res, height * width);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int row = matrix.length;\n int col = matrix[0].length;\n\n // Calculate heights for each column\n for (int i = 1; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (matrix[i][j] == 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n int res = 0;\n for (int i = 0; i < row; i++) {\n // Sort the heights in ascending order\n Arrays.sort(matrix[i]);\n\n // Iterate through the sorted heights\n for (int j = 0; j < col; j++) {\n int height = matrix[i][j];\n int width = col - j;\n res = Math.max(res, height * width);\n }\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int row = matrix.size();\n int col = matrix[0].size();\n\n // Calculate heights for each column\n for (int i = 1; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (matrix[i][j] == 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n int res = 0;\n for (int i = 0; i < row; i++) {\n // Sort the heights in ascending order\n sort(matrix[i].begin(), matrix[i].end());\n\n // Iterate through the sorted heights\n for (int j = 0; j < col; j++) {\n int height = matrix[i][j];\n int width = col - j;\n res = max(res, height * width);\n }\n }\n\n return res; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/solutions/4340183/video-give-me-7-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/DF9NXNW0G6E\n\n\u25A0 Timeline of the video\n\n`0:05` Return 0\n`0:38` Think about a case where we can put dividers\n`4:44` Coding\n`7:18` Time Complexity and Space Complexity\n`7:33` Summary of the algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/solutions/4329227/video-give-me-10-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bwQh44GWME8\n\n\u25A0 Timeline of the video\n\n`0:05` How we can solve this question\n`1:56` Calculate left total\n`6:32` Calculate right total\n`11:12` Create answers\n`11:51` Coding\n`14:14` Time Complexity and Space Complexity\n`14:39` Summary of the algorithm with my solution code\n\n | 77 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
γVideoγGive me 10 minutes - how we think about a solution | largest-submatrix-with-rearrangements | 1 | 1 | # Intuition\nUsing sort for width.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/odAv92zWKqs\n\nThese days, many people watch my video more than 70% of whole time, which is good to my channel reputation. Thank you!\n\nI\'m creating this video or post with the goal of ensuring that viewers, whether they read the post or watch the video, won\'t waste their time. I\'m confident that if you spend 10 minutes watching the video, you\'ll grasp the understanding of this problem.\n\n\u25A0 Timeline of the video\n\n`0:05` How we can move columns\n`1:09` Calculate height\n`2:48` Calculate width\n`4:10` Let\'s make sure it works\n`5:40` Demonstrate how it works\n`7:44` Coding\n`9:59` Time Complexity and Space Complexity\n`10:35` Summary of the algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,225\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n## How we think about a solution\n\nWe should return the largest square in the metrix. Simply formula is\n\n```\nheight * width\n```\nLet\'s think about this.\n```\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\n```\nSince we can rearrange the matrix by entire columns, we can consider entire columns as a height.\n\n### How can we rearrange the matrix?\n\nFor example, we can move entire columns at index 2 to left.\n```\n \u2193 \u2193\n[0,0,1] [0,1,0]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [1,1,0]\n```\nWe can\'t move part of columns like this.\n```\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [1,1,0]\u2190\n```\n### Calculate height at each column.\n```\nAt column index 0\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1]\n[1,0,1] [2,0,1]\n\nmatrix[0][0] is 0 height.\nmatrix[1][0] is 1 height.\nmatrix[2][0] is 2 height.(= from matrix[1][0] to matrix[2][0])\n```\n```\nAt column index 1\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,1] \n[2,0,1] [2,0,1]\n\nmatrix[0][1] is 0 height.\nmatrix[1][1] is 1 height.\nmatrix[2][1] is 0 height.\n```\n```\nAt column index 2\n\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,2] \n[2,0,1] [2,0,3]\n\nmatrix[0][2] is 1 height.\nmatrix[1][2] is 2 height. (= from matrix[0][2] to matrix[1][2])\nmatrix[2][2] is 3 height. (= from matrix[0][2] to matrix[2][2])\n```\nIn the end\n```\nOriginal\n[0,0,1] [0,0,1]\n[1,1,1] \u2192 [1,1,2]\n[1,0,1]. [2,0,3]\n```\nIn my solution code, we iterate through each row one by one, then calculate heights. It\'s not difficult. When current number is `1`, add height from above row to current place. You can check it later in my solution code.\n\n### Calculate width at each row.\n\nNext, we need to think about width. We know that if each number is greater than `0`, it means that there is at least `1` in each position, so we can consider non zero position as `1` length for width.\n\nSince we can rearrange the matrix by entire columns, we can sort each row to move zero position to small index(left side).\n\nIn the solution code, we sort each row one by one but image of entire matrix after sorting is like this.\n```\n[0,0,1] [0,0,1]\n[1,1,2] \u2192 [1,1,2]\n[2,0,3] [0,2,3]\n```\nAfter sorting, all zeros in each row move to left side, that means we have some numbers on the right side, so we can consider right side as part of width.\n\nCalculation of each postion\nHeight is each number.\nWidth is length of row - current column index\n```\n[0,0,1]\n[1,1,2]\n[0,2,3]\n\n h w a\nmatrix[0][0]: 0 3 0\nmatrix[0][1]: 0 2 0\nmatrix[0][2]: 1 1 1\nmatrix[1][0]: 1 3 3\nmatrix[1][1]: 1 2 3\nmatrix[1][2]: 2 1 3\nmatrix[2][0]: 0 3 3\nmatrix[2][1]: 2 2 4\nmatrix[2][2]: 3 1 4\n\nh: height\nw: width\na: max area so far\n```\n```\nOutput: 4\n```\n### Are you sure sorting works?\n \nSomebody is wondering "Are you sure sorting works?"\n\nLet\'s focus on `[0,2,3]`. This means at `column index 1`, there is `2` heights and at `column index 2`(different column index from `column index 1`), there are `3` heights.\n\nSo we are sure that we can create this matrix.\n```\n[0,0,1] \n[1,1,1]\n[0,1,1]\n \u2191 \u2191\n 2 3\n```\nThat\'s why at `matrix[2][1]`, we calculate `2`(= height from `matrix[1][1]` to `matrix[2][1]`) * `2`(= width from `matrix[2][1]` to `matrix[2][2]`).\n\nSorting enables the creation of heights from right to left in descending order. In other words, we are sure after `column index 1`, we have `at least 2 height or more`(in this case, we have `3 heights`), so definitely we can calculate size of the square(in this case, `2 * 2`).\n\nThank you sorting algorithm!\nLet\'s wrap up the coding part quickly and grab a beer! lol\n\n---\n\n\n\n### Algorithm Overview:\n\n1. Calculate Heights:\n2. Calculate Maximum Area:\n\n### Detailed Explanation:\n\n1. **Calculate Heights:**\n```python\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row, col = len(matrix), len(matrix[0])\n\n # Calculate Heights for Each Column\n for i in range(1, row):\n for j in range(col):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n```\n\n**Explanation:**\n- This part iterates through each row (starting from the second row) and each column.\n- If the current element is 1 (`matrix[i][j] == 1`), it adds the value from the previous row to the current element.\n- This creates a cumulative sum of heights for each column, forming a "height matrix."\n\n\n2. **Calculate Maximum Area:**\n\n```python\n res = 0\n\n # Calculate Maximum Area\n for i in range(row):\n # Sort the heights in ascending order\n matrix[i].sort()\n\n # Iterate through the sorted heights\n for j in range(col):\n height = matrix[i][j]\n width = col - j\n\n # Calculate the area using the current height and remaining width\n res = max(res, height * width)\n```\n\n**Explanation:**\n- This part initializes `res` to 0, which will store the maximum area.\n- It then iterates through each row of the matrix.\n- For each row, it sorts the heights in ascending order. This is crucial for calculating the maximum area.\n- It iterates through the sorted heights and calculates the area for each height and its corresponding width.\n- The maximum area is updated in the variable `res` if a larger area is found.\n\n\n---\n\n\n\n# Complexity\n- Time complexity: $$O(row * col * log(col))$$\nSort each row and each row has length of col.\n\n- Space complexity: $$O(log col)$$ or $$O(col)$$\nExcept matrix. The sort() operation on the heights array utilizes a temporary working space, which can be estimated as $$O(log col)$$ or $$O(col)$$ in the worst case.\n\n```python []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row, col = len(matrix), len(matrix[0])\n\n # Calculate heights for each column\n for i in range(1, row):\n for j in range(col):\n if matrix[i][j] == 1:\n matrix[i][j] += matrix[i - 1][j]\n\n res = 0\n for i in range(row):\n # Sort the heights in ascending order\n matrix[i].sort()\n\n # Iterate through the sorted heights\n for j in range(col):\n height = matrix[i][j]\n width = col - j\n res = max(res, height * width)\n\n return res\n```\n```javascript []\nvar largestSubmatrix = function(matrix) {\n const row = matrix.length;\n const col = matrix[0].length;\n\n // Calculate heights for each column\n for (let i = 1; i < row; i++) {\n for (let j = 0; j < col; j++) {\n if (matrix[i][j] === 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n let res = 0;\n for (let i = 0; i < row; i++) {\n // Sort the heights in ascending order\n matrix[i].sort((a, b) => a - b);\n\n // Iterate through the sorted heights\n for (let j = 0; j < col; j++) {\n const height = matrix[i][j];\n const width = col - j;\n res = Math.max(res, height * width);\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int row = matrix.length;\n int col = matrix[0].length;\n\n // Calculate heights for each column\n for (int i = 1; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (matrix[i][j] == 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n int res = 0;\n for (int i = 0; i < row; i++) {\n // Sort the heights in ascending order\n Arrays.sort(matrix[i]);\n\n // Iterate through the sorted heights\n for (int j = 0; j < col; j++) {\n int height = matrix[i][j];\n int width = col - j;\n res = Math.max(res, height * width);\n }\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int row = matrix.size();\n int col = matrix[0].size();\n\n // Calculate heights for each column\n for (int i = 1; i < row; i++) {\n for (int j = 0; j < col; j++) {\n if (matrix[i][j] == 1) {\n matrix[i][j] += matrix[i - 1][j];\n }\n }\n }\n\n int res = 0;\n for (int i = 0; i < row; i++) {\n // Sort the heights in ascending order\n sort(matrix[i].begin(), matrix[i].end());\n\n // Iterate through the sorted heights\n for (int j = 0; j < col; j++) {\n int height = matrix[i][j];\n int width = col - j;\n res = max(res, height * width);\n }\n }\n\n return res; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/solutions/4340183/video-give-me-7-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/DF9NXNW0G6E\n\n\u25A0 Timeline of the video\n\n`0:05` Return 0\n`0:38` Think about a case where we can put dividers\n`4:44` Coding\n`7:18` Time Complexity and Space Complexity\n`7:33` Summary of the algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/solutions/4329227/video-give-me-10-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bwQh44GWME8\n\n\u25A0 Timeline of the video\n\n`0:05` How we can solve this question\n`1:56` Calculate left total\n`6:32` Calculate right total\n`11:12` Create answers\n`11:51` Coding\n`14:14` Time Complexity and Space Complexity\n`14:39` Summary of the algorithm with my solution code\n\n | 77 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
16 line Python solution (998ms) | largest-submatrix-with-rearrangements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate over rows while keeping track of the height of columns of 1\'s above the row. Sort the heights after each iteration and check the area of all possible rectangles that would fit into the graph of heights.\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$$O(n \\cdot log(n)\\cdot m)$$ with `n = matrix[i].length` and `m = matrix.length`\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ with `n = matrix[i].length`\n# Code\n```python\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix) # num rows\n n = len(matrix[0]) # num cols\n # The height of a column of 1\'s at a specific index\n heights = matrix[0].copy()\n maxArea = heights.count(1)\n for ri in range(1, m):\n # Increase or reset height of the column\n for ci in range(n):\n if matrix[ri][ci] == 1:\n heights[ci] += 1\n else:\n heights[ci] = 0\n # Bring columns into a "triangle" form, with descending values\n sortedHeights = sorted(heights.copy(), reverse=True)\n # Check the area of all possible rectangles inside the imagined triangle\n for i in range(n):\n area = sortedHeights[i] * (i+1)\n if area > maxArea:\n maxArea = area\n return maxArea\n\n``` | 2 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
16 line Python solution (998ms) | largest-submatrix-with-rearrangements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate over rows while keeping track of the height of columns of 1\'s above the row. Sort the heights after each iteration and check the area of all possible rectangles that would fit into the graph of heights.\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$$O(n \\cdot log(n)\\cdot m)$$ with `n = matrix[i].length` and `m = matrix.length`\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ with `n = matrix[i].length`\n# Code\n```python\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix) # num rows\n n = len(matrix[0]) # num cols\n # The height of a column of 1\'s at a specific index\n heights = matrix[0].copy()\n maxArea = heights.count(1)\n for ri in range(1, m):\n # Increase or reset height of the column\n for ci in range(n):\n if matrix[ri][ci] == 1:\n heights[ci] += 1\n else:\n heights[ci] = 0\n # Bring columns into a "triangle" form, with descending values\n sortedHeights = sorted(heights.copy(), reverse=True)\n # Check the area of all possible rectangles inside the imagined triangle\n for i in range(n):\n area = sortedHeights[i] * (i+1)\n if area > maxArea:\n maxArea = area\n return maxArea\n\n``` | 2 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
β
β[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINEDπ₯ | largest-submatrix-with-rearrangements | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Sort By Height On Each Baseline Row)***\n1. **Matrix traversal:**\n - The code iterates through each row of the matrix.\n1. **Accumulating consecutive ones:**\n - For each non-zero element in the matrix (except in the first row), the code accumulates its value with the element directly above it. This accumulation happens vertically, tracking consecutive ones.\n\n - For example, if we start with the first row, the elements with 1s in the second row get incremented by the value in the first row if the element in the first row at the same column is also 1. It accumulates the count of consecutive ones vertically.\n\n1. **Finding the largest submatrix:**\n - After accumulating the consecutive ones, it creates a copy of the current row and sorts it in descending order.\n\n - By sorting, the largest consecutive blocks of ones are moved to the front of the row.\n\n - The code then calculates the area of the largest submatrix by multiplying the height (number of consecutive ones) with the width (position in the sorted row). It updates and keeps track of the maximum area found.\n\n*In the example matrix:*\n\n- **For the first row:** `[0, 1, 1, 0, 1]`, the consecutive ones count would be `[0, 1, 1, 0, 2]`.\n- **For the second row:** `[1, 2, 1, 2, 0]`, the consecutive ones count would be `[1, 2, 1, 2, 0]`.\n- **For the third row:** `[1, 2, 3, 4, 0]`, the consecutive ones count would be `[1, 2, 3, 4, 0]`.\n- **For the fourth row:** `[2, 3, 4, 5, 1]`, the consecutive ones count would be `[2, 3, 4, 5, 1]`.\n\n# Complexity\n- *Time complexity:*\n $$O(m.n.logn)$$\n \n\n- *Space complexity:*\n $$O(m.n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int m = matrix.size(); // Number of rows in the matrix\n int n = matrix[0].size(); // Number of columns in the matrix\n int ans = 0; // Initialize the maximum area of the largest submatrix\n \n // Traverse through each row in the matrix\n for (int row = 0; row < m; row++) {\n // For each non-zero element in the matrix (except the first row),\n // accumulate its value with the element directly above it\n for (int col = 0; col < n; col++) {\n if (matrix[row][col] != 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n \n // Create a copy of the current row to work with\n vector<int> currRow = matrix[row];\n \n // Sort the elements in the current row in descending order\n sort(currRow.begin(), currRow.end(), greater<int>());\n \n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (int i = 0; i < n; i++) {\n ans = max(ans, currRow[i] * (i + 1));\n }\n }\n \n return ans; // Return the maximum area of the largest submatrix\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n\n// Function to calculate the maximum area of the largest submatrix with consecutive ones\nint largestSubmatrix(int** matrix, int m, int n) {\n int ans = 0; // Initialize the maximum area of the largest submatrix\n\n // Traverse through each row in the matrix\n for (int row = 0; row < m; row++) {\n // For each non-zero element in the matrix (except the first row),\n // accumulate its value with the element directly above it\n for (int col = 0; col < n; col++) {\n if (matrix[row][col] != 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n\n // Create a copy of the current row to work with\n int* currRow = malloc(n * sizeof(int));\n for (int i = 0; i < n; i++) {\n currRow[i] = matrix[row][i];\n }\n\n // Sort the elements in the current row in descending order\n for (int i = 0; i < n - 1; i++) {\n for (int j = 0; j < n - i - 1; j++) {\n if (currRow[j] < currRow[j + 1]) {\n int temp = currRow[j];\n currRow[j] = currRow[j + 1];\n currRow[j + 1] = temp;\n }\n }\n }\n\n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (int i = 0; i < n; i++) {\n ans = ans > currRow[i] * (i + 1) ? ans : currRow[i] * (i + 1);\n }\n\n free(currRow);\n }\n\n return ans; // Return the maximum area of the largest submatrix\n}\n\n\n```\n```Java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n for (int col = 0; col < n; col++) {\n if (matrix[row][col] != 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n \n int[] currRow = matrix[row].clone();\n Arrays.sort(currRow);\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, currRow[i] * (n - i));\n }\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n ans = 0\n\n for row in range(m):\n for col in range(n):\n if matrix[row][col] != 0 and row > 0:\n matrix[row][col] += matrix[row - 1][col]\n\n curr_row = sorted(matrix[row], reverse=True)\n for i in range(n):\n ans = max(ans, curr_row[i] * (i + 1))\n\n return ans\n\n```\n\n```javascript []\nfunction largestSubmatrix(matrix) {\n let m = matrix.length; // Number of rows\n let n = matrix[0].length; // Number of columns\n let ans = 0; // Initialize the maximum area of the largest submatrix\n\n // Traverse through each row in the matrix\n for (let row = 0; row < m; row++) {\n // For each non-zero element in the matrix (except the first row),\n // accumulate its value with the element directly above it\n for (let col = 0; col < n; col++) {\n if (matrix[row][col] !== 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n\n // Create a copy of the current row to work with\n let currRow = matrix[row].slice();\n \n // Sort the elements in the current row in descending order\n currRow.sort((a, b) => b - a);\n\n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, currRow[i] * (i + 1));\n }\n }\n\n return ans; // Return the maximum area of the largest submatrix\n}\n\n\n\n```\n\n---\n\n#### ***Approach 2(Without Modifying Input)***\n1. **Initialization:** Define the matrix\'s size, initialize the `prevRow` vector, and initialize ans to store the maximum area.\n1. **Iteration through Rows:** Traverse through each row of the matrix.\n1. **Cumulative Sum:** Calculate the cumulative sum for each element in the current row by adding the element with its corresponding element in the `prevRow`.\n1. **Sorting:** Sort the elements of the current row in descending order.\n1. **Calculate Maximum Area:** For each index `i`, calculate the area considering the sorted row and update `ans` if a larger area is found.\n1. **Update Previous Row:** Update the `prevRow` for the next iteration with the current row.\n1. **Return Result:** Return the maximum area found.\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(m\u22C5n\u22C5logn)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int m = matrix.size(); // Number of rows in the matrix\n int n = matrix[0].size(); // Number of columns in the matrix\n vector<int> prevRow = vector<int>(n, 0); // Vector to store the previous row\n int ans = 0; // Initialize the maximum area of the largest submatrix\n \n for (int row = 0; row < m; row++) {\n vector<int> currRow = matrix[row]; // Copy the current row of the matrix\n \n // Calculate the cumulative sum for each element in the current row\n for (int col = 0; col < n; col++) {\n if (currRow[col] != 0) {\n currRow[col] += prevRow[col]; // Add the element with its corresponding element in the previous row\n }\n }\n \n // Sort the elements in the current row in descending order\n vector<int> sortedRow = currRow;\n sort(sortedRow.begin(), sortedRow.end(), greater<int>());\n \n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (int i = 0; i < n; i++) {\n ans = max(ans, sortedRow[i] * (i + 1)); // Update the maximum area\n }\n \n prevRow = currRow; // Update the previous row for the next iteration\n }\n\n return ans; // Return the maximum area of the largest submatrix\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n\n// Function to calculate the largest submatrix\nint largestSubmatrix(int** matrix, int m, int n) {\n int ans = 0;\n int* prevRow = (int*)malloc(n * sizeof(int));\n for (int i = 0; i < n; i++) {\n prevRow[i] = 0;\n }\n\n for (int row = 0; row < m; row++) {\n int* currRow = matrix[row];\n\n for (int col = 0; col < n; col++) {\n if (currRow[col] != 0) {\n currRow[col] += prevRow[col];\n }\n }\n\n int sortedRow[n];\n for (int i = 0; i < n; i++) {\n sortedRow[i] = currRow[i];\n }\n // Sort the row in descending order\n for (int i = 0; i < n - 1; i++) {\n for (int j = 0; j < n - i - 1; j++) {\n if (sortedRow[j] < sortedRow[j + 1]) {\n int temp = sortedRow[j];\n sortedRow[j] = sortedRow[j + 1];\n sortedRow[j + 1] = temp;\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n ans = ans > sortedRow[i] * (i + 1) ? ans : sortedRow[i] * (i + 1);\n }\n\n for (int i = 0; i < n; i++) {\n prevRow[i] = currRow[i];\n }\n }\n\n free(prevRow);\n return ans;\n}\n\n\n```\n```Java []\n\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[] prevRow = new int[n];\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n int[] currRow = matrix[row].clone();\n for (int col = 0; col < n; col++) {\n if (currRow[col] != 0) {\n currRow[col] += prevRow[col];\n }\n }\n \n int[] sortedRow = currRow.clone();\n Arrays.sort(sortedRow);\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, sortedRow[i] * (n - i));\n }\n \n prevRow = currRow;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n prev_row = [0] * n\n ans = 0\n \n for row in range(m):\n curr_row = matrix[row][:]\n for col in range(n):\n if curr_row[col] != 0:\n curr_row[col] += prev_row[col]\n\n sorted_row = sorted(curr_row, reverse=True)\n for i in range(n):\n ans = max(ans, sorted_row[i] * (i + 1))\n\n prev_row = curr_row\n\n return ans\n\n```\n\n```javascript []\nfunction largestSubmatrix(matrix) {\n let m = matrix.length;\n let n = matrix[0].length;\n let prevRow = Array(n).fill(0);\n let ans = 0;\n\n for (let row = 0; row < m; row++) {\n let currRow = [...matrix[row]];\n\n for (let col = 0; col < n; col++) {\n if (currRow[col] !== 0) {\n currRow[col] += prevRow[col];\n }\n }\n\n let sortedRow = [...currRow].sort((a, b) => b - a);\n\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, sortedRow[i] * (i + 1));\n }\n\n prevRow = [...currRow];\n }\n\n return ans;\n}\n\n```\n\n---\n#### ***Approach 3(No Sort)***\n\n1. **largestSubmatrix Function:**\n - Finds the largest submatrix of consecutive ones in the given matrix.\n \n1. **Variables Used:**\n - **`m` and `n`:** Number of rows and columns in the matrix, respectively.\n - **prevHeights:** Stores heights of 1s from the previous row.\n - **ans:** Tracks the maximum submatrix area.\n1. **Iterating Through Each Row:**\n - The outer loop iterates through each row of the matrix.\n1. **Finding Heights of Ones in Each Row:**\n - For each row, it tracks the heights of consecutive 1s and columns seen in the previous row.\n - **heights:** Vector that stores pairs of heights and corresponding columns for the current row.\n - **seen:** Tracks the columns that have already been seen in the previous row.\n1. **Calculating Heights:**\n - It iterates through the previous heights and increments the height for each 1 encountered in the current row.\n - For new 1s in the current row (not seen in the previous row), it sets a new height.\n1. **Calculating Maximum Submatrix Area:**\n - For each height, it calculates the area by multiplying the height by the width (i + 1) and updates `ans` if a larger area is found.\n1. **Updating Heights for the Next Row:**\n - Updates `prevHeights` with the heights from the current row to prepare for the next row iteration.\n1. **Returns:**\n - Returns the maximum submatrix area found.\n\n# Complexity\n- *Time complexity:*\n $$O(m.n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int m = matrix.size(); // Number of rows in the matrix\n int n = matrix[0].size(); // Number of columns in the matrix\n vector<pair<int,int>> prevHeights; // To store heights of 1s from the previous row\n int ans = 0; // Initialize the maximum submatrix area\n \n for (int row = 0; row < m; row++) {\n vector<pair<int,int>> heights; // Heights of 1s for the current row\n vector<bool> seen = vector(n, false); // To track the columns already seen\n \n // Process the heights from the previous row\n for (auto [height, col] : prevHeights) {\n if (matrix[row][col] == 1) {\n heights.push_back({height + 1, col}); // Increase the height if the current element is 1\n seen[col] = true; // Mark the column as seen\n }\n }\n \n // Process the new heights in the current row\n for (int col = 0; col < n; col++) {\n if (seen[col] == false && matrix[row][col] == 1) {\n heights.push_back({1, col}); // New height for a new column\n }\n }\n \n // Calculate the area for each height and update the maximum area\n for (int i = 0; i < heights.size(); i++) {\n ans = max(ans, heights[i].first * (i + 1));\n }\n \n prevHeights = heights; // Update the heights for the next row\n }\n\n return ans; // Return the maximum submatrix area\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct Pair {\n int first;\n int second;\n};\n\nint max(int a, int b) {\n return (a > b) ? a : b;\n}\n\nint largestSubmatrix(int** matrix, int m, int n) {\n struct Pair* prevHeights = malloc(sizeof(struct Pair) * n);\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n struct Pair* heights = malloc(sizeof(struct Pair) * n);\n int* seen = calloc(n, sizeof(int));\n \n for (int i = 0; i < n; i++) {\n heights[i].first = 0;\n heights[i].second = 0;\n }\n \n for (int i = 0; i < n; i++) {\n heights[i].first = prevHeights[i].first;\n heights[i].second = prevHeights[i].second;\n }\n \n for (int col = 0; col < n; col++) {\n if (matrix[row][col] == 1) {\n if (row > 0 && matrix[row - 1][col] == 1) {\n heights[col].first++;\n }\n else {\n heights[col].first = 1;\n heights[col].second = col;\n }\n seen[col] = 1;\n }\n }\n \n for (int col = 0; col < n; col++) {\n if (seen[col] == 0 && matrix[row][col] == 1) {\n heights[col].first = 1;\n heights[col].second = col;\n }\n }\n \n for (int i = 0; i < n; i++) {\n ans = max(ans, heights[i].first * (i + 1));\n }\n \n for (int i = 0; i < n; i++) {\n prevHeights[i].first = heights[i].first;\n prevHeights[i].second = heights[i].second;\n }\n \n free(heights);\n free(seen);\n }\n\n free(prevHeights);\n return ans;\n}\n\n\n```\n```Java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n List<Pair<Integer,Integer>> prevHeights = new ArrayList();\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n List<Pair<Integer,Integer>> heights = new ArrayList();\n boolean[] seen = new boolean[n];\n \n for (Pair<Integer, Integer> pair : prevHeights) {\n int height = pair.getKey();\n int col = pair.getValue();\n if (matrix[row][col] == 1) {\n heights.add(new Pair(height + 1, col));\n seen[col] = true;\n }\n }\n \n for (int col = 0; col < n; col++) {\n if (seen[col] == false && matrix[row][col] == 1) {\n heights.add(new Pair(1, col));\n }\n }\n \n for (int i = 0; i < heights.size(); i++) {\n ans = Math.max(ans, heights.get(i).getKey() * (i + 1));\n }\n\n prevHeights = heights;\n }\n \n return ans;\n }\n}\n\n\n\n\n```\n```python3 []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n prev_heights = []\n ans = 0\n\n for row in range(m):\n heights = []\n seen = [False] * n\n \n for height, col in prev_heights:\n if matrix[row][col] == 1:\n heights.append((height + 1, col))\n seen[col] = True\n\n for col in range(n):\n if seen[col] == False and matrix[row][col] == 1:\n heights.append((1, col))\n \n for i in range(len(heights)):\n ans = max(ans, heights[i][0] * (i + 1))\n \n prev_heights = heights\n\n return ans\n\n```\n\n```javascript []\nfunction largestSubmatrix(matrix) {\n let m = matrix.length;\n let n = matrix[0].length;\n let prevHeights = new Array(n).fill({ first: 0, second: 0 });\n let ans = 0;\n\n for (let row = 0; row < m; row++) {\n let heights = new Array(n).fill({ first: 0, second: 0 });\n let seen = new Array(n).fill(0);\n\n for (let i = 0; i < n; i++) {\n heights[i].first = prevHeights[i].first;\n heights[i].second = prevHeights[i].second;\n }\n\n for (let col = 0; col < n; col++) {\n if (matrix[row][col] === 1) {\n if (row > 0 && matrix[row - 1][col] === 1) {\n heights[col].first++;\n } else {\n heights[col].first = 1;\n heights[col].second = col;\n }\n seen[col] = 1;\n }\n }\n\n for (let col = 0; col < n; col++) {\n if (seen[col] === 0 && matrix[row][col] === 1) {\n heights[col].first = 1;\n heights[col].second = col;\n }\n }\n\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, heights[i].first * (i + 1));\n }\n\n prevHeights = heights;\n }\n\n return ans;\n}\n\n```\n\n---\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 2 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
β
β[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINEDπ₯ | largest-submatrix-with-rearrangements | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Sort By Height On Each Baseline Row)***\n1. **Matrix traversal:**\n - The code iterates through each row of the matrix.\n1. **Accumulating consecutive ones:**\n - For each non-zero element in the matrix (except in the first row), the code accumulates its value with the element directly above it. This accumulation happens vertically, tracking consecutive ones.\n\n - For example, if we start with the first row, the elements with 1s in the second row get incremented by the value in the first row if the element in the first row at the same column is also 1. It accumulates the count of consecutive ones vertically.\n\n1. **Finding the largest submatrix:**\n - After accumulating the consecutive ones, it creates a copy of the current row and sorts it in descending order.\n\n - By sorting, the largest consecutive blocks of ones are moved to the front of the row.\n\n - The code then calculates the area of the largest submatrix by multiplying the height (number of consecutive ones) with the width (position in the sorted row). It updates and keeps track of the maximum area found.\n\n*In the example matrix:*\n\n- **For the first row:** `[0, 1, 1, 0, 1]`, the consecutive ones count would be `[0, 1, 1, 0, 2]`.\n- **For the second row:** `[1, 2, 1, 2, 0]`, the consecutive ones count would be `[1, 2, 1, 2, 0]`.\n- **For the third row:** `[1, 2, 3, 4, 0]`, the consecutive ones count would be `[1, 2, 3, 4, 0]`.\n- **For the fourth row:** `[2, 3, 4, 5, 1]`, the consecutive ones count would be `[2, 3, 4, 5, 1]`.\n\n# Complexity\n- *Time complexity:*\n $$O(m.n.logn)$$\n \n\n- *Space complexity:*\n $$O(m.n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int m = matrix.size(); // Number of rows in the matrix\n int n = matrix[0].size(); // Number of columns in the matrix\n int ans = 0; // Initialize the maximum area of the largest submatrix\n \n // Traverse through each row in the matrix\n for (int row = 0; row < m; row++) {\n // For each non-zero element in the matrix (except the first row),\n // accumulate its value with the element directly above it\n for (int col = 0; col < n; col++) {\n if (matrix[row][col] != 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n \n // Create a copy of the current row to work with\n vector<int> currRow = matrix[row];\n \n // Sort the elements in the current row in descending order\n sort(currRow.begin(), currRow.end(), greater<int>());\n \n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (int i = 0; i < n; i++) {\n ans = max(ans, currRow[i] * (i + 1));\n }\n }\n \n return ans; // Return the maximum area of the largest submatrix\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n\n// Function to calculate the maximum area of the largest submatrix with consecutive ones\nint largestSubmatrix(int** matrix, int m, int n) {\n int ans = 0; // Initialize the maximum area of the largest submatrix\n\n // Traverse through each row in the matrix\n for (int row = 0; row < m; row++) {\n // For each non-zero element in the matrix (except the first row),\n // accumulate its value with the element directly above it\n for (int col = 0; col < n; col++) {\n if (matrix[row][col] != 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n\n // Create a copy of the current row to work with\n int* currRow = malloc(n * sizeof(int));\n for (int i = 0; i < n; i++) {\n currRow[i] = matrix[row][i];\n }\n\n // Sort the elements in the current row in descending order\n for (int i = 0; i < n - 1; i++) {\n for (int j = 0; j < n - i - 1; j++) {\n if (currRow[j] < currRow[j + 1]) {\n int temp = currRow[j];\n currRow[j] = currRow[j + 1];\n currRow[j + 1] = temp;\n }\n }\n }\n\n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (int i = 0; i < n; i++) {\n ans = ans > currRow[i] * (i + 1) ? ans : currRow[i] * (i + 1);\n }\n\n free(currRow);\n }\n\n return ans; // Return the maximum area of the largest submatrix\n}\n\n\n```\n```Java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n for (int col = 0; col < n; col++) {\n if (matrix[row][col] != 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n \n int[] currRow = matrix[row].clone();\n Arrays.sort(currRow);\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, currRow[i] * (n - i));\n }\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n ans = 0\n\n for row in range(m):\n for col in range(n):\n if matrix[row][col] != 0 and row > 0:\n matrix[row][col] += matrix[row - 1][col]\n\n curr_row = sorted(matrix[row], reverse=True)\n for i in range(n):\n ans = max(ans, curr_row[i] * (i + 1))\n\n return ans\n\n```\n\n```javascript []\nfunction largestSubmatrix(matrix) {\n let m = matrix.length; // Number of rows\n let n = matrix[0].length; // Number of columns\n let ans = 0; // Initialize the maximum area of the largest submatrix\n\n // Traverse through each row in the matrix\n for (let row = 0; row < m; row++) {\n // For each non-zero element in the matrix (except the first row),\n // accumulate its value with the element directly above it\n for (let col = 0; col < n; col++) {\n if (matrix[row][col] !== 0 && row > 0) {\n matrix[row][col] += matrix[row - 1][col];\n }\n }\n\n // Create a copy of the current row to work with\n let currRow = matrix[row].slice();\n \n // Sort the elements in the current row in descending order\n currRow.sort((a, b) => b - a);\n\n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, currRow[i] * (i + 1));\n }\n }\n\n return ans; // Return the maximum area of the largest submatrix\n}\n\n\n\n```\n\n---\n\n#### ***Approach 2(Without Modifying Input)***\n1. **Initialization:** Define the matrix\'s size, initialize the `prevRow` vector, and initialize ans to store the maximum area.\n1. **Iteration through Rows:** Traverse through each row of the matrix.\n1. **Cumulative Sum:** Calculate the cumulative sum for each element in the current row by adding the element with its corresponding element in the `prevRow`.\n1. **Sorting:** Sort the elements of the current row in descending order.\n1. **Calculate Maximum Area:** For each index `i`, calculate the area considering the sorted row and update `ans` if a larger area is found.\n1. **Update Previous Row:** Update the `prevRow` for the next iteration with the current row.\n1. **Return Result:** Return the maximum area found.\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(m\u22C5n\u22C5logn)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int m = matrix.size(); // Number of rows in the matrix\n int n = matrix[0].size(); // Number of columns in the matrix\n vector<int> prevRow = vector<int>(n, 0); // Vector to store the previous row\n int ans = 0; // Initialize the maximum area of the largest submatrix\n \n for (int row = 0; row < m; row++) {\n vector<int> currRow = matrix[row]; // Copy the current row of the matrix\n \n // Calculate the cumulative sum for each element in the current row\n for (int col = 0; col < n; col++) {\n if (currRow[col] != 0) {\n currRow[col] += prevRow[col]; // Add the element with its corresponding element in the previous row\n }\n }\n \n // Sort the elements in the current row in descending order\n vector<int> sortedRow = currRow;\n sort(sortedRow.begin(), sortedRow.end(), greater<int>());\n \n // Calculate the maximum area of the largest submatrix with consecutive ones\n for (int i = 0; i < n; i++) {\n ans = max(ans, sortedRow[i] * (i + 1)); // Update the maximum area\n }\n \n prevRow = currRow; // Update the previous row for the next iteration\n }\n\n return ans; // Return the maximum area of the largest submatrix\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n\n// Function to calculate the largest submatrix\nint largestSubmatrix(int** matrix, int m, int n) {\n int ans = 0;\n int* prevRow = (int*)malloc(n * sizeof(int));\n for (int i = 0; i < n; i++) {\n prevRow[i] = 0;\n }\n\n for (int row = 0; row < m; row++) {\n int* currRow = matrix[row];\n\n for (int col = 0; col < n; col++) {\n if (currRow[col] != 0) {\n currRow[col] += prevRow[col];\n }\n }\n\n int sortedRow[n];\n for (int i = 0; i < n; i++) {\n sortedRow[i] = currRow[i];\n }\n // Sort the row in descending order\n for (int i = 0; i < n - 1; i++) {\n for (int j = 0; j < n - i - 1; j++) {\n if (sortedRow[j] < sortedRow[j + 1]) {\n int temp = sortedRow[j];\n sortedRow[j] = sortedRow[j + 1];\n sortedRow[j + 1] = temp;\n }\n }\n }\n\n for (int i = 0; i < n; i++) {\n ans = ans > sortedRow[i] * (i + 1) ? ans : sortedRow[i] * (i + 1);\n }\n\n for (int i = 0; i < n; i++) {\n prevRow[i] = currRow[i];\n }\n }\n\n free(prevRow);\n return ans;\n}\n\n\n```\n```Java []\n\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[] prevRow = new int[n];\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n int[] currRow = matrix[row].clone();\n for (int col = 0; col < n; col++) {\n if (currRow[col] != 0) {\n currRow[col] += prevRow[col];\n }\n }\n \n int[] sortedRow = currRow.clone();\n Arrays.sort(sortedRow);\n for (int i = 0; i < n; i++) {\n ans = Math.max(ans, sortedRow[i] * (n - i));\n }\n \n prevRow = currRow;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n prev_row = [0] * n\n ans = 0\n \n for row in range(m):\n curr_row = matrix[row][:]\n for col in range(n):\n if curr_row[col] != 0:\n curr_row[col] += prev_row[col]\n\n sorted_row = sorted(curr_row, reverse=True)\n for i in range(n):\n ans = max(ans, sorted_row[i] * (i + 1))\n\n prev_row = curr_row\n\n return ans\n\n```\n\n```javascript []\nfunction largestSubmatrix(matrix) {\n let m = matrix.length;\n let n = matrix[0].length;\n let prevRow = Array(n).fill(0);\n let ans = 0;\n\n for (let row = 0; row < m; row++) {\n let currRow = [...matrix[row]];\n\n for (let col = 0; col < n; col++) {\n if (currRow[col] !== 0) {\n currRow[col] += prevRow[col];\n }\n }\n\n let sortedRow = [...currRow].sort((a, b) => b - a);\n\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, sortedRow[i] * (i + 1));\n }\n\n prevRow = [...currRow];\n }\n\n return ans;\n}\n\n```\n\n---\n#### ***Approach 3(No Sort)***\n\n1. **largestSubmatrix Function:**\n - Finds the largest submatrix of consecutive ones in the given matrix.\n \n1. **Variables Used:**\n - **`m` and `n`:** Number of rows and columns in the matrix, respectively.\n - **prevHeights:** Stores heights of 1s from the previous row.\n - **ans:** Tracks the maximum submatrix area.\n1. **Iterating Through Each Row:**\n - The outer loop iterates through each row of the matrix.\n1. **Finding Heights of Ones in Each Row:**\n - For each row, it tracks the heights of consecutive 1s and columns seen in the previous row.\n - **heights:** Vector that stores pairs of heights and corresponding columns for the current row.\n - **seen:** Tracks the columns that have already been seen in the previous row.\n1. **Calculating Heights:**\n - It iterates through the previous heights and increments the height for each 1 encountered in the current row.\n - For new 1s in the current row (not seen in the previous row), it sets a new height.\n1. **Calculating Maximum Submatrix Area:**\n - For each height, it calculates the area by multiplying the height by the width (i + 1) and updates `ans` if a larger area is found.\n1. **Updating Heights for the Next Row:**\n - Updates `prevHeights` with the heights from the current row to prepare for the next row iteration.\n1. **Returns:**\n - Returns the maximum submatrix area found.\n\n# Complexity\n- *Time complexity:*\n $$O(m.n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int largestSubmatrix(vector<vector<int>>& matrix) {\n int m = matrix.size(); // Number of rows in the matrix\n int n = matrix[0].size(); // Number of columns in the matrix\n vector<pair<int,int>> prevHeights; // To store heights of 1s from the previous row\n int ans = 0; // Initialize the maximum submatrix area\n \n for (int row = 0; row < m; row++) {\n vector<pair<int,int>> heights; // Heights of 1s for the current row\n vector<bool> seen = vector(n, false); // To track the columns already seen\n \n // Process the heights from the previous row\n for (auto [height, col] : prevHeights) {\n if (matrix[row][col] == 1) {\n heights.push_back({height + 1, col}); // Increase the height if the current element is 1\n seen[col] = true; // Mark the column as seen\n }\n }\n \n // Process the new heights in the current row\n for (int col = 0; col < n; col++) {\n if (seen[col] == false && matrix[row][col] == 1) {\n heights.push_back({1, col}); // New height for a new column\n }\n }\n \n // Calculate the area for each height and update the maximum area\n for (int i = 0; i < heights.size(); i++) {\n ans = max(ans, heights[i].first * (i + 1));\n }\n \n prevHeights = heights; // Update the heights for the next row\n }\n\n return ans; // Return the maximum submatrix area\n }\n};\n\n\n\n```\n```C []\n\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct Pair {\n int first;\n int second;\n};\n\nint max(int a, int b) {\n return (a > b) ? a : b;\n}\n\nint largestSubmatrix(int** matrix, int m, int n) {\n struct Pair* prevHeights = malloc(sizeof(struct Pair) * n);\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n struct Pair* heights = malloc(sizeof(struct Pair) * n);\n int* seen = calloc(n, sizeof(int));\n \n for (int i = 0; i < n; i++) {\n heights[i].first = 0;\n heights[i].second = 0;\n }\n \n for (int i = 0; i < n; i++) {\n heights[i].first = prevHeights[i].first;\n heights[i].second = prevHeights[i].second;\n }\n \n for (int col = 0; col < n; col++) {\n if (matrix[row][col] == 1) {\n if (row > 0 && matrix[row - 1][col] == 1) {\n heights[col].first++;\n }\n else {\n heights[col].first = 1;\n heights[col].second = col;\n }\n seen[col] = 1;\n }\n }\n \n for (int col = 0; col < n; col++) {\n if (seen[col] == 0 && matrix[row][col] == 1) {\n heights[col].first = 1;\n heights[col].second = col;\n }\n }\n \n for (int i = 0; i < n; i++) {\n ans = max(ans, heights[i].first * (i + 1));\n }\n \n for (int i = 0; i < n; i++) {\n prevHeights[i].first = heights[i].first;\n prevHeights[i].second = heights[i].second;\n }\n \n free(heights);\n free(seen);\n }\n\n free(prevHeights);\n return ans;\n}\n\n\n```\n```Java []\nclass Solution {\n public int largestSubmatrix(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n List<Pair<Integer,Integer>> prevHeights = new ArrayList();\n int ans = 0;\n \n for (int row = 0; row < m; row++) {\n List<Pair<Integer,Integer>> heights = new ArrayList();\n boolean[] seen = new boolean[n];\n \n for (Pair<Integer, Integer> pair : prevHeights) {\n int height = pair.getKey();\n int col = pair.getValue();\n if (matrix[row][col] == 1) {\n heights.add(new Pair(height + 1, col));\n seen[col] = true;\n }\n }\n \n for (int col = 0; col < n; col++) {\n if (seen[col] == false && matrix[row][col] == 1) {\n heights.add(new Pair(1, col));\n }\n }\n \n for (int i = 0; i < heights.size(); i++) {\n ans = Math.max(ans, heights.get(i).getKey() * (i + 1));\n }\n\n prevHeights = heights;\n }\n \n return ans;\n }\n}\n\n\n\n\n```\n```python3 []\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len(matrix[0])\n prev_heights = []\n ans = 0\n\n for row in range(m):\n heights = []\n seen = [False] * n\n \n for height, col in prev_heights:\n if matrix[row][col] == 1:\n heights.append((height + 1, col))\n seen[col] = True\n\n for col in range(n):\n if seen[col] == False and matrix[row][col] == 1:\n heights.append((1, col))\n \n for i in range(len(heights)):\n ans = max(ans, heights[i][0] * (i + 1))\n \n prev_heights = heights\n\n return ans\n\n```\n\n```javascript []\nfunction largestSubmatrix(matrix) {\n let m = matrix.length;\n let n = matrix[0].length;\n let prevHeights = new Array(n).fill({ first: 0, second: 0 });\n let ans = 0;\n\n for (let row = 0; row < m; row++) {\n let heights = new Array(n).fill({ first: 0, second: 0 });\n let seen = new Array(n).fill(0);\n\n for (let i = 0; i < n; i++) {\n heights[i].first = prevHeights[i].first;\n heights[i].second = prevHeights[i].second;\n }\n\n for (let col = 0; col < n; col++) {\n if (matrix[row][col] === 1) {\n if (row > 0 && matrix[row - 1][col] === 1) {\n heights[col].first++;\n } else {\n heights[col].first = 1;\n heights[col].second = col;\n }\n seen[col] = 1;\n }\n }\n\n for (let col = 0; col < n; col++) {\n if (seen[col] === 0 && matrix[row][col] === 1) {\n heights[col].first = 1;\n heights[col].second = col;\n }\n }\n\n for (let i = 0; i < n; i++) {\n ans = Math.max(ans, heights[i].first * (i + 1));\n }\n\n prevHeights = heights;\n }\n\n return ans;\n}\n\n```\n\n---\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 2 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
Python3 Solution | largest-submatrix-with-rearrangements | 0 | 1 | \n```\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row=len(matrix)\n col=len(matrix[0])\n ans=0\n for r in range(1,row):\n for c in range(col):\n matrix[r][c]+=matrix[r-1][c] if matrix[r][c] else 0\n\n for r in range(row):\n matrix[r].sort(reverse=True)\n for c in range(col):\n ans=max(ans,(c+1)*matrix[r][c])\n return ans \n``` | 2 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
Python3 Solution | largest-submatrix-with-rearrangements | 0 | 1 | \n```\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n row=len(matrix)\n col=len(matrix[0])\n ans=0\n for r in range(1,row):\n for c in range(col):\n matrix[r][c]+=matrix[r-1][c] if matrix[r][c] else 0\n\n for r in range(row):\n matrix[r].sort(reverse=True)\n for c in range(col):\n ans=max(ans,(c+1)*matrix[r][c])\n return ans \n``` | 2 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
One line solution. Runtime 100%!!! | largest-submatrix-with-rearrangements | 0 | 1 | \n```\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n return max(max(map(mul, sorted(row, reverse = True), count(1))) for row in accumulate(matrix, lambda row_s, row: list(map(lambda s, n: (s+n)*n, row_s, row))))\n```\n> More readable\n```\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n def prefix_sum(row_s, row):\n return list(map(lambda s, n: (s+n)*n, row_s, row))\n return max(max(map(mul, sorted(row, reverse = True), count(1))) for row in accumulate(matrix, prefix_sum))\n``` | 1 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
One line solution. Runtime 100%!!! | largest-submatrix-with-rearrangements | 0 | 1 | \n```\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n return max(max(map(mul, sorted(row, reverse = True), count(1))) for row in accumulate(matrix, lambda row_s, row: list(map(lambda s, n: (s+n)*n, row_s, row))))\n```\n> More readable\n```\nclass Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n def prefix_sum(row_s, row):\n return list(map(lambda s, n: (s+n)*n, row_s, row))\n return max(max(map(mul, sorted(row, reverse = True), count(1))) for row in accumulate(matrix, prefix_sum))\n``` | 1 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
[WeπSimple] Counting Sort, Dynamic Programming w/ Explanations | largest-submatrix-with-rearrangements | 0 | 1 | I always like to find solutions that are very simple and easy, yet do not sacrifice time complexity. I keep creating more solutions\n\n# Code\n``` Kotlin []\nclass Solution {\n fun largestSubmatrix(matrix: Array<IntArray>): Int {\n val heights = IntArray(matrix[0].size)\n var maxArea = 0\n for (row in matrix) {\n val countByHeightInRow = sortedMapOf<Int, Int>(Comparator.reverseOrder())\n for ((j, v) in row.withIndex()) {\n if (v == 0) {\n heights[j] = 0\n } else {\n heights[j] += 1\n countByHeightInRow[heights[j]] = countByHeightInRow.getOrDefault(heights[j], 0) + 1\n }\n }\n var accHeightCount = 0\n for ((height, count) in countByHeightInRow) {\n accHeightCount += count\n maxArea = maxOf(maxArea, accHeightCount * height)\n }\n }\n return maxArea\n }\n}\n\n// Shorter version\nclass Solution {\n fun largestSubmatrix(matrix: Array<IntArray>): Int =\n matrix.fold(0 to IntArray(matrix[0].size)) { (maxArea, heights), row ->\n sortedMapOf<Int, Int>(Comparator.reverseOrder()).apply {\n for ((j, v) in row.withIndex()) {\n heights[j] = if (v == 0) 0 else heights[j] + 1\n this[heights[j]] = this.getOrDefault(heights[j], 0) + 1\n }\n }.entries.fold(maxArea to 0) { (maxArea, acc), (height, count) ->\n maxOf(maxArea, height * (acc + count)) to acc + count\n }.first to heights\n }.first\n}\n\n// Sort version\nclass Solution {\n fun largestSubmatrix(matrix: Array<IntArray>): Int {\n val m = matrix.size\n val n = matrix[0].size\n var maxArea = 0\n\n for (i in 1 until m) {\n for (j in 0 until n) {\n if (matrix[i][j] != 0) {\n matrix[i][j] += matrix[i - 1][j]\n }\n }\n }\n\n for (row in matrix) {\n row.sort()\n for (j in 0 until n) {\n maxArea = maxOf(maxArea, row[j] * (n - j))\n }\n }\n\n return maxArea\n }\n}\n\n```\n\n``` Python3 []\nclass Solution:\n def largestSubmatrix(self, matrix):\n heights = [0] * len(matrix[0])\n answer = 0\n\n for row in matrix:\n count_by_height = {}\n for j, value in enumerate(row):\n if value == 0:\n heights[j] = 0\n else:\n heights[j] += 1\n count_by_height[heights[j]] = count_by_height.get(heights[j], 0) + 1\n \n acc_height_count = 0\n for height in sorted(count_by_height.keys(), reverse=True):\n acc_height_count += count_by_height[height]\n answer = max(answer, acc_height_count * height)\n \n return answer\n```\n\n1. **Iterating Through Each Row and Calculating Heights**: The algorithm iterates through each row of the matrix and calculates the \'heights\' of consecutive 1s for each column. This \'height\' represents the number of 1s stacked vertically up to the current row. For instance, if a column has 1s in three consecutive rows, its height would be 3 in the third row. This step is crucial because it transforms the problem into a series of histogram-like structures where each column\'s height can be visualized as a bar in a histogram.\n\n2. **Count Sorting of Heights**: After computing the heights for each column in a row, these heights are sorted in descending order using a `sortedMapOf`. This sorting is essential because it aligns the columns in order of their heights, prioritizing taller \'bars\' first. This priority is key for efficiently finding the largest rectangle at each step.\n3. **Iterating in Descending Order of Heights**: The algorithm then iterates over these heights, starting from the tallest. During this iteration, it calculates the potential size of the submatrix (rectangle) that can be formed using the current height as the limiting factor. The idea is to consider the tallest column and see how wide the rectangle can be, encompassing shorter columns to its right. This process is repeated for each height, progressively considering shorter heights and wider potential rectangles.\n4. **Updating the Maximum Submatrix Size**: For each height, the algorithm calculates the area of the potential rectangle and updates the maximum size found so far. This update is a crucial step because it ensures that the largest possible submatrix is not missed. The area is calculated by multiplying the current height with the cumulative count of columns that are at least as tall as the current height.\n\nBy integrating these steps, the algorithm efficiently finds the largest rectangular area in a binary matrix. The use of height calculation transforms the 2D problem into a series of 1D problems (like histograms), and the sorted iteration ensures that the largest possible rectangles are considered first, optimizing the search for the maximum area. This approach is a blend of dynamic programming (keeping track of heights) and a greedy strategy (prioritizing larger heights first).\n | 1 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
[WeπSimple] Counting Sort, Dynamic Programming w/ Explanations | largest-submatrix-with-rearrangements | 0 | 1 | I always like to find solutions that are very simple and easy, yet do not sacrifice time complexity. I keep creating more solutions\n\n# Code\n``` Kotlin []\nclass Solution {\n fun largestSubmatrix(matrix: Array<IntArray>): Int {\n val heights = IntArray(matrix[0].size)\n var maxArea = 0\n for (row in matrix) {\n val countByHeightInRow = sortedMapOf<Int, Int>(Comparator.reverseOrder())\n for ((j, v) in row.withIndex()) {\n if (v == 0) {\n heights[j] = 0\n } else {\n heights[j] += 1\n countByHeightInRow[heights[j]] = countByHeightInRow.getOrDefault(heights[j], 0) + 1\n }\n }\n var accHeightCount = 0\n for ((height, count) in countByHeightInRow) {\n accHeightCount += count\n maxArea = maxOf(maxArea, accHeightCount * height)\n }\n }\n return maxArea\n }\n}\n\n// Shorter version\nclass Solution {\n fun largestSubmatrix(matrix: Array<IntArray>): Int =\n matrix.fold(0 to IntArray(matrix[0].size)) { (maxArea, heights), row ->\n sortedMapOf<Int, Int>(Comparator.reverseOrder()).apply {\n for ((j, v) in row.withIndex()) {\n heights[j] = if (v == 0) 0 else heights[j] + 1\n this[heights[j]] = this.getOrDefault(heights[j], 0) + 1\n }\n }.entries.fold(maxArea to 0) { (maxArea, acc), (height, count) ->\n maxOf(maxArea, height * (acc + count)) to acc + count\n }.first to heights\n }.first\n}\n\n// Sort version\nclass Solution {\n fun largestSubmatrix(matrix: Array<IntArray>): Int {\n val m = matrix.size\n val n = matrix[0].size\n var maxArea = 0\n\n for (i in 1 until m) {\n for (j in 0 until n) {\n if (matrix[i][j] != 0) {\n matrix[i][j] += matrix[i - 1][j]\n }\n }\n }\n\n for (row in matrix) {\n row.sort()\n for (j in 0 until n) {\n maxArea = maxOf(maxArea, row[j] * (n - j))\n }\n }\n\n return maxArea\n }\n}\n\n```\n\n``` Python3 []\nclass Solution:\n def largestSubmatrix(self, matrix):\n heights = [0] * len(matrix[0])\n answer = 0\n\n for row in matrix:\n count_by_height = {}\n for j, value in enumerate(row):\n if value == 0:\n heights[j] = 0\n else:\n heights[j] += 1\n count_by_height[heights[j]] = count_by_height.get(heights[j], 0) + 1\n \n acc_height_count = 0\n for height in sorted(count_by_height.keys(), reverse=True):\n acc_height_count += count_by_height[height]\n answer = max(answer, acc_height_count * height)\n \n return answer\n```\n\n1. **Iterating Through Each Row and Calculating Heights**: The algorithm iterates through each row of the matrix and calculates the \'heights\' of consecutive 1s for each column. This \'height\' represents the number of 1s stacked vertically up to the current row. For instance, if a column has 1s in three consecutive rows, its height would be 3 in the third row. This step is crucial because it transforms the problem into a series of histogram-like structures where each column\'s height can be visualized as a bar in a histogram.\n\n2. **Count Sorting of Heights**: After computing the heights for each column in a row, these heights are sorted in descending order using a `sortedMapOf`. This sorting is essential because it aligns the columns in order of their heights, prioritizing taller \'bars\' first. This priority is key for efficiently finding the largest rectangle at each step.\n3. **Iterating in Descending Order of Heights**: The algorithm then iterates over these heights, starting from the tallest. During this iteration, it calculates the potential size of the submatrix (rectangle) that can be formed using the current height as the limiting factor. The idea is to consider the tallest column and see how wide the rectangle can be, encompassing shorter columns to its right. This process is repeated for each height, progressively considering shorter heights and wider potential rectangles.\n4. **Updating the Maximum Submatrix Size**: For each height, the algorithm calculates the area of the potential rectangle and updates the maximum size found so far. This update is a crucial step because it ensures that the largest possible submatrix is not missed. The area is calculated by multiplying the current height with the cumulative count of columns that are at least as tall as the current height.\n\nBy integrating these steps, the algorithm efficiently finds the largest rectangular area in a binary matrix. The use of height calculation transforms the 2D problem into a series of 1D problems (like histograms), and the sorted iteration ensures that the largest possible rectangles are considered first, optimizing the search for the maximum area. This approach is a blend of dynamic programming (keeping track of heights) and a greedy strategy (prioritizing larger heights first).\n | 1 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
Python3 Clean & Commented Top-down DP with the early stopping trick | cat-and-mouse-ii | 0 | 1 | The question is composed of sub-problems, which can be formatted as the dp problem.\n\nThe tricky part is that we don\'t need to do 1000 turns to determine the result.\nLet\'s say the cat and the mouse decide to take only 1 step each time, how many turns it takes to search the whole grid?\nYes, m * n * 2 (mouse and cat, each takes m * n turns).\nSo we can early stop the search and return False (cat wins) when the turn exceeds m * n * 2.\n\n~~Time Complexity: O((MN) ^ 3)~~\nUPDATE2:\nBecause we iterate all jumps in each recursive function, the time complexity should be multiplied by (M + N).\n\n**Time Complexity: O((MN) ^ 3 * (M + N))**\n**Space Complexity: O((MN) ^ 3)**\n\nCredits to @DBabichev.\n\nUPDATE1:\nWe could further improve the constraint as well.\nWe calculate numbers of the available steps and make it the constraint of the turns.\nThis trick improves this code from 9372 ms\t74.3 MB -> 5200 ms\t57.5 MB.\n\n```\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n m, n = len(grid), len(grid[0])\n mouse_pos = cat_pos = None\n\t\tavailable = 0 # available steps for mouse and cat\n\t\t# Search the start pos of mouse and cat\n for i in range(m):\n for j in range(n):\n\t\t\t\tif grid[i][j] != \'#\':\n available += 1\n if grid[i][j] == \'M\':\n mouse_pos = (i, j)\n elif grid[i][j] == \'C\':\n cat_pos = (i, j)\n \n @functools.lru_cache(None)\n def dp(turn, mouse_pos, cat_pos):\n # if turn == m * n * 2:\n\t\t\t# We already search the whole grid (9372 ms 74.3 MB)\n\t\t\tif turn == available * 2:\n\t\t\t\t# We already search the whole touchable grid (5200 ms 57.5 MB)\n return False\n if turn % 2 == 0:\n # Mouse\n i, j = mouse_pos\n for di, dj in dirs:\n for jump in range(mouseJump + 1):\n\t\t\t\t\t\t# Note that we want to do range(mouseJump + 1) instead of range(1, mouseJump + 1)\n\t\t\t\t\t\t# considering the case that we can stay at the same postion for next turn.\n new_i, new_j = i + di * jump, j + dj * jump\n if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != \'#\':\n\t\t\t\t\t\t\t# Valid pos\n if dp(turn + 1, (new_i, new_j), cat_pos) or grid[new_i][new_j] == \'F\':\n return True\n else:\n\t\t\t\t\t\t\t# Stop extending the jump since we cannot go further\n break\n return False\n else:\n # Cat\n i, j = cat_pos\n for di, dj in dirs:\n for jump in range(catJump + 1):\n new_i, new_j = i + di * jump, j + dj * jump\n if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != \'#\':\n if not dp(turn + 1, mouse_pos, (new_i, new_j)) or (new_i, new_j) == mouse_pos or grid[new_i][new_j] == \'F\':\n\t\t\t\t\t\t\t# This condition will also handle the case that the cat cannot jump through the mouse\n return False\n else:\n break\n return True\n\t\t\t\t\n return dp(0, mouse_pos, cat_pos)\n``` | 53 | A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.
* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
* Floors are represented by the character `'.'` and can be walked on.
* Walls are represented by the character `'#'` and cannot be walked on.
* Food is represented by the character `'F'` and can be walked on.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
Mouse and Cat play according to the following rules:
* Mouse **moves first**, then they take turns to move.
* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
* Staying in the same position is allowed.
* Mouse can jump over Cat.
The game can end in 4 ways:
* If Cat occupies the same position as Mouse, Cat wins.
* If Cat reaches the food first, Cat wins.
* If Mouse reaches the food first, Mouse wins.
* If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
**Example 2:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true
**Example 3:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false
**Constraints:**
* `rows == grid.length`
* `cols = grid[i].length`
* `1 <= rows, cols <= 8`
* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
* `1 <= catJump, mouseJump <= 8` | Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value. |
Python3 Clean & Commented Top-down DP with the early stopping trick | cat-and-mouse-ii | 0 | 1 | The question is composed of sub-problems, which can be formatted as the dp problem.\n\nThe tricky part is that we don\'t need to do 1000 turns to determine the result.\nLet\'s say the cat and the mouse decide to take only 1 step each time, how many turns it takes to search the whole grid?\nYes, m * n * 2 (mouse and cat, each takes m * n turns).\nSo we can early stop the search and return False (cat wins) when the turn exceeds m * n * 2.\n\n~~Time Complexity: O((MN) ^ 3)~~\nUPDATE2:\nBecause we iterate all jumps in each recursive function, the time complexity should be multiplied by (M + N).\n\n**Time Complexity: O((MN) ^ 3 * (M + N))**\n**Space Complexity: O((MN) ^ 3)**\n\nCredits to @DBabichev.\n\nUPDATE1:\nWe could further improve the constraint as well.\nWe calculate numbers of the available steps and make it the constraint of the turns.\nThis trick improves this code from 9372 ms\t74.3 MB -> 5200 ms\t57.5 MB.\n\n```\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n m, n = len(grid), len(grid[0])\n mouse_pos = cat_pos = None\n\t\tavailable = 0 # available steps for mouse and cat\n\t\t# Search the start pos of mouse and cat\n for i in range(m):\n for j in range(n):\n\t\t\t\tif grid[i][j] != \'#\':\n available += 1\n if grid[i][j] == \'M\':\n mouse_pos = (i, j)\n elif grid[i][j] == \'C\':\n cat_pos = (i, j)\n \n @functools.lru_cache(None)\n def dp(turn, mouse_pos, cat_pos):\n # if turn == m * n * 2:\n\t\t\t# We already search the whole grid (9372 ms 74.3 MB)\n\t\t\tif turn == available * 2:\n\t\t\t\t# We already search the whole touchable grid (5200 ms 57.5 MB)\n return False\n if turn % 2 == 0:\n # Mouse\n i, j = mouse_pos\n for di, dj in dirs:\n for jump in range(mouseJump + 1):\n\t\t\t\t\t\t# Note that we want to do range(mouseJump + 1) instead of range(1, mouseJump + 1)\n\t\t\t\t\t\t# considering the case that we can stay at the same postion for next turn.\n new_i, new_j = i + di * jump, j + dj * jump\n if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != \'#\':\n\t\t\t\t\t\t\t# Valid pos\n if dp(turn + 1, (new_i, new_j), cat_pos) or grid[new_i][new_j] == \'F\':\n return True\n else:\n\t\t\t\t\t\t\t# Stop extending the jump since we cannot go further\n break\n return False\n else:\n # Cat\n i, j = cat_pos\n for di, dj in dirs:\n for jump in range(catJump + 1):\n new_i, new_j = i + di * jump, j + dj * jump\n if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != \'#\':\n if not dp(turn + 1, mouse_pos, (new_i, new_j)) or (new_i, new_j) == mouse_pos or grid[new_i][new_j] == \'F\':\n\t\t\t\t\t\t\t# This condition will also handle the case that the cat cannot jump through the mouse\n return False\n else:\n break\n return True\n\t\t\t\t\n return dp(0, mouse_pos, cat_pos)\n``` | 53 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
1000 turns is too big a threshold | cat-and-mouse-ii | 0 | 1 | # Code\n```\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n m = len(grid)\n n = len(grid[0])\n for i in range(m):\n for j in range(n):\n if grid[i][j] == \'F\':\n food = (i,j)\n elif grid[i][j] == \'C\':\n cato = (i,j)\n #grid[i][j] = \'.\'\n elif grid[i][j] == \'M\':\n mouseo = (i,j)\n #grid[i][j] = \'.\'\n @cache\n def dp(mousepos,catpos,turns):\n if mousepos == catpos:\n return False\n if catpos == food:\n return False\n if turns >= m*n*2:# all combinations probed, no need to go deeper\n return False\n if mousepos == food:\n return True\n if turns % 2 == 0:\n for di,dj in [(0,1),(1,0),(-1,0),(0,-1)]:\n for k in range(mouseJump+1):\n newi,newj = mousepos[0] + k*di,mousepos[1] + k*dj\n if 0<=newi<m and 0<=newj<n:\n if grid[newi][newj] != \'#\':\n t = dp((newi,newj),catpos,turns+1)\n if t:\n return True\n else:break\n return False\n else:\n for di,dj in [(0,1),(1,0),(-1,0),(0,-1)]:\n for k in range(catJump+1):\n newi,newj = catpos[0] + k*di,catpos[1] + k*dj\n if 0<=newi<m and 0<=newj<n:\n if grid[newi][newj] != \'#\': # pay attention not to jump across the wall\n t = dp(mousepos,(newi,newj),turns+1)\n if not t:\n return False\n else:break\n return True\n return dp(mouseo,cato,0)\n\n\n\n\n \n``` | 0 | A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.
* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
* Floors are represented by the character `'.'` and can be walked on.
* Walls are represented by the character `'#'` and cannot be walked on.
* Food is represented by the character `'F'` and can be walked on.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
Mouse and Cat play according to the following rules:
* Mouse **moves first**, then they take turns to move.
* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
* Staying in the same position is allowed.
* Mouse can jump over Cat.
The game can end in 4 ways:
* If Cat occupies the same position as Mouse, Cat wins.
* If Cat reaches the food first, Cat wins.
* If Mouse reaches the food first, Mouse wins.
* If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
**Example 2:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true
**Example 3:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false
**Constraints:**
* `rows == grid.length`
* `cols = grid[i].length`
* `1 <= rows, cols <= 8`
* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
* `1 <= catJump, mouseJump <= 8` | Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value. |
1000 turns is too big a threshold | cat-and-mouse-ii | 0 | 1 | # Code\n```\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n m = len(grid)\n n = len(grid[0])\n for i in range(m):\n for j in range(n):\n if grid[i][j] == \'F\':\n food = (i,j)\n elif grid[i][j] == \'C\':\n cato = (i,j)\n #grid[i][j] = \'.\'\n elif grid[i][j] == \'M\':\n mouseo = (i,j)\n #grid[i][j] = \'.\'\n @cache\n def dp(mousepos,catpos,turns):\n if mousepos == catpos:\n return False\n if catpos == food:\n return False\n if turns >= m*n*2:# all combinations probed, no need to go deeper\n return False\n if mousepos == food:\n return True\n if turns % 2 == 0:\n for di,dj in [(0,1),(1,0),(-1,0),(0,-1)]:\n for k in range(mouseJump+1):\n newi,newj = mousepos[0] + k*di,mousepos[1] + k*dj\n if 0<=newi<m and 0<=newj<n:\n if grid[newi][newj] != \'#\':\n t = dp((newi,newj),catpos,turns+1)\n if t:\n return True\n else:break\n return False\n else:\n for di,dj in [(0,1),(1,0),(-1,0),(0,-1)]:\n for k in range(catJump+1):\n newi,newj = catpos[0] + k*di,catpos[1] + k*dj\n if 0<=newi<m and 0<=newj<n:\n if grid[newi][newj] != \'#\': # pay attention not to jump across the wall\n t = dp(mousepos,(newi,newj),turns+1)\n if not t:\n return False\n else:break\n return True\n return dp(mouseo,cato,0)\n\n\n\n\n \n``` | 0 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
Clean DP + Shortest path heuristic + Early stopping | cat-and-mouse-ii | 0 | 1 | # Approach\nUses DP to cache the expansion of the game tree. It also pre-computes the shortest distance from any reachable point to the food and uses it to explore those branches first. Finally, it also uses a couple of early stopping conditions including if there exists a path from the mouse or cat to the food, and the number of turns that have passed based on the grid size.\n\n\n# Code\n```\nfrom typing import Optional\nfrom functools import lru_cache\nfrom collections import deque\n\nclass Solution:\n def canMouseWin(self, grid: list[str], catJump: int, mouseJump: int) -> bool:\n N, M = len(grid), len(grid[0])\n mouse_pos = None\n cat_pos = None\n food_pos = None\n _grid = [list(s) for s in grid]\n\n # remove cat, mouse, and food from grid\n for i in range(len(_grid)):\n for j in range(len(_grid[0])):\n if _grid[i][j] == "C":\n cat_pos = (i, j)\n _grid[i][j] = "."\n elif _grid[i][j] == "M":\n mouse_pos = (i, j)\n _grid[i][j] = "."\n elif _grid[i][j] == "F":\n food_pos = (i, j)\n _grid[i][j] = "."\n\n assert mouse_pos is not None\n assert cat_pos is not None\n assert food_pos is not None\n\n def next_positions(pos, max_jump):\n i, j = pos\n # UP\n for k in range(1, max_jump + 1):\n if i + k >= N or _grid[i + k][j] == "#":\n break\n yield (i + k, j)\n # RIGHT\n for k in range(1, max_jump + 1):\n if j + k >= M or _grid[i][j + k] == "#":\n break\n yield (i, j + k)\n # DOWN\n for k in range(1, max_jump + 1):\n if i - k < 0 or _grid[i - k][j] == "#":\n break\n yield (i - k, j)\n # RIGHT\n for k in range(1, max_jump + 1):\n if j - k < 0 or _grid[i][j - k] == "#":\n break\n yield (i, j - k)\n # stay still\n yield (i, j)\n\n # calculate distance to food\n distance_to_food = dict[tuple[int, int], int]()\n bag = deque[tuple[int, int, int]]()\n bag.append((0, *food_pos))\n\n while bag:\n distance, i, j = bag.pop()\n\n if (i, j) in distance_to_food:\n if distance < distance_to_food[(i, j)]:\n distance_to_food[(i, j)] = distance\n continue\n \n distance_to_food[(i, j)] = distance\n\n for i, j in next_positions((i, j), max_jump=1):\n bag.append((distance + 1, i, j))\n \n \n @lru_cache(maxsize=None)\n def mouse_wins(turn: int, mouse_pos: tuple[int, int], cat_pos: tuple[int, int]) -> bool:\n if turn == 1000 or turn == 2 * N * M: # early stopping\n return False\n if mouse_pos == cat_pos:\n return False\n if mouse_pos == food_pos:\n return True\n if cat_pos == food_pos:\n return False\n\n if turn % 2 == 0: # mouse turn\n # get positions sorted by distance to food\n # if not reachable, set all distances to 0 (no sort)\n positions = sorted(\n next_positions(mouse_pos, mouseJump), \n key=lambda p: distance_to_food.get(p, 0)\n )\n # min max: mouse chooses the first action that wins\n for next_pos in positions:\n if mouse_wins(turn + 1, next_pos, cat_pos):\n return True\n # else, mouse loses\n return False\n else: # cat turn\n # get positions sorted by distance to food\n # if not reachable, set all distances to 0 (no sort)\n positions = sorted(\n next_positions(cat_pos, catJump),\n key=lambda p: distance_to_food.get(p, 0)\n )\n for next_pos in positions:\n # min max: cat chooses the first action that makes the mouse lose\n if not mouse_wins(turn + 1, mouse_pos, next_pos):\n return False\n # else, mouse wins\n return True\n \n # early stopping\n if mouse_pos not in distance_to_food:\n return False\n if cat_pos not in distance_to_food:\n return True\n \n return mouse_wins(0, mouse_pos, cat_pos) \n``` | 0 | A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.
* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
* Floors are represented by the character `'.'` and can be walked on.
* Walls are represented by the character `'#'` and cannot be walked on.
* Food is represented by the character `'F'` and can be walked on.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
Mouse and Cat play according to the following rules:
* Mouse **moves first**, then they take turns to move.
* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
* Staying in the same position is allowed.
* Mouse can jump over Cat.
The game can end in 4 ways:
* If Cat occupies the same position as Mouse, Cat wins.
* If Cat reaches the food first, Cat wins.
* If Mouse reaches the food first, Mouse wins.
* If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
**Example 2:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true
**Example 3:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false
**Constraints:**
* `rows == grid.length`
* `cols = grid[i].length`
* `1 <= rows, cols <= 8`
* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
* `1 <= catJump, mouseJump <= 8` | Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value. |
Clean DP + Shortest path heuristic + Early stopping | cat-and-mouse-ii | 0 | 1 | # Approach\nUses DP to cache the expansion of the game tree. It also pre-computes the shortest distance from any reachable point to the food and uses it to explore those branches first. Finally, it also uses a couple of early stopping conditions including if there exists a path from the mouse or cat to the food, and the number of turns that have passed based on the grid size.\n\n\n# Code\n```\nfrom typing import Optional\nfrom functools import lru_cache\nfrom collections import deque\n\nclass Solution:\n def canMouseWin(self, grid: list[str], catJump: int, mouseJump: int) -> bool:\n N, M = len(grid), len(grid[0])\n mouse_pos = None\n cat_pos = None\n food_pos = None\n _grid = [list(s) for s in grid]\n\n # remove cat, mouse, and food from grid\n for i in range(len(_grid)):\n for j in range(len(_grid[0])):\n if _grid[i][j] == "C":\n cat_pos = (i, j)\n _grid[i][j] = "."\n elif _grid[i][j] == "M":\n mouse_pos = (i, j)\n _grid[i][j] = "."\n elif _grid[i][j] == "F":\n food_pos = (i, j)\n _grid[i][j] = "."\n\n assert mouse_pos is not None\n assert cat_pos is not None\n assert food_pos is not None\n\n def next_positions(pos, max_jump):\n i, j = pos\n # UP\n for k in range(1, max_jump + 1):\n if i + k >= N or _grid[i + k][j] == "#":\n break\n yield (i + k, j)\n # RIGHT\n for k in range(1, max_jump + 1):\n if j + k >= M or _grid[i][j + k] == "#":\n break\n yield (i, j + k)\n # DOWN\n for k in range(1, max_jump + 1):\n if i - k < 0 or _grid[i - k][j] == "#":\n break\n yield (i - k, j)\n # RIGHT\n for k in range(1, max_jump + 1):\n if j - k < 0 or _grid[i][j - k] == "#":\n break\n yield (i, j - k)\n # stay still\n yield (i, j)\n\n # calculate distance to food\n distance_to_food = dict[tuple[int, int], int]()\n bag = deque[tuple[int, int, int]]()\n bag.append((0, *food_pos))\n\n while bag:\n distance, i, j = bag.pop()\n\n if (i, j) in distance_to_food:\n if distance < distance_to_food[(i, j)]:\n distance_to_food[(i, j)] = distance\n continue\n \n distance_to_food[(i, j)] = distance\n\n for i, j in next_positions((i, j), max_jump=1):\n bag.append((distance + 1, i, j))\n \n \n @lru_cache(maxsize=None)\n def mouse_wins(turn: int, mouse_pos: tuple[int, int], cat_pos: tuple[int, int]) -> bool:\n if turn == 1000 or turn == 2 * N * M: # early stopping\n return False\n if mouse_pos == cat_pos:\n return False\n if mouse_pos == food_pos:\n return True\n if cat_pos == food_pos:\n return False\n\n if turn % 2 == 0: # mouse turn\n # get positions sorted by distance to food\n # if not reachable, set all distances to 0 (no sort)\n positions = sorted(\n next_positions(mouse_pos, mouseJump), \n key=lambda p: distance_to_food.get(p, 0)\n )\n # min max: mouse chooses the first action that wins\n for next_pos in positions:\n if mouse_wins(turn + 1, next_pos, cat_pos):\n return True\n # else, mouse loses\n return False\n else: # cat turn\n # get positions sorted by distance to food\n # if not reachable, set all distances to 0 (no sort)\n positions = sorted(\n next_positions(cat_pos, catJump),\n key=lambda p: distance_to_food.get(p, 0)\n )\n for next_pos in positions:\n # min max: cat chooses the first action that makes the mouse lose\n if not mouse_wins(turn + 1, mouse_pos, next_pos):\n return False\n # else, mouse wins\n return True\n \n # early stopping\n if mouse_pos not in distance_to_food:\n return False\n if cat_pos not in distance_to_food:\n return True\n \n return mouse_wins(0, mouse_pos, cat_pos) \n``` | 0 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
Python solution | cat-and-mouse-ii | 0 | 1 | # Intuition\n\nThe code is relatively long. It does the following. First you need to get a graph, one for the cat one for the mouse. They differ as the max jump size may be different. Then we have a two player game, on the product of these two graphs.\n\nThe function `alice_wins` compute if the first player (the mouse) can win the game within `max_step` steps. \n\n# Code\n```\ndef alice_wins(g_alice, g_bob, alice, bob, max_step=None):\n bob_step_cnt = [[len(ni)] * len(g_alice) for ni in g_bob]\n value = [[0] * len(g_bob) for _ in range(len(g_alice))]\n\n for i, j in alice:\n bob_step_cnt[j][i] = 0\n value[i][j] = 1\n for j, i in bob:\n bob_step_cnt[j][i] = -1\n value[i][j] = -1\n\n pos = alice.copy()\n for i in range(len(g_alice)):\n for j in range(len(g_bob)):\n if bob_step_cnt[j][i] == 0:\n for i0 in g_alice[i]:\n if value[i0][j] == 0:\n value[i0][j] = 1\n pos.append((i0, j))\n\n step_count = 2\n tmp = []\n while pos and step_count < max_step:\n step_count += 2\n while pos:\n i, j = pos.pop()\n for j0 in g_bob[j]:\n if bob_step_cnt[j0][i] > 0:\n bob_step_cnt[j0][i] -= 1\n if bob_step_cnt[j0][i] == 0:\n for i0 in g_alice[i]:\n if value[i0][j0] == 0:\n tmp.append((i0, j0))\n value[i0][j0] = 1\n pos, tmp = tmp, pos\n # print(f"bob_step_cnt=\\n{str(np.array(bob_step_cnt))}")\n return value\n\n\ndef get_graph(vertices, grid, max_jump):\n m, n = len(grid), len(grid[0])\n\n def neighbors(a, b):\n result = [vertices[(a,b)]]\n a0 = a - 1\n while 0 <= a0 and a - a0 <= max_jump and grid[a0][b]!="#":\n result.append(vertices[(a0, b)])\n a0 -= 1\n a0 = a + 1\n while a0 < m and a0 - a <= max_jump and grid[a0][b] != "#":\n result.append(vertices[(a0, b)])\n a0 += 1\n b0 = b - 1\n while 0 <= b0 and b - b0 <= max_jump and grid[a][b0] != "#":\n result.append(vertices[(a, b0)])\n b0 -= 1\n b0 = b + 1\n while b0 < n and b0 - b <= max_jump and grid[a][b0] != "#":\n result.append(vertices[(a, b0)])\n b0 += 1\n return result\n\n graph = [neighbors(a, b) for a, b in vertices]\n return graph\n pass\n\ndef sol(grid, catJump, mouseJump):\n vertices = [(i,j) for i, line in enumerate(grid) for j, ch in enumerate(line) if ch!="#" ]\n vertices = {v: k for k, v in enumerate(vertices)}\n g_cat = get_graph(vertices, grid, catJump)\n g_mouse = get_graph(vertices, grid, mouseJump)\n for i, line in enumerate(grid):\n for j, ch in enumerate(line):\n if ch == "F":\n food_pos = vertices[(i,j)]\n elif ch == "M":\n mouse_pos = vertices[(i,j)]\n elif ch == "C":\n cat_pos = vertices[(i,j)]\n mouse = [(food_pos, j) for j in range(len(vertices)) if j != food_pos]\n cat = [(food_pos, j) for j in range(len(vertices))] + [(j,j) for j in range(len(vertices))]\n value = alice_wins(g_mouse, g_cat, mouse, cat, 1000)\n return value[mouse_pos][cat_pos]==1\n\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n return sol(grid, catJump, mouseJump)\n``` | 0 | A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.
* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
* Floors are represented by the character `'.'` and can be walked on.
* Walls are represented by the character `'#'` and cannot be walked on.
* Food is represented by the character `'F'` and can be walked on.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
Mouse and Cat play according to the following rules:
* Mouse **moves first**, then they take turns to move.
* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
* Staying in the same position is allowed.
* Mouse can jump over Cat.
The game can end in 4 ways:
* If Cat occupies the same position as Mouse, Cat wins.
* If Cat reaches the food first, Cat wins.
* If Mouse reaches the food first, Mouse wins.
* If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
**Example 2:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true
**Example 3:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false
**Constraints:**
* `rows == grid.length`
* `cols = grid[i].length`
* `1 <= rows, cols <= 8`
* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
* `1 <= catJump, mouseJump <= 8` | Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value. |
Python solution | cat-and-mouse-ii | 0 | 1 | # Intuition\n\nThe code is relatively long. It does the following. First you need to get a graph, one for the cat one for the mouse. They differ as the max jump size may be different. Then we have a two player game, on the product of these two graphs.\n\nThe function `alice_wins` compute if the first player (the mouse) can win the game within `max_step` steps. \n\n# Code\n```\ndef alice_wins(g_alice, g_bob, alice, bob, max_step=None):\n bob_step_cnt = [[len(ni)] * len(g_alice) for ni in g_bob]\n value = [[0] * len(g_bob) for _ in range(len(g_alice))]\n\n for i, j in alice:\n bob_step_cnt[j][i] = 0\n value[i][j] = 1\n for j, i in bob:\n bob_step_cnt[j][i] = -1\n value[i][j] = -1\n\n pos = alice.copy()\n for i in range(len(g_alice)):\n for j in range(len(g_bob)):\n if bob_step_cnt[j][i] == 0:\n for i0 in g_alice[i]:\n if value[i0][j] == 0:\n value[i0][j] = 1\n pos.append((i0, j))\n\n step_count = 2\n tmp = []\n while pos and step_count < max_step:\n step_count += 2\n while pos:\n i, j = pos.pop()\n for j0 in g_bob[j]:\n if bob_step_cnt[j0][i] > 0:\n bob_step_cnt[j0][i] -= 1\n if bob_step_cnt[j0][i] == 0:\n for i0 in g_alice[i]:\n if value[i0][j0] == 0:\n tmp.append((i0, j0))\n value[i0][j0] = 1\n pos, tmp = tmp, pos\n # print(f"bob_step_cnt=\\n{str(np.array(bob_step_cnt))}")\n return value\n\n\ndef get_graph(vertices, grid, max_jump):\n m, n = len(grid), len(grid[0])\n\n def neighbors(a, b):\n result = [vertices[(a,b)]]\n a0 = a - 1\n while 0 <= a0 and a - a0 <= max_jump and grid[a0][b]!="#":\n result.append(vertices[(a0, b)])\n a0 -= 1\n a0 = a + 1\n while a0 < m and a0 - a <= max_jump and grid[a0][b] != "#":\n result.append(vertices[(a0, b)])\n a0 += 1\n b0 = b - 1\n while 0 <= b0 and b - b0 <= max_jump and grid[a][b0] != "#":\n result.append(vertices[(a, b0)])\n b0 -= 1\n b0 = b + 1\n while b0 < n and b0 - b <= max_jump and grid[a][b0] != "#":\n result.append(vertices[(a, b0)])\n b0 += 1\n return result\n\n graph = [neighbors(a, b) for a, b in vertices]\n return graph\n pass\n\ndef sol(grid, catJump, mouseJump):\n vertices = [(i,j) for i, line in enumerate(grid) for j, ch in enumerate(line) if ch!="#" ]\n vertices = {v: k for k, v in enumerate(vertices)}\n g_cat = get_graph(vertices, grid, catJump)\n g_mouse = get_graph(vertices, grid, mouseJump)\n for i, line in enumerate(grid):\n for j, ch in enumerate(line):\n if ch == "F":\n food_pos = vertices[(i,j)]\n elif ch == "M":\n mouse_pos = vertices[(i,j)]\n elif ch == "C":\n cat_pos = vertices[(i,j)]\n mouse = [(food_pos, j) for j in range(len(vertices)) if j != food_pos]\n cat = [(food_pos, j) for j in range(len(vertices))] + [(j,j) for j in range(len(vertices))]\n value = alice_wins(g_mouse, g_cat, mouse, cat, 1000)\n return value[mouse_pos][cat_pos]==1\n\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n return sol(grid, catJump, mouseJump)\n``` | 0 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
[Python3] dp | cat-and-mouse-ii | 0 | 1 | **Algo**\nI wrote this implementation based on this [post](https://leetcode.com/problems/cat-and-mouse-ii/discuss/1020616/Python3-Clean-and-Commented-Top-down-DP-with-the-early-stopping-trick). Although the 1000 turns limit looks fishy as the grid is at most 8x8, I couldn\'t come up with a bound as tight as `m*n*2`. In fact, I still don\'t understand why this upper bound works. Please share your insight here. In the meantime, I will update this post once it becomes clear to me. \n\n**Implementation**\n```\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n m, n = len(grid), len(grid[0]) # dimensions \n walls = set()\n for i in range(m):\n for j in range(n):\n if grid[i][j] == "F": food = (i, j)\n elif grid[i][j] == "C": cat = (i, j)\n elif grid[i][j] == "M": mouse = (i, j)\n elif grid[i][j] == "#": walls.add((i, j))\n \n @lru_cache(None)\n def fn(cat, mouse, turn): \n """Return True if mouse wins."""\n if cat == food or cat == mouse or turn >= m*n*2: return False \n if mouse == food: return True # mouse reaching food\n \n if not turn & 1: # mouse moving \n x, y = mouse\n for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1): \n for jump in range(0, mouseJump+1):\n xx, yy = x+jump*dx, y+jump*dy\n if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: break \n if fn(cat, (xx, yy), turn+1): return True \n return False \n else: # cat moving\n x, y = cat\n for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1): \n for jump in range(0, catJump+1):\n xx, yy = x+jump*dx, y+jump*dy\n if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: break \n if not fn((xx, yy), mouse, turn+1): return False\n return True\n \n return fn(cat, mouse, 0)\n```\n\n**Analysis**\nTime complexity `O((MN)^3)`\nSpace complexity `O((MN)^3)` | 6 | A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.
* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
* Floors are represented by the character `'.'` and can be walked on.
* Walls are represented by the character `'#'` and cannot be walked on.
* Food is represented by the character `'F'` and can be walked on.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
Mouse and Cat play according to the following rules:
* Mouse **moves first**, then they take turns to move.
* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
* Staying in the same position is allowed.
* Mouse can jump over Cat.
The game can end in 4 ways:
* If Cat occupies the same position as Mouse, Cat wins.
* If Cat reaches the food first, Cat wins.
* If Mouse reaches the food first, Mouse wins.
* If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
**Example 2:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true
**Example 3:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false
**Constraints:**
* `rows == grid.length`
* `cols = grid[i].length`
* `1 <= rows, cols <= 8`
* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
* `1 <= catJump, mouseJump <= 8` | Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value. |
[Python3] dp | cat-and-mouse-ii | 0 | 1 | **Algo**\nI wrote this implementation based on this [post](https://leetcode.com/problems/cat-and-mouse-ii/discuss/1020616/Python3-Clean-and-Commented-Top-down-DP-with-the-early-stopping-trick). Although the 1000 turns limit looks fishy as the grid is at most 8x8, I couldn\'t come up with a bound as tight as `m*n*2`. In fact, I still don\'t understand why this upper bound works. Please share your insight here. In the meantime, I will update this post once it becomes clear to me. \n\n**Implementation**\n```\nclass Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n m, n = len(grid), len(grid[0]) # dimensions \n walls = set()\n for i in range(m):\n for j in range(n):\n if grid[i][j] == "F": food = (i, j)\n elif grid[i][j] == "C": cat = (i, j)\n elif grid[i][j] == "M": mouse = (i, j)\n elif grid[i][j] == "#": walls.add((i, j))\n \n @lru_cache(None)\n def fn(cat, mouse, turn): \n """Return True if mouse wins."""\n if cat == food or cat == mouse or turn >= m*n*2: return False \n if mouse == food: return True # mouse reaching food\n \n if not turn & 1: # mouse moving \n x, y = mouse\n for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1): \n for jump in range(0, mouseJump+1):\n xx, yy = x+jump*dx, y+jump*dy\n if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: break \n if fn(cat, (xx, yy), turn+1): return True \n return False \n else: # cat moving\n x, y = cat\n for dx, dy in (-1, 0), (0, 1), (1, 0), (0, -1): \n for jump in range(0, catJump+1):\n xx, yy = x+jump*dx, y+jump*dy\n if not (0 <= xx < m and 0 <= yy < n) or (xx, yy) in walls: break \n if not fn((xx, yy), mouse, turn+1): return False\n return True\n \n return fn(cat, mouse, 0)\n```\n\n**Analysis**\nTime complexity `O((MN)^3)`\nSpace complexity `O((MN)^3)` | 6 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
[Python] Top Down DP | cat-and-mouse-ii | 0 | 1 | **Approach:**\n\n1. For every space that is not a wall, find which spaces the cat and mouse can jump to from this space. (```cat_moves``` and ```mouse_moves```)\n\n2. Find the starting locations of the cat, the mouse, and the food. (```cat```, ```mouse```, and ```food```)\n\n3. Take an Alice and Bob style game approach to determine if there is a guaranteed path to victory for the mouse. <br>\nThe exit conditions are:\n**i.** if the mouse reaches the food return True\n**ii.** if the game runs out of turns or the cat reaches the food or the mouse return False<br>\nIf none of the exit conditions have been met:\n**i.** and it is the cat\'s turn, try all possible cat moves, if any choice results in the mouse losing, return False\n**ii.** and it is the mouse\'s turn, try all possible mouse moves, if any choice results in the mouse winning, return True\n\n**Optimizations:**\n\n1. The board is rather small (8 by 8 at most) so the outcome of any game that \ngoes on for 1,000 moves can definitely be resolved in fewer moves. By trial and\nerror 2·R·C is a satisfactory bound for the maximum number of turns.\n*Note: since the cat moves on odd turns, it is important that this number is even.*\n\n2. Caching the possible moves the cat and mouse can make from each position removes the\nneed to check if each move is valid (on the grid and not on a wall) within the helper function.\n\n<br>\n\n```python\ndef canMouseWin(self, grid: List[str], cj: int, mj: int) -> bool:\n\n\tdef get_moves(m):\n\t\t"""Builds a map of locations cat/mouse can move to from any given (i,j)."""\n\t\tmoves = collections.defaultdict(set)\n\t\tfor i in range(R):\n\t\t\tfor j in range(C):\n\t\t\t\tif grid[i][j] != \'#\':\n\t\t\t\t\tv = {(i,j)}\n\t\t\t\t\tfor dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n\t\t\t\t\t\tfor s in range(1, m+1):\n\t\t\t\t\t\t\tr, c = i + s*dy, j + s*dx\n\t\t\t\t\t\t\tif not (0 <= r < R and 0 <= c < C and grid[r][c] != \'#\'):\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tv.add((r,c))\n\t\t\t\t\tmoves[(i,j)] = v\n\t\treturn moves\n\n\tdef get_locations():\n\t\t"""Returns the starting locations of the Mouse, Cat, and Food."""\n\t\tstart = dict()\n\t\tfor (i, j) in mouse_moves:\n\t\t\tif grid[i][j] in (\'M\',\'C\',\'F\'):\n\t\t\t\tstart[grid[i][j]] = (i, j)\n\t\treturn start[\'M\'], start[\'C\'], start[\'F\']\n\n\[email protected]_cache(None)\n\tdef helper(turn, cat, mouse):\n\t\t"""Returns True if mouse wins and False if cat wins."""\n\t\t# cat\'s turn\n\t\tif turn & 1:\n\t\t\tif (turn == 1) or {food, mouse} & cat_moves[cat]:\n\t\t\t\treturn False\n\t\t\treturn not any(not helper(turn-1, c, mouse) for c in cat_moves[cat])\n\n\t\t# mouse\'s turn\n\t\tif food in mouse_moves[mouse]:\n\t\t\treturn True\n\t\treturn any(helper(turn-1, cat, m) for m in mouse_moves[mouse])\n\n\tR, C = len(grid), len(grid[0])\n\tcat_moves = get_moves(cj)\n\tmouse_moves = get_moves(mj)\n\tmouse, cat, food = get_locations()\n\n\treturn helper(2*R*C, cat, mouse)\n``` | 3 | A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food.
* Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse).
* Floors are represented by the character `'.'` and can be walked on.
* Walls are represented by the character `'#'` and cannot be walked on.
* Food is represented by the character `'F'` and can be walked on.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
Mouse and Cat play according to the following rules:
* Mouse **moves first**, then they take turns to move.
* During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`.
* `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.
* Staying in the same position is allowed.
* Mouse can jump over Cat.
The game can end in 4 ways:
* If Cat occupies the same position as Mouse, Cat wins.
* If Cat reaches the food first, Cat wins.
* If Mouse reaches the food first, Mouse wins.
* If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`.
**Example 1:**
**Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2
**Output:** true
**Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
**Example 2:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4
**Output:** true
**Example 3:**
**Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3
**Output:** false
**Constraints:**
* `rows == grid.length`
* `cols = grid[i].length`
* `1 <= rows, cols <= 8`
* `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`.
* There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`.
* `1 <= catJump, mouseJump <= 8` | Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value. |
[Python] Top Down DP | cat-and-mouse-ii | 0 | 1 | **Approach:**\n\n1. For every space that is not a wall, find which spaces the cat and mouse can jump to from this space. (```cat_moves``` and ```mouse_moves```)\n\n2. Find the starting locations of the cat, the mouse, and the food. (```cat```, ```mouse```, and ```food```)\n\n3. Take an Alice and Bob style game approach to determine if there is a guaranteed path to victory for the mouse. <br>\nThe exit conditions are:\n**i.** if the mouse reaches the food return True\n**ii.** if the game runs out of turns or the cat reaches the food or the mouse return False<br>\nIf none of the exit conditions have been met:\n**i.** and it is the cat\'s turn, try all possible cat moves, if any choice results in the mouse losing, return False\n**ii.** and it is the mouse\'s turn, try all possible mouse moves, if any choice results in the mouse winning, return True\n\n**Optimizations:**\n\n1. The board is rather small (8 by 8 at most) so the outcome of any game that \ngoes on for 1,000 moves can definitely be resolved in fewer moves. By trial and\nerror 2·R·C is a satisfactory bound for the maximum number of turns.\n*Note: since the cat moves on odd turns, it is important that this number is even.*\n\n2. Caching the possible moves the cat and mouse can make from each position removes the\nneed to check if each move is valid (on the grid and not on a wall) within the helper function.\n\n<br>\n\n```python\ndef canMouseWin(self, grid: List[str], cj: int, mj: int) -> bool:\n\n\tdef get_moves(m):\n\t\t"""Builds a map of locations cat/mouse can move to from any given (i,j)."""\n\t\tmoves = collections.defaultdict(set)\n\t\tfor i in range(R):\n\t\t\tfor j in range(C):\n\t\t\t\tif grid[i][j] != \'#\':\n\t\t\t\t\tv = {(i,j)}\n\t\t\t\t\tfor dy, dx in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n\t\t\t\t\t\tfor s in range(1, m+1):\n\t\t\t\t\t\t\tr, c = i + s*dy, j + s*dx\n\t\t\t\t\t\t\tif not (0 <= r < R and 0 <= c < C and grid[r][c] != \'#\'):\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tv.add((r,c))\n\t\t\t\t\tmoves[(i,j)] = v\n\t\treturn moves\n\n\tdef get_locations():\n\t\t"""Returns the starting locations of the Mouse, Cat, and Food."""\n\t\tstart = dict()\n\t\tfor (i, j) in mouse_moves:\n\t\t\tif grid[i][j] in (\'M\',\'C\',\'F\'):\n\t\t\t\tstart[grid[i][j]] = (i, j)\n\t\treturn start[\'M\'], start[\'C\'], start[\'F\']\n\n\[email protected]_cache(None)\n\tdef helper(turn, cat, mouse):\n\t\t"""Returns True if mouse wins and False if cat wins."""\n\t\t# cat\'s turn\n\t\tif turn & 1:\n\t\t\tif (turn == 1) or {food, mouse} & cat_moves[cat]:\n\t\t\t\treturn False\n\t\t\treturn not any(not helper(turn-1, c, mouse) for c in cat_moves[cat])\n\n\t\t# mouse\'s turn\n\t\tif food in mouse_moves[mouse]:\n\t\t\treturn True\n\t\treturn any(helper(turn-1, cat, m) for m in mouse_moves[mouse])\n\n\tR, C = len(grid), len(grid[0])\n\tcat_moves = get_moves(cj)\n\tmouse_moves = get_moves(mj)\n\tmouse, cat, food = get_locations()\n\n\treturn helper(2*R*C, cat, mouse)\n``` | 3 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. |
Modern Pandas [Method Chaining] β
| the-number-of-employees-which-report-to-each-employee | 0 | 1 | # Code\n\n```python\nimport pandas as pd\n\ndef count_employees(employees: pd.DataFrame) -> pd.DataFrame:\n return (\n employees\n .groupby("reports_to", as_index=False)\n .aggregate(\n reports_count=pd.NamedAgg("employee_id", "nunique"),\n average_age = pd.NamedAgg("age", "mean"),\n )\n .apply(lambda x: round(x + 1e-10))\n .rename(columns={"reports_to": "employee_id"})\n .merge(employees[["employee_id", "name"]])\n [["employee_id", "name", "reports_count", "average_age"]]\n )\n``` | 0 | You are given two **0-indexed** integer arrays `servers` and `tasks` of lengths `n`ββββββ and `m`ββββββ respectively. `servers[i]` is the **weight** of the `iββββββth`ββββ server, and `tasks[j]` is the **time needed** to process the `jββββββth`ββββ task **in seconds**.
Tasks are assigned to the servers using a **task queue**. Initially, all servers are free, and the queue is **empty**.
At second `j`, the `jth` task is **inserted** into the queue (starting with the `0th` task being inserted at second `0`). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the **smallest weight**, and in case of a tie, it is assigned to a free server with the **smallest index**.
If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned **in order of insertion** following the weight and index priorities above.
A server that is assigned task `j` at second `t` will be free again at second `t + tasks[j]`.
Build an array `ans`ββββ of length `m`, where `ans[j]` is the **index** of the server the `jββββββth` task will be assigned to.
Return _the array_ `ans`ββββ.
**Example 1:**
**Input:** servers = \[3,3,2\], tasks = \[1,2,3,2,1,2\]
**Output:** \[2,2,0,2,1,2\]
**Explanation:** Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 2 until second 1.
- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.
- At second 2, task 2 is added and processed using server 0 until second 5.
- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.
- At second 4, task 4 is added and processed using server 1 until second 5.
- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.
**Example 2:**
**Input:** servers = \[5,1,4,3,2\], tasks = \[2,1,2,4,5,2,1\]
**Output:** \[1,4,1,4,1,3,2\]
**Explanation:** Events in chronological order go as follows:
- At second 0, task 0 is added and processed using server 1 until second 2.
- At second 1, task 1 is added and processed using server 4 until second 2.
- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4.
- At second 3, task 3 is added and processed using server 4 until second 7.
- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9.
- At second 5, task 5 is added and processed using server 3 until second 7.
- At second 6, task 6 is added and processed using server 2 until second 7.
**Constraints:**
* `servers.length == n`
* `tasks.length == m`
* `1 <= n, m <= 2 * 105`
* `1 <= servers[i], tasks[j] <= 2 * 105` | null |
Easy to understand python solution | find-the-highest-altitude | 0 | 1 | # Approach\nTo solve this problem, we need to store the original element and move to the next element by adding the difference. Thus, cur_num stores the value from the list with heights. At each iteration we look at the maximum value.\n\n# Complexity\n- Time complexity:\nThe complexity of this algorithm is O(n) and it is executed in 28 ms\n\n- Space complexity:\n16.10MB\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n max_num = 0\n cur_num = 0\n\n for i in range(len(gain)):\n if max_num < cur_num + gain[i]:\n max_num = cur_num + gain[i]\n\n cur_num += gain[i] \n \n return max_num\n \n``` | 3 | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100` | The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n. |
Easy to understand python solution | find-the-highest-altitude | 0 | 1 | # Approach\nTo solve this problem, we need to store the original element and move to the next element by adding the difference. Thus, cur_num stores the value from the list with heights. At each iteration we look at the maximum value.\n\n# Complexity\n- Time complexity:\nThe complexity of this algorithm is O(n) and it is executed in 28 ms\n\n- Space complexity:\n16.10MB\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n max_num = 0\n cur_num = 0\n\n for i in range(len(gain)):\n if max_num < cur_num + gain[i]:\n max_num = cur_num + gain[i]\n\n cur_num += gain[i] \n \n return max_num\n \n``` | 3 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108` | Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array |
Detailed understandable beginner explanation | find-the-highest-altitude | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe given code is implementing a method largestAltitude in the Solution class. This method takes a list gain as input, which represents the altitude gain or loss at each point of a journey. The goal is to calculate the highest altitude reached during the journey.\n\nHere\'s how the code works:\n\nThe method initializes two variables, current and highest, to keep track of the current altitude and the highest altitude reached so far, respectively. Both are initially set to 0.\nUsing a for loop, the code iterates over each element x in the gain list.\nIn each iteration, the code updates the current altitude by adding the gain/loss value x to it. This is done by current += x.\nAfter updating the current altitude, the code compares it with the highest altitude using the max function. The max function returns the greater of the two values, assigning the result to highest. This ensures that highest always stores the maximum altitude reached during the journey.\nThe loop continues until all elements in the gain list are processed.\nFinally, the method returns the value of highest, which represents the highest altitude reached during the journey.\nIntuitively, the code calculates the cumulative altitude at each point of the journey by adding the gain/loss values one by one. It keeps track of the highest altitude reached so far and updates it whenever a new higher altitude is encountered\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n Add your time cohe time complexity of the code is O(n), where n is the length of the gain list. This is because the code iterates over each element in the list once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) since the code only uses a constant amount of additional space to store the current and highest altitudes, regardless of the input size.\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n current=0\n highest=0\n for x in gain:\n current+=x\n highest=max(current,highest)\n return highest\n``` | 1 | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100` | The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n. |
Detailed understandable beginner explanation | find-the-highest-altitude | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe given code is implementing a method largestAltitude in the Solution class. This method takes a list gain as input, which represents the altitude gain or loss at each point of a journey. The goal is to calculate the highest altitude reached during the journey.\n\nHere\'s how the code works:\n\nThe method initializes two variables, current and highest, to keep track of the current altitude and the highest altitude reached so far, respectively. Both are initially set to 0.\nUsing a for loop, the code iterates over each element x in the gain list.\nIn each iteration, the code updates the current altitude by adding the gain/loss value x to it. This is done by current += x.\nAfter updating the current altitude, the code compares it with the highest altitude using the max function. The max function returns the greater of the two values, assigning the result to highest. This ensures that highest always stores the maximum altitude reached during the journey.\nThe loop continues until all elements in the gain list are processed.\nFinally, the method returns the value of highest, which represents the highest altitude reached during the journey.\nIntuitively, the code calculates the cumulative altitude at each point of the journey by adding the gain/loss values one by one. It keeps track of the highest altitude reached so far and updates it whenever a new higher altitude is encountered\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n Add your time cohe time complexity of the code is O(n), where n is the length of the gain list. This is because the code iterates over each element in the list once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) since the code only uses a constant amount of additional space to store the current and highest altitudes, regardless of the input size.\n\n# Code\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n current=0\n highest=0\n for x in gain:\n current+=x\n highest=max(current,highest)\n return highest\n``` | 1 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108` | Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array |
Simple Solution in both Python and C++ languagesπ | find-the-highest-altitude | 0 | 1 | # Solution \n```Python3 []\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n highest_point = 0\n prev_altitude = 0\n for i in gain:\n prev_altitude += i\n highest_point = max(highest_point, prev_altitude)\n\n return highest_point\n```\n```C++ []\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int highest_point = 0;\n int prev_point = 0;\n for (int i = 0; i < gain.size(); i++){\n prev_point += gain.at(i);\n highest_point = max(highest_point, prev_point);\n\n }\n\n return highest_point;\n \n }\n};\n```\n\n\n | 1 | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100` | The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n. |
Simple Solution in both Python and C++ languagesπ | find-the-highest-altitude | 0 | 1 | # Solution \n```Python3 []\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n highest_point = 0\n prev_altitude = 0\n for i in gain:\n prev_altitude += i\n highest_point = max(highest_point, prev_altitude)\n\n return highest_point\n```\n```C++ []\nclass Solution {\npublic:\n int largestAltitude(vector<int>& gain) {\n int highest_point = 0;\n int prev_point = 0;\n for (int i = 0; i < gain.size(); i++){\n prev_point += gain.at(i);\n highest_point = max(highest_point, prev_point);\n\n }\n\n return highest_point;\n \n }\n};\n```\n\n\n | 1 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108` | Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array |
Python Very Easy Solution || O(n) || Java beats 100% || C# | find-the-highest-altitude | 1 | 1 | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\n1) Python\n\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n maxVal=0\n alt=0\n for i in gain:\n alt+=i\n maxVal=max(alt,maxVal)\n return maxVal\n```\n\n2) Java\n\n```\nclass Solution {\n public int largestAltitude(int[] gain) {\n int maxVal=0;\n int alt=0;\n for(int i=0;i<gain.length;i++){\n alt=alt+gain[i];\n if(alt>maxVal)\n maxVal=alt;\n }\n return maxVal;\n }\n}\n```\n\n3) C#\n\n```\npublic class Solution {\n public int LargestAltitude(int[] gain) {\n int maxVal=0;\n int alt=0;\n for(int i=0;i<gain.Length;i++){\n alt=alt+gain[i];\n if(alt>maxVal)\n maxVal=alt;\n }\n return maxVal;\n }\n}\n```\n\n***Please Upvote*** | 1 | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._
**Example 1:**
**Input:** gain = \[-5,1,5,0,-7\]
**Output:** 1
**Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1.
**Example 2:**
**Input:** gain = \[-4,-3,-2,-1,4,3,2\]
**Output:** 0
**Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0.
**Constraints:**
* `n == gain.length`
* `1 <= n <= 100`
* `-100 <= gain[i] <= 100` | The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n. |
Python Very Easy Solution || O(n) || Java beats 100% || C# | find-the-highest-altitude | 1 | 1 | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\n1) Python\n\n```\nclass Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n maxVal=0\n alt=0\n for i in gain:\n alt+=i\n maxVal=max(alt,maxVal)\n return maxVal\n```\n\n2) Java\n\n```\nclass Solution {\n public int largestAltitude(int[] gain) {\n int maxVal=0;\n int alt=0;\n for(int i=0;i<gain.length;i++){\n alt=alt+gain[i];\n if(alt>maxVal)\n maxVal=alt;\n }\n return maxVal;\n }\n}\n```\n\n3) C#\n\n```\npublic class Solution {\n public int LargestAltitude(int[] gain) {\n int maxVal=0;\n int alt=0;\n for(int i=0;i<gain.Length;i++){\n alt=alt+gain[i];\n if(alt>maxVal)\n maxVal=alt;\n }\n return maxVal;\n }\n}\n```\n\n***Please Upvote*** | 1 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108` | Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array |
Python 3 || 5 lines, w/ explanation and example || T/M: 75% / 67% | minimum-number-of-people-to-teach | 0 | 1 | Here\'s the plan:\n- Determine the group of users who do not have a common language with at least one friend.\n- Determine the most common language in that group.\n- Return the number in the group who do not speak that language.\n```\nclass Solution:\n def minimumTeachings(self, n, languages, friendships):\n # Example:\n l = list(map(set,languages)) # friendships = [[1,4],[1,2],[3,4],[2,3]]\n # languages = [[2] ,[1,3],[1,2],[1,3]]\n users = set(chain(*((i-1,j-1) for i,j in \n friendships if not l[i-1]&l[j-1]))) # users = {0,1,3} <- zero-indexed\n\n if not users: return 0\n\n ctr = Counter(chain(*[languages[i] for i in users])) # ctr = {1:2, 3:2, 2:1}\n \n return len(users) - max(ctr.values()) # return len({0,1,3}) - max(2,2,1) = 3 - 2 = 1\n```\n[https://leetcode.com/problems/minimum-number-of-people-to-teach/submissions/903176253/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).\n | 3 | On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer `n`, an array `languages`, and an array `friendships` where:
* There are `n` languages numbered `1` through `n`,
* `languages[i]` is the set of languages the `iββββββth`ββββ user knows, and
* `friendships[i] = [uββββββiβββ, vββββββi]` denotes a friendship between the users `uβββββββββββi`βββββ and `vi`.
You can choose **one** language and teach it to some users so that all friends can communicate with each other. Return _the_ _**minimum**_ _number of users you need to teach._
Note that friendships are not transitive, meaning if `x` is a friend of `y` and `y` is a friend of `z`, this doesn't guarantee that `x` is a friend of `z`.
**Example 1:**
**Input:** n = 2, languages = \[\[1\],\[2\],\[1,2\]\], friendships = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** 1
**Explanation:** You can either teach user 1 the second language or user 2 the first language.
**Example 2:**
**Input:** n = 3, languages = \[\[2\],\[1,3\],\[1,2\],\[3\]\], friendships = \[\[1,4\],\[1,2\],\[3,4\],\[2,3\]\]
**Output:** 2
**Explanation:** Teach the third language to users 1 and 3, yielding two users to teach.
**Constraints:**
* `2 <= n <= 500`
* `languages.length == m`
* `1 <= m <= 500`
* `1 <= languages[i].length <= n`
* `1 <= languages[i][j] <= n`
* `1 <= uββββββi < vββββββi <= languages.length`
* `1 <= friendships.length <= 500`
* All tuples `(uβββββi, vββββββi)` are unique
* `languages[i]` contains only unique values | Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, itβd be helpful to append the point list to itself after sorting. |
Python 3 || 5 lines, w/ explanation and example || T/M: 75% / 67% | minimum-number-of-people-to-teach | 0 | 1 | Here\'s the plan:\n- Determine the group of users who do not have a common language with at least one friend.\n- Determine the most common language in that group.\n- Return the number in the group who do not speak that language.\n```\nclass Solution:\n def minimumTeachings(self, n, languages, friendships):\n # Example:\n l = list(map(set,languages)) # friendships = [[1,4],[1,2],[3,4],[2,3]]\n # languages = [[2] ,[1,3],[1,2],[1,3]]\n users = set(chain(*((i-1,j-1) for i,j in \n friendships if not l[i-1]&l[j-1]))) # users = {0,1,3} <- zero-indexed\n\n if not users: return 0\n\n ctr = Counter(chain(*[languages[i] for i in users])) # ctr = {1:2, 3:2, 2:1}\n \n return len(users) - max(ctr.values()) # return len({0,1,3}) - max(2,2,1) = 3 - 2 = 1\n```\n[https://leetcode.com/problems/minimum-number-of-people-to-teach/submissions/903176253/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).\n | 3 | You are given `n`ββββββ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `iββββββth`ββββ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109` | You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once |
Python, 3 steps | minimum-number-of-people-to-teach | 0 | 1 | First, find those who can\'t communicate with each other.\nThen, find the most popular language among them.\nThen teach that language to the minority who doesn\'t speak it: \n```\ndef minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n\tlanguages = [set(l) for l in languages]\n\n\tdontspeak = set()\n\tfor u, v in friendships:\n\t\tu = u-1\n\t\tv = v-1\n\t\tif languages[u] & languages[v]: continue\n\t\tdontspeak.add(u)\n\t\tdontspeak.add(v)\n\n\tlangcount = Counter()\n\tfor f in dontspeak:\n\t\tfor l in languages[f]:\n\t\t\tlangcount[l] += 1\n\n\treturn 0 if not dontspeak else len(dontspeak) - max(list(langcount.values()))\n``` | 93 | On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer `n`, an array `languages`, and an array `friendships` where:
* There are `n` languages numbered `1` through `n`,
* `languages[i]` is the set of languages the `iββββββth`ββββ user knows, and
* `friendships[i] = [uββββββiβββ, vββββββi]` denotes a friendship between the users `uβββββββββββi`βββββ and `vi`.
You can choose **one** language and teach it to some users so that all friends can communicate with each other. Return _the_ _**minimum**_ _number of users you need to teach._
Note that friendships are not transitive, meaning if `x` is a friend of `y` and `y` is a friend of `z`, this doesn't guarantee that `x` is a friend of `z`.
**Example 1:**
**Input:** n = 2, languages = \[\[1\],\[2\],\[1,2\]\], friendships = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** 1
**Explanation:** You can either teach user 1 the second language or user 2 the first language.
**Example 2:**
**Input:** n = 3, languages = \[\[2\],\[1,3\],\[1,2\],\[3\]\], friendships = \[\[1,4\],\[1,2\],\[3,4\],\[2,3\]\]
**Output:** 2
**Explanation:** Teach the third language to users 1 and 3, yielding two users to teach.
**Constraints:**
* `2 <= n <= 500`
* `languages.length == m`
* `1 <= m <= 500`
* `1 <= languages[i].length <= n`
* `1 <= languages[i][j] <= n`
* `1 <= uββββββi < vββββββi <= languages.length`
* `1 <= friendships.length <= 500`
* All tuples `(uβββββi, vββββββi)` are unique
* `languages[i]` contains only unique values | Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, itβd be helpful to append the point list to itself after sorting. |
Python, 3 steps | minimum-number-of-people-to-teach | 0 | 1 | First, find those who can\'t communicate with each other.\nThen, find the most popular language among them.\nThen teach that language to the minority who doesn\'t speak it: \n```\ndef minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n\tlanguages = [set(l) for l in languages]\n\n\tdontspeak = set()\n\tfor u, v in friendships:\n\t\tu = u-1\n\t\tv = v-1\n\t\tif languages[u] & languages[v]: continue\n\t\tdontspeak.add(u)\n\t\tdontspeak.add(v)\n\n\tlangcount = Counter()\n\tfor f in dontspeak:\n\t\tfor l in languages[f]:\n\t\t\tlangcount[l] += 1\n\n\treturn 0 if not dontspeak else len(dontspeak) - max(list(langcount.values()))\n``` | 93 | You are given `n`ββββββ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `iββββββth`ββββ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109` | You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once |
Python3 solution: logic + brute force | minimum-number-of-people-to-teach | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst intuition was graph, because the problem was framed like a graph problem\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince constraints are rather small, brute force trial and error would suffice\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n * friendships.length)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n + friendships.length)$$\n# Code\n```\n#\n# @lc app=leetcode id=1733 lang=python3\n#\n# [1733] Minimum Number of People to Teach\n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n \'\'\'\n Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn\'t guarantee that x is a friend of z. This means graph is not appropriate. Instead we should consider between each pair of friend, which language does not intersect. The language which got the most vote is the optimal answer \n \'\'\'\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n lang = [set(l) for l in languages]\n frds = [f for f in friendships if len(lang[f[0] - 1].intersection(lang[f[1] - 1])) == 0]\n result = float(\'inf\')\n for i in range(1, n + 1):\n teach = set()\n for u, v in frds:\n if i not in lang[u - 1]:\n teach.add(u)\n if i not in lang[v - 1]:\n teach.add(v)\n result = min(result, len(teach)) \n return result \n# @lc code=end\n\n\n``` | 0 | On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer `n`, an array `languages`, and an array `friendships` where:
* There are `n` languages numbered `1` through `n`,
* `languages[i]` is the set of languages the `iββββββth`ββββ user knows, and
* `friendships[i] = [uββββββiβββ, vββββββi]` denotes a friendship between the users `uβββββββββββi`βββββ and `vi`.
You can choose **one** language and teach it to some users so that all friends can communicate with each other. Return _the_ _**minimum**_ _number of users you need to teach._
Note that friendships are not transitive, meaning if `x` is a friend of `y` and `y` is a friend of `z`, this doesn't guarantee that `x` is a friend of `z`.
**Example 1:**
**Input:** n = 2, languages = \[\[1\],\[2\],\[1,2\]\], friendships = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** 1
**Explanation:** You can either teach user 1 the second language or user 2 the first language.
**Example 2:**
**Input:** n = 3, languages = \[\[2\],\[1,3\],\[1,2\],\[3\]\], friendships = \[\[1,4\],\[1,2\],\[3,4\],\[2,3\]\]
**Output:** 2
**Explanation:** Teach the third language to users 1 and 3, yielding two users to teach.
**Constraints:**
* `2 <= n <= 500`
* `languages.length == m`
* `1 <= m <= 500`
* `1 <= languages[i].length <= n`
* `1 <= languages[i][j] <= n`
* `1 <= uββββββi < vββββββi <= languages.length`
* `1 <= friendships.length <= 500`
* All tuples `(uβββββi, vββββββi)` are unique
* `languages[i]` contains only unique values | Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, itβd be helpful to append the point list to itself after sorting. |
Python3 solution: logic + brute force | minimum-number-of-people-to-teach | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst intuition was graph, because the problem was framed like a graph problem\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince constraints are rather small, brute force trial and error would suffice\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n * friendships.length)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n + friendships.length)$$\n# Code\n```\n#\n# @lc app=leetcode id=1733 lang=python3\n#\n# [1733] Minimum Number of People to Teach\n#\n\n# @lc code=start\nfrom typing import List\n\n\nclass Solution:\n \'\'\'\n Note that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn\'t guarantee that x is a friend of z. This means graph is not appropriate. Instead we should consider between each pair of friend, which language does not intersect. The language which got the most vote is the optimal answer \n \'\'\'\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n lang = [set(l) for l in languages]\n frds = [f for f in friendships if len(lang[f[0] - 1].intersection(lang[f[1] - 1])) == 0]\n result = float(\'inf\')\n for i in range(1, n + 1):\n teach = set()\n for u, v in frds:\n if i not in lang[u - 1]:\n teach.add(u)\n if i not in lang[v - 1]:\n teach.add(v)\n result = min(result, len(teach)) \n return result \n# @lc code=end\n\n\n``` | 0 | You are given `n`ββββββ tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `iββββββth`ββββ task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109` | You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once |
clean commented code | minimum-number-of-people-to-teach | 0 | 1 | the question is tricky to understand but easy to implement when you overcome that intial hurdle. \n\n```\nclass Solution:\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n # modify languages to be a set for quick intersection \n languages = {person+1: set(language) for person, language in enumerate(languages)} \n\n # create a set of people with a language barrier between a friend\n barrier = set() \n for u, v in friendships:\n if not languages[u] & languages[v]:\n barrier.add(u)\n barrier.add(v)\n\n # count the spoken languages between people with barriers \n spoken = Counter()\n for person in barrier:\n spoken += Counter(languages[person])\n\n # teach the most common language to those who don\'t know it\n return len(barrier) - max(spoken.values(), default=0)\n\n``` | 0 | On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer `n`, an array `languages`, and an array `friendships` where:
* There are `n` languages numbered `1` through `n`,
* `languages[i]` is the set of languages the `iββββββth`ββββ user knows, and
* `friendships[i] = [uββββββiβββ, vββββββi]` denotes a friendship between the users `uβββββββββββi`βββββ and `vi`.
You can choose **one** language and teach it to some users so that all friends can communicate with each other. Return _the_ _**minimum**_ _number of users you need to teach._
Note that friendships are not transitive, meaning if `x` is a friend of `y` and `y` is a friend of `z`, this doesn't guarantee that `x` is a friend of `z`.
**Example 1:**
**Input:** n = 2, languages = \[\[1\],\[2\],\[1,2\]\], friendships = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** 1
**Explanation:** You can either teach user 1 the second language or user 2 the first language.
**Example 2:**
**Input:** n = 3, languages = \[\[2\],\[1,3\],\[1,2\],\[3\]\], friendships = \[\[1,4\],\[1,2\],\[3,4\],\[2,3\]\]
**Output:** 2
**Explanation:** Teach the third language to users 1 and 3, yielding two users to teach.
**Constraints:**
* `2 <= n <= 500`
* `languages.length == m`
* `1 <= m <= 500`
* `1 <= languages[i].length <= n`
* `1 <= languages[i][j] <= n`
* `1 <= uββββββi < vββββββi <= languages.length`
* `1 <= friendships.length <= 500`
* All tuples `(uβββββi, vββββββi)` are unique
* `languages[i]` contains only unique values | Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, itβd be helpful to append the point list to itself after sorting. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.