title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Python 3 || DFS | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach taken is to use a stack to perform an iterative depth-first search (DFS) of the binary trees. The stack initially contains a tuple of the root nodes of both the original and cloned trees. The while loop runs as long as there are tuples in the stack, and for each tuple that is popped off the stack, the corresponding nodes in the original and cloned trees are compared to the target node. If the original node matches the target, then the corresponding node in the cloned tree is returned. Otherwise, if the original node has left and/or right children, then tuples of the corresponding nodes are added to the stack.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n stack = [(original, cloned)]\n \n while stack:\n node1, node2 = stack.pop()\n \n if node1 == target:\n return node2\n \n if node1.left:\n stack.append((node1.left, node2.left))\n \n if node1.right:\n stack.append((node1.right, node2.right))\n \n return None\n\n``` | 5 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree.
**Example 1:**
**Input:** tree = \[7,4,3,null,null,6,19\], target = 3
**Output:** 3
**Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
**Example 2:**
**Input:** tree = \[7\], target = 7
**Output:** 7
**Example 3:**
**Input:** tree = \[8,null,6,null,5,null,4,null,3,null,2,null,1\], target = 4
**Output:** 4
**Constraints:**
* The number of nodes in the `tree` is in the range `[1, 104]`.
* The values of the nodes of the `tree` are unique.
* `target` node is a node from the `original` tree and is not `null`.
**Follow up:** Could you solve the problem if repeated values on the tree are allowed? | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Python 3 || DFS | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach taken is to use a stack to perform an iterative depth-first search (DFS) of the binary trees. The stack initially contains a tuple of the root nodes of both the original and cloned trees. The while loop runs as long as there are tuples in the stack, and for each tuple that is popped off the stack, the corresponding nodes in the original and cloned trees are compared to the target node. If the original node matches the target, then the corresponding node in the cloned tree is returned. Otherwise, if the original node has left and/or right children, then tuples of the corresponding nodes are added to the stack.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n stack = [(original, cloned)]\n \n while stack:\n node1, node2 = stack.pop()\n \n if node1 == target:\n return node2\n \n if node1.left:\n stack.append((node1.left, node2.left))\n \n if node1.right:\n stack.append((node1.right, node2.right))\n \n return None\n\n``` | 5 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
Using Recursion || Find a corresponding node of a binary tree in a clone of that tree | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-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\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n if not original or target==original:\n return cloned\n return self.getTargetCopy(original.left,cloned.left,target) or self.getTargetCopy(original.right,cloned.right,target)\n``` | 2 | Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.
The `cloned` tree is a **copy of** the `original` tree.
Return _a reference to the same node_ in the `cloned` tree.
**Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree.
**Example 1:**
**Input:** tree = \[7,4,3,null,null,6,19\], target = 3
**Output:** 3
**Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
**Example 2:**
**Input:** tree = \[7\], target = 7
**Output:** 7
**Example 3:**
**Input:** tree = \[8,null,6,null,5,null,4,null,3,null,2,null,1\], target = 4
**Output:** 4
**Constraints:**
* The number of nodes in the `tree` is in the range `[1, 104]`.
* The values of the nodes of the `tree` are unique.
* `target` node is a node from the `original` tree and is not `null`.
**Follow up:** Could you solve the problem if repeated values on the tree are allowed? | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Using Recursion || Find a corresponding node of a binary tree in a clone of that tree | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-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\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n if not original or target==original:\n return cloned\n return self.getTargetCopy(original.left,cloned.left,target) or self.getTargetCopy(original.right,cloned.right,target)\n``` | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
python3 solution using memory or hashset beats 100% | lucky-numbers-in-a-matrix | 0 | 1 | # stats\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe can use memory by using 2 array to store max and min of eac row and column and if an element occurs in both then it is appended to answer\nreturning answer does the job\n\n# Complexity\nN being max of number of elements in row or column\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N) \n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n m,n=len(matrix),len(matrix[0])\n lr=[min(i) for i in matrix]\n lc=[]\n ans=[]\n for i in range(n):\n c=[k[i] for k in matrix]\n lc.append(max(c))\n for i in lr:\n if i in lc:ans.append(i)\n return ans\n``` | 4 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
python3 solution using memory or hashset beats 100% | lucky-numbers-in-a-matrix | 0 | 1 | # stats\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe can use memory by using 2 array to store max and min of eac row and column and if an element occurs in both then it is appended to answer\nreturning answer does the job\n\n# Complexity\nN being max of number of elements in row or column\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N) \n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n m,n=len(matrix),len(matrix[0])\n lr=[min(i) for i in matrix]\n lc=[]\n ans=[]\n for i in range(n):\n c=[k[i] for k in matrix]\n lc.append(max(c))\n for i in lr:\n if i in lc:ans.append(i)\n return ans\n``` | 4 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python 3 -- Easy solution -- Beats 97.29% | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n minrow = {min(r) for r in matrix}\n maxcol = {max(c) for c in zip(*matrix)} # zip(*) \u5BF9\u77E9\u9635\u8FDB\u884C\u8F6C\u7F6E\uFF0C\u5373\u627E\u51FA\u6BCF\u4E00\u5217\u4E2D\u7684\u6700\u5927\u503C\n return list(minrow & maxcol)\n\n``` | 49 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Python 3 -- Easy solution -- Beats 97.29% | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n minrow = {min(r) for r in matrix}\n maxcol = {max(c) for c in zip(*matrix)} # zip(*) \u5BF9\u77E9\u9635\u8FDB\u884C\u8F6C\u7F6E\uFF0C\u5373\u627E\u51FA\u6BCF\u4E00\u5217\u4E2D\u7684\u6700\u5927\u503C\n return list(minrow & maxcol)\n\n``` | 49 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Simple Python solution with explanations - 3 lines of code | lucky-numbers-in-a-matrix | 0 | 1 | `Intuition\n\nSetup 2 lists: minimum on rows and maximum on columns, then check the values that are common in both lists`\n\n```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n mins = [min(i) for i in matrix]\n maxs = [max(i) for i in zip(*matrix)]\n return list(set(maxs) & set(mins))\n``` | 1 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Simple Python solution with explanations - 3 lines of code | lucky-numbers-in-a-matrix | 0 | 1 | `Intuition\n\nSetup 2 lists: minimum on rows and maximum on columns, then check the values that are common in both lists`\n\n```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n mins = [min(i) for i in matrix]\n maxs = [max(i) for i in zip(*matrix)]\n return list(set(maxs) & set(mins))\n``` | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python || 99.43% Faster || Easy || Using Set | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n m,n=len(matrix),len(matrix[0])\n s=set()\n ans=[]\n for i in range(m):\n s.add(min(matrix[i]))\n for j in zip(*matrix):\n t=max(j)\n if t in s:\n ans.append(t)\n return ans\n``` | 2 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Python || 99.43% Faster || Easy || Using Set | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n m,n=len(matrix),len(matrix[0])\n s=set()\n ans=[]\n for i in range(m):\n s.add(min(matrix[i]))\n for j in zip(*matrix):\n t=max(j)\n if t in s:\n ans.append(t)\n return ans\n``` | 2 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python simple 90% solution | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, m: List[List[int]]) -> List[int]:\n min_r = [min(x) for x in m]\n max_c = []\n for i in range(len(m[0])):\n tmp = []\n for j in range(len(m)):\n tmp.append(m[j][i])\n max_c.append(max(tmp))\n return set(min_r)&set(max_c)\n``` | 1 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Python simple 90% solution | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, m: List[List[int]]) -> List[int]:\n min_r = [min(x) for x in m]\n max_c = []\n for i in range(len(m[0])):\n tmp = []\n for j in range(len(m)):\n tmp.append(m[j][i])\n max_c.append(max(tmp))\n return set(min_r)&set(max_c)\n``` | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python3 90.79% 125ms One-liner | lucky-numbers-in-a-matrix | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n a = []\n for i in zip(*matrix):\n if max(i) is min(matrix[i.index(max(i))]):\n a.append(max(i))\n return a\n \n # Oneliner\n return [max(i) for i in zip(*matrix) if max(i) is min(matrix[i.index(max(i))])]\n``` | 2 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Python3 90.79% 125ms One-liner | lucky-numbers-in-a-matrix | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n a = []\n for i in zip(*matrix):\n if max(i) is min(matrix[i.index(max(i))]):\n a.append(max(i))\n return a\n \n # Oneliner\n return [max(i) for i in zip(*matrix) if max(i) is min(matrix[i.index(max(i))])]\n``` | 2 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python Easy Solution | Simple Approach ✔ | lucky-numbers-in-a-matrix | 0 | 1 | \tclass Solution:\n\t\tdef luckyNumbers(self, mat: List[List[int]]) -> List[int]:\n\t\t\treturn list({min(row) for row in mat} & {max(col) for col in zip(*mat)})\nIf you have any questions, please ask me, and if you like this approach, please **vote it up**!\n | 5 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Python Easy Solution | Simple Approach ✔ | lucky-numbers-in-a-matrix | 0 | 1 | \tclass Solution:\n\t\tdef luckyNumbers(self, mat: List[List[int]]) -> List[int]:\n\t\t\treturn list({min(row) for row in mat} & {max(col) for col in zip(*mat)})\nIf you have any questions, please ask me, and if you like this approach, please **vote it up**!\n | 5 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
easy Python code | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n m,n = [],[]\n output = []\n for i in matrix:\n m.append(min(i))\n for i in range(len(matrix[0])):\n c = []\n for j in range(len(matrix)):\n c.append(matrix[j][i])\n n.append(max(c))\n for i in m:\n if i in n:\n output.append(i)\n return output\n```\nif this helped, plz consider **upvote** | 9 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:** \[15\]
**Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 2:**
**Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\]
**Output:** \[12\]
**Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Example 3:**
**Input:** matrix = \[\[7,8\],\[1,2\]\]
**Output:** \[7\]
**Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= n, m <= 50`
* `1 <= matrix[i][j] <= 105`.
* All elements in the matrix are distinct. | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
easy Python code | lucky-numbers-in-a-matrix | 0 | 1 | ```\nclass Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n m,n = [],[]\n output = []\n for i in matrix:\n m.append(min(i))\n for i in range(len(matrix[0])):\n c = []\n for j in range(len(matrix)):\n c.append(matrix[j][i])\n n.append(max(c))\n for i in m:\n if i in n:\n output.append(i)\n return output\n```\nif this helped, plz consider **upvote** | 9 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Implementing a Custom Stack by using Stack DS | design-a-stack-with-increment-operation | 0 | 1 | # Intuition\nThe problem description is quite simple and requires implementing a **Stack DS** (data structure), that follows LIFO-schema.\n\n# Approach\n1. inside `__init__` method store `maxSize` and `stack`\n2. implement `push` and `pop` methods as regular stack methods\n3. implement `increment` method, that increments in the range of `k` at each step current value by `val` \n\n# Complexity\n- Time complexity: **O(n)** because of iterating inside `increment`\n\n- Space complexity: **O(k)** because of storing **exactly** `k`- elements\n\n# Code\n```\nclass CustomStack:\n\n def __init__(self, maxSize: int):\n self.maxSize = maxSize\n self.stack = [] \n\n def push(self, x: int) -> None:\n if len(self.stack) < self.maxSize:\n self.stack.append(x)\n\n def pop(self) -> int:\n return self.stack.pop() if self.stack else -1\n\n def increment(self, k: int, val: int) -> None:\n j = min(k, len(self.stack))\n\n for i in range(j):\n self.stack[i] += val\n\n# Your CustomStack object will be instantiated and called as such:\n# obj = CustomStack(maxSize)\n# obj.push(x)\n# param_2 = obj.pop()\n# obj.increment(k,val)\n``` | 1 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `maxSize`.
* `int pop()` Pops and returns the top of the stack or `-1` if the stack is empty.
* `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, increment all the elements in the stack.
**Example 1:**
**Input**
\[ "CustomStack ", "push ", "push ", "pop ", "push ", "push ", "push ", "increment ", "increment ", "pop ", "pop ", "pop ", "pop "\]
\[\[3\],\[1\],\[2\],\[\],\[2\],\[3\],\[4\],\[5,100\],\[2,100\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,2,null,null,null,null,null,103,202,201,-1\]
**Explanation**
CustomStack stk = new CustomStack(3); // Stack is Empty \[\]
stk.push(1); // stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.pop(); // return 2 --> Return top of the stack 2, stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.push(3); // stack becomes \[1, 2, 3\]
stk.push(4); // stack still \[1, 2, 3\], Do not add another elements as size is 4
stk.increment(5, 100); // stack becomes \[101, 102, 103\]
stk.increment(2, 100); // stack becomes \[201, 202, 103\]
stk.pop(); // return 103 --> Return top of the stack 103, stack becomes \[201, 202\]
stk.pop(); // return 202 --> Return top of the stack 202, stack becomes \[201\]
stk.pop(); // return 201 --> Return top of the stack 201, stack becomes \[\]
stk.pop(); // return -1 --> Stack is empty return -1.
**Constraints:**
* `1 <= maxSize, x, k <= 1000`
* `0 <= val <= 100`
* At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately. | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
Stack with top and maxSize | design-a-stack-with-increment-operation | 0 | 1 | # Upvote it :)\n```\nclass CustomStack:\n\n def __init__(self, maxSize: int):\n self.arr = []\n self.m = maxSize\n self.top = -1\n\n def push(self, x: int) -> None:\n if self.top < self.m - 1:\n self.arr.append(x)\n self.top += 1\n\n def pop(self) -> int:\n if self.top == -1: return -1\n self.top -= 1\n return(self.arr.pop(-1))\n\n def increment(self, k: int, val: int) -> None:\n for i in range(min(k, self.top + 1)): self.arr[i] += val\n``` | 1 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `maxSize`.
* `int pop()` Pops and returns the top of the stack or `-1` if the stack is empty.
* `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, increment all the elements in the stack.
**Example 1:**
**Input**
\[ "CustomStack ", "push ", "push ", "pop ", "push ", "push ", "push ", "increment ", "increment ", "pop ", "pop ", "pop ", "pop "\]
\[\[3\],\[1\],\[2\],\[\],\[2\],\[3\],\[4\],\[5,100\],\[2,100\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,2,null,null,null,null,null,103,202,201,-1\]
**Explanation**
CustomStack stk = new CustomStack(3); // Stack is Empty \[\]
stk.push(1); // stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.pop(); // return 2 --> Return top of the stack 2, stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.push(3); // stack becomes \[1, 2, 3\]
stk.push(4); // stack still \[1, 2, 3\], Do not add another elements as size is 4
stk.increment(5, 100); // stack becomes \[101, 102, 103\]
stk.increment(2, 100); // stack becomes \[201, 202, 103\]
stk.pop(); // return 103 --> Return top of the stack 103, stack becomes \[201, 202\]
stk.pop(); // return 202 --> Return top of the stack 202, stack becomes \[201\]
stk.pop(); // return 201 --> Return top of the stack 201, stack becomes \[\]
stk.pop(); // return -1 --> Stack is empty return -1.
**Constraints:**
* `1 <= maxSize, x, k <= 1000`
* `0 <= val <= 100`
* At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately. | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
Python || 98.18% Faster || Easy || O(!) Solution | design-a-stack-with-increment-operation | 0 | 1 | ```\nclass CustomStack:\n\n def __init__(self, maxSize: int):\n self.stack=[]\n self.n=maxSize\n\n def push(self, x: int) -> None:\n if len(self.stack)<self.n:\n self.stack.append(x)\n\n def pop(self) -> int:\n if len(self.stack)==0:\n return -1\n return self.stack.pop()\n\n def increment(self, k: int, val: int) -> None:\n l=len(self.stack)\n for i in range(l):\n if i==k:\n break\n self.stack[i]+=val\n```\n**An upvote will be encouraging** | 2 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `maxSize`.
* `int pop()` Pops and returns the top of the stack or `-1` if the stack is empty.
* `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, increment all the elements in the stack.
**Example 1:**
**Input**
\[ "CustomStack ", "push ", "push ", "pop ", "push ", "push ", "push ", "increment ", "increment ", "pop ", "pop ", "pop ", "pop "\]
\[\[3\],\[1\],\[2\],\[\],\[2\],\[3\],\[4\],\[5,100\],\[2,100\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,2,null,null,null,null,null,103,202,201,-1\]
**Explanation**
CustomStack stk = new CustomStack(3); // Stack is Empty \[\]
stk.push(1); // stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.pop(); // return 2 --> Return top of the stack 2, stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.push(3); // stack becomes \[1, 2, 3\]
stk.push(4); // stack still \[1, 2, 3\], Do not add another elements as size is 4
stk.increment(5, 100); // stack becomes \[101, 102, 103\]
stk.increment(2, 100); // stack becomes \[201, 202, 103\]
stk.pop(); // return 103 --> Return top of the stack 103, stack becomes \[201, 202\]
stk.pop(); // return 202 --> Return top of the stack 202, stack becomes \[201\]
stk.pop(); // return 201 --> Return top of the stack 201, stack becomes \[\]
stk.pop(); // return -1 --> Stack is empty return -1.
**Constraints:**
* `1 <= maxSize, x, k <= 1000`
* `0 <= val <= 100`
* At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately. | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
python3 Solution | Stack | design-a-stack-with-increment-operation | 0 | 1 | ```\nclass CustomStack:\n\n def __init__(self, maxSize: int):\n self.stack = []\n self.maxLength = maxSize\n \n\n def push(self, x: int) -> None:\n if len(self.stack) < self.maxLength:\n self.stack.append(x)\n \n def pop(self) -> int:\n if len(self.stack) >0:\n return self.stack.pop()\n return -1\n \n def increment(self, k: int, val: int) -> None:\n n = min(k,len(self.stack))\n for i in range(n):\n self.stack[i] += val | 10 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `maxSize`.
* `int pop()` Pops and returns the top of the stack or `-1` if the stack is empty.
* `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, increment all the elements in the stack.
**Example 1:**
**Input**
\[ "CustomStack ", "push ", "push ", "pop ", "push ", "push ", "push ", "increment ", "increment ", "pop ", "pop ", "pop ", "pop "\]
\[\[3\],\[1\],\[2\],\[\],\[2\],\[3\],\[4\],\[5,100\],\[2,100\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,2,null,null,null,null,null,103,202,201,-1\]
**Explanation**
CustomStack stk = new CustomStack(3); // Stack is Empty \[\]
stk.push(1); // stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.pop(); // return 2 --> Return top of the stack 2, stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.push(3); // stack becomes \[1, 2, 3\]
stk.push(4); // stack still \[1, 2, 3\], Do not add another elements as size is 4
stk.increment(5, 100); // stack becomes \[101, 102, 103\]
stk.increment(2, 100); // stack becomes \[201, 202, 103\]
stk.pop(); // return 103 --> Return top of the stack 103, stack becomes \[201, 202\]
stk.pop(); // return 202 --> Return top of the stack 202, stack becomes \[201\]
stk.pop(); // return 201 --> Return top of the stack 201, stack becomes \[\]
stk.pop(); // return -1 --> Stack is empty return -1.
**Constraints:**
* `1 <= maxSize, x, k <= 1000`
* `0 <= val <= 100`
* At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately. | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
✅✅✅ very easy to understand solution with a details | design-a-stack-with-increment-operation | 0 | 1 | ### Intuition\n- First of all I think I need array and one varieble that equal max size. So I assigned `self.arr` equal empty and `self.max` inside `__init__ `function.\n\n### Approach\n- To solve this problem we only need to write a few lines.\n 1. Inside `push` function we need to append a new variable to our `self.arr` but we must check `length` of our array because we can capable to add `self.max` elements. So our `push` function can be this kind of:\n ```\n if len(self.arr)<self.max: self.arr.append(x)\n ```\n 2. Inside `pop` function we need to `pop` an element from the array and before doing that we need to know there is an element inside our array. Instead of checking there is an element in array we can simply use `try` and `except` function for this purpose. So our `pop` function can be this kind of:\n ```\n try: return self.arr.pop()\n except: return -1\n ```\n 3. Inside last `increment` function we need to increment `self.arr[0]` to `self.arr[k]` or `self.arr[-1]` because if length of arr id less thank k we need to stop our loop on the last element of the array. That means we need to identify `minimum` these two of them and then we need to use for loop to increment every single element that we need to increment. So our `increment` function can be this kind of:\n ```\n for i in range(min(k, len(self.arr))): self.arr[i]+=val\n ```\n### Code\n```\nclass CustomStack:\n\n def __init__(self, maxSize: int):\n self.arr = []\n self.max = maxSize\n\n def push(self, x: int) -> None:\n if len(self.arr)<self.max: self.arr.append(x)\n\n def pop(self) -> int:\n try: return self.arr.pop()\n except: return -1\n\n def increment(self, k: int, val: int) -> None:\n for i in range(min(k, len(self.arr))): self.arr[i]+=val\n```\n | 1 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `maxSize`.
* `int pop()` Pops and returns the top of the stack or `-1` if the stack is empty.
* `void inc(int k, int val)` Increments the bottom `k` elements of the stack by `val`. If there are less than `k` elements in the stack, increment all the elements in the stack.
**Example 1:**
**Input**
\[ "CustomStack ", "push ", "push ", "pop ", "push ", "push ", "push ", "increment ", "increment ", "pop ", "pop ", "pop ", "pop "\]
\[\[3\],\[1\],\[2\],\[\],\[2\],\[3\],\[4\],\[5,100\],\[2,100\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,null,null,2,null,null,null,null,null,103,202,201,-1\]
**Explanation**
CustomStack stk = new CustomStack(3); // Stack is Empty \[\]
stk.push(1); // stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.pop(); // return 2 --> Return top of the stack 2, stack becomes \[1\]
stk.push(2); // stack becomes \[1, 2\]
stk.push(3); // stack becomes \[1, 2, 3\]
stk.push(4); // stack still \[1, 2, 3\], Do not add another elements as size is 4
stk.increment(5, 100); // stack becomes \[101, 102, 103\]
stk.increment(2, 100); // stack becomes \[201, 202, 103\]
stk.pop(); // return 103 --> Return top of the stack 103, stack becomes \[201, 202\]
stk.pop(); // return 202 --> Return top of the stack 202, stack becomes \[201\]
stk.pop(); // return 201 --> Return top of the stack 201, stack becomes \[\]
stk.pop(); // return -1 --> Stack is empty return -1.
**Constraints:**
* `1 <= maxSize, x, k <= 1000`
* `0 <= val <= 100`
* At most `1000` calls will be made to each method of `increment`, `push` and `pop` each separately. | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
Very Simple Solution using Java & Python🔥 | balance-a-binary-search-tree | 1 | 1 | > # Algorithm \n- Traverse and find the inorder of the tree and store it in an ArrayList.\n- Now Similar to merge sort we mantain low, high pointers and mid will be the root element and the left part will be its left subtree and right part will be its right subtree. \n- We will be recursively travelling to the left and right parts of the ArrayList.\n- Finally we will return the root that if have got from the buildTree function.\n> ## *Look at the code for better understanding.* \n---\n# Java\n```\nclass Solution {\n public void inorderTraversal(TreeNode root,List<Integer> lst)\n {\n if(root!=null)\n {\n inorderTraversal(root.left,lst);\n lst.add(root.val);\n inorderTraversal(root.right,lst);\n }\n }\n public TreeNode buildTree(List<Integer> lst ,int low,int high)\n {\n if(low > high) return null;\n int mid = (low+high)/2;\n TreeNode root = new TreeNode(lst.get(mid));\n root.left = buildTree(lst,low,mid-1);\n root.right = buildTree(lst,mid+1,high);\n return root;\n }\n public TreeNode balanceBST(TreeNode root) {\n List<Integer> lst = new ArrayList<>();\n inorderTraversal(root,lst);\n root = buildTree(lst,0,lst.size()-1);\n return root;\n }\n}\n```\n---\n# Python\n```\nclass Solution:\n def inorder(self,root,lst):\n if root!=None:\n self.inorder(root.left,lst)\n lst.append(root.val)\n self.inorder(root.right,lst)\n def buildTree(self,lst,low,high):\n if low > high:\n return None\n mid = (low+high)//2\n root = TreeNode(lst[mid])\n root.left = self.buildTree(lst,low,mid-1)\n root.right = self.buildTree(lst,mid+1,high)\n return root\n\n def balanceBST(self, root: TreeNode) -> TreeNode:\n lst = []\n self.inorder(root,lst)\n low = 0\n high = len(lst)-1\n root = self.buildTree(lst,low,high)\n return root\n```\n---\n#### *Please don\'t forget to upvote if you\'ve liked my explanation.* \u2B06\uFE0F\n---\n | 8 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
Simple DFS solution | balance-a-binary-search-tree | 0 | 1 | ```\nclass Solution:\n\n def inorder_bts(self, root):\n if not root:\n return []\n return self.inorder_bts(root.left) + [root] + self.inorder_bts(root.right)\n \n def construct_bst(self, left, right, path):\n if left > right:\n return None\n middle = (left+right)//2\n path[middle].left = self.construct_bst(left, middle-1, path)\n path[middle].right = self.construct_bst(middle+1, right, path)\n return path[middle]\n \n def balanceBST(self, root: TreeNode) -> TreeNode:\n path = self.inorder_bts(root)\n return self.construct_bst(0, len(path)-1, path)\n``` | 1 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
Divide and Conquer || Simple solution in Python3 | balance-a-binary-search-tree | 0 | 1 | # Intuition\nThe problem description is the following:\n- given a **Binary Search Tree**\n- the goal is to make this tree `balanced`\n\n```py\n# Example\nnodes = TreeNode(0, None, TreeNode(1, None, TreeNode(2)))\n\n# The first step is to inorder traversal, to get all nodes\n# in sorted order \nnums = [0, 1, 2]\n\n# The next step is to recreate a tree,\n# there\'s a bunch of different approaches, like building \n# AVL-tree, but for the sake of brefity, we focus only\n# on Divide-and-Conquer.\n# The goal is to split a list at equal size parts by\n# defining a middle of an initial list\nnode = TreeNode(nums[1])\nnode.left = TreeNode(nums[0])\nnode.right = TreeNode(nums[2])\n\n# The thing is that the example above HARDCODED only for 3 nodes\n# in that list, thus we need to split a list and repeat\n# the procedure until we\'re out of nodes\n\n```\n\n# Approach\n1. initialize a `nums` variable to store the ordered numbers\n2. perform `inorder traversal` by implementing and calling `dfs` function\n3. create a `balance` function with `left` and `right` arguments as starting and ending index of `nums`\n4. if we\'re out of nodes `left > right`, return `None`\n5. find the `mid` by dividing a **sum** of pointers\n6. shift the pointers as if it was a **binary search** and store the result into `node.left` and `node.right` children\n7. return `node`\n\n# Complexity\n- Time complexity: **O(n)**, because of twice iterating over `root` and `nums`\n\n- Space complexity: **O(n)**, this requires for recursive stack calling.\n\n# Code\n```\nclass Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n nums = []\n\n def dfs(node):\n if not node:\n return \n\n dfs(node.left)\n nums.append(node.val)\n dfs(node.right)\n\n dfs(root)\n\n def balance(left = 0, right = len(nums) - 1):\n if left > right:\n return None\n\n mid = (left + right) // 2\n node = TreeNode(nums[mid])\n node.left = balance(left, mid - 1)\n node.right = balance(mid + 1, right)\n\n return node\n\n return balance() \n``` | 3 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
Simple Python solution with inorder traversal || beats 92% | balance-a-binary-search-tree | 0 | 1 | ```\nclass Solution:\n def __init__(self):\n self.arr = []\n def inOrder(self,root):\n if root is None:\n return []\n else:\n self.inOrder(root.left)\n self.arr.append(root.val)\n self.inOrder(root.right)\n return self.arr\n \n def balanced(self,left,right,nums):\n if left > right:\n return None\n else:\n mid = (left + right)//2\n root = TreeNode(nums[mid])\n root.left = self.balanced(left,mid-1,nums)\n root.right = self.balanced(mid+1,right,nums)\n return root\n def balanceBST(self, root: TreeNode) -> TreeNode:\n nums = self.inOrder(root)\n return self.balanced(0,len(nums)-1,nums)\n \n``` | 1 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
[Python 3] DFS (in-order) extraction & balanced tree-building | balance-a-binary-search-tree | 0 | 1 | # Steps\n1. We use DFS (in-order) to extract node values while preserving the order.\n2. We build the balanced tree by recursively taking the middle element of the ordered list as root.\n\n*Note: we use indices (`l:left`, `r:right`) instead of slicing to preserve space.*\n\n```Python\nclass Solution:\n def balanceBST(self, root):\n \n def dfs(node):\n if not node: return []\n return dfs(node.left) + [node.val] + dfs(node.right)\n ns = dfs(root)\n \n def build(l, r):\n if l > r: return None\n m = (l + r) // 2\n root = TreeNode(ns[m])\n root.left, root.right = build(l, m-1), build(m + 1, r)\n return root\n \n return build(0, len(ns) - 1)\n```\n | 30 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
✅ [Python] Simple, Clean approach, Easy | balance-a-binary-search-tree | 0 | 1 | #### Approach:\n- Sort the BST using In-Order\n- Construck BST using Sorted Array\n\n\n```\nclass Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n \n def inorder(root):\n if root is None: return []\n return inorder(root.left) + [root.val] + inorder(root.right)\n \n nums = inorder(root)\n \n def bst(l,r):\n if l>r: return None\n mid = (l+r)//2\n return TreeNode(nums[mid], bst(l,mid-1), bst(mid+1,r))\n \n return bst(0, len(nums)-1)\n```\n\nIf you think this post is **helpful** for you, hit a **thums up.** Any questions or discussions are welcome!\n\n | 0 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
Python sol by rebuilding. [w/ Hint] | balance-a-binary-search-tree | 0 | 1 | Python sol by rebuilding.\n\n---\n**Hint**:\n\nExcept for roration-based algorithm, like [this post](https://leetcode.com/problems/balance-a-binary-search-tree/discuss/541785/C%2B%2BJava-with-picture-DSW-O(n)orO(1)) by @votrubac.\n\nThere is another one feasible solution.\nWe can reuse the algorithm we had developed before in [Leetcode #108 Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/).\n\n---\n\nHere is the procedure:\n\n1. \nFlatten original BST into a ascending sorted sequence.\n( Recall that BST is a binary tree with ordered elements with inorder traversal )\n\n2. \nConvert asecnding sorted sequence into Balanced BST by the algorithm in Leetcode #108\n\n---\n\n**Implementation**:\n\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n \n nums = []\n \n def inorder( node,nums):\n \'\'\'\n Convert BST to ascending sequence\n \'\'\' \n if node:\n \n inorder( node.left, nums )\n nums.append( node.val )\n inorder( node.right, nums )\n \n # ----------------------------------------\n \n def sequence_to_balanced_BST( left, right, nums):\n \'\'\'\n Convert ascending sequence to balanced BST\n \'\'\'\n if left > right:\n # Base case:\n return None\n \n else:\n # General case:\n\n mid = left + ( right - left ) // 2\n\n root = TreeNode( nums[mid] )\n\n root.left = sequence_to_balanced_BST( left, mid-1, nums)\n root.right = sequence_to_balanced_BST( mid+1, right, nums)\n\n return root\n \n # ----------------------------------------\n\t\t\n # Flatten original BST into a ascending sorted sequence.\n inorder( root, nums )\n \n\t\t# Convert asecnding sorted sequence into Balanced BST by the algorithm in Leetcode #108\n return sequence_to_balanced_BST( left = 0, right = len(nums)-1, nums = nums)\n```\n\n---\n\nRelated leetcode challenge:\n\n[1] [Leetcode #94 Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal)\n\n[2] [Leetcode #108 Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | 19 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
Python: Clean Recursive Soln | Beats 60% soln | w/ Comments | Time & Space Complexity - O(n) | balance-a-binary-search-tree | 0 | 1 | # Solution:\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def inOrderTraversal(self, root):\n if not root:\n return \n \n\t\t# traverse left subtree\n\t\tself.inOrderTraversal(root.left)\n\t\t\n\t\t# append to list\n self.inOrderList.append(root)\n \n\t\t# traverse right subtree\n\t\tself.inOrderTraversal(root.right)\n \n return \n \n def createBBST(self,low, high):\n\t\t# base case\n if low > high:\n return None\n\n\t\t# pick middle node\n mid = low + high >> 1\n \n node = self.inOrderList[mid]\n node.left = self.createBBST(low, mid - 1)\n node.right = self.createBBST(mid + 1, high)\n \n return node\n \n \n def balanceBST(self, root: TreeNode) -> TreeNode:\n self.inOrderList = []\n self.inOrderTraversal(root)\n return self.createBBST(0, len(self.inOrderList)-1)\n```\t\t\n\t\t\n# Intuition/Approach:\n**Step 1:** Inorder traversal on a binary search tree gives us all the nodes in sorted ascending order.\n**Step 2:** To build a Balanced BST we would need a root with equal number of nodes to its left as to its right\n**Example:** input: [3, 1, 4, null, null, null, 7, null, 9, null, 10] (*doesn\'t really matter how the nodes are provided*)\n```\n\t\t3\n\t / \\\n \t 1 4\n\t \\\n\t\t\t 7\n\t\t\t \\\n\t\t\t 9\n\t\t\t\t\\\n\t\t\t \t 10\n\t\t\t\t \n# we perform inOrderTraversal on this BST, we get\n\ninOrderList = [1,3,4,7,9,10]\n\n# Now if we were to form a Balanced BST from this list, our choice of root will be either 4 or 7 \n#(partioning the list in such a way that left subtree is roughly equal to right subtree in size/# of nodes).\n\n# Say, it was 4: then\n#\t\tleft node of 4 will be decided from the left half of the list (from inOrderList[0:2])\n#\t\tand right node of 4 will be decided from the right half of the list (from inOrderList[3:])\n#\t\tand the process goes on recursively\n```\n\n\n\t\n\t\t | 3 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
Python easy to read and understand | inorder and recusion | balance-a-binary-search-tree | 0 | 1 | ```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def bst(self, nums, i, j):\n if i > j:\n return None\n mid = (i+j) // 2\n node = TreeNode(nums[mid])\n node.left = self.bst(nums, i, mid-1)\n node.right = self.bst(nums, mid+1, j)\n return node\n \n def dfs(self, node):\n if not node:\n return []\n l, r = self.dfs(node.left), self.dfs(node.right)\n return l + [node.val] + r\n \n def balanceBST(self, root: TreeNode) -> TreeNode:\n nums = self.dfs(root)\n return self.bst(nums, 0, len(nums)-1) | 8 | Given the `root` of a binary search tree, return _a **balanced** binary search tree with the same node values_. If there is more than one answer, return **any of them**.
A binary search tree is **balanced** if the depth of the two subtrees of every node never differs by more than `1`.
**Example 1:**
**Input:** root = \[1,null,2,null,3,null,4,null,null\]
**Output:** \[2,1,3,null,null,null,4\]
**Explanation:** This is not the only correct answer, \[3,1,4,null,2\] is also correct.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 105` | null |
nlogn time space O(n) | maximum-performance-of-a-team | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n eng = []\n for eff,spd in zip(efficiency,speed):\n eng.append([eff,spd])\n eng.sort(reverse = True)\n\n res,speed = 0,0\n minHeap = []\n\n for eff,spd in eng:\n if len(minHeap) == k:\n speed -= heapq.heappop(minHeap)\n\n speed += spd\n heapq.heappush(minHeap,spd)\n res = max(res,eff*speed)\n\n return res % (10 ** 9 + 7)\n``` | 1 | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. |
nlogn time space O(n) | maximum-performance-of-a-team | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n eng = []\n for eff,spd in zip(efficiency,speed):\n eng.append([eff,spd])\n eng.sort(reverse = True)\n\n res,speed = 0,0\n minHeap = []\n\n for eff,spd in eng:\n if len(minHeap) == k:\n speed -= heapq.heappop(minHeap)\n\n speed += spd\n heapq.heappush(minHeap,spd)\n res = max(res,eff*speed)\n\n return res % (10 ** 9 + 7)\n``` | 1 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
[Python3] Runtime: 387 ms, faster than 98.24% | Memory: 29.5 MB, less than 99.37% | maximum-performance-of-a-team | 0 | 1 | ```\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n \n cur_sum, h = 0, []\n ans = -float(\'inf\')\n \n for i, j in sorted(zip(efficiency, speed),reverse=True):\n while len(h) > k-1:\n cur_sum -= heappop(h)\n heappush(h, j)\n cur_sum += j\n ans = max(ans, cur_sum * i)\n \n return ans % (10**9+7)\n``` | 16 | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. |
[Python3] Runtime: 387 ms, faster than 98.24% | Memory: 29.5 MB, less than 99.37% | maximum-performance-of-a-team | 0 | 1 | ```\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n \n cur_sum, h = 0, []\n ans = -float(\'inf\')\n \n for i, j in sorted(zip(efficiency, speed),reverse=True):\n while len(h) > k-1:\n cur_sum -= heappop(h)\n heappush(h, j)\n cur_sum += j\n ans = max(ans, cur_sum * i)\n \n return ans % (10**9+7)\n``` | 16 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | maximum-performance-of-a-team | 0 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n**C++**\n\n```cpp\n// Time Complexity: O(N * (logN + logK)) \n// Space Complexity: O(N + K)\n// where N is the total number of candidates and K is the size of team\nclass Solution {\npublic:\n int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {\n int MOD = 1e9 + 7;\n vector<pair<int, int>> candidates(n);\n // we build the pair { efficiency, speed } so that we can sort it later\n for (int i = 0; i < n; i++) candidates[i] = { efficiency[i], speed[i] };\n // sort candidates in descending order\n sort(candidates.rbegin(), candidates.rend());\n // Using Example 1: \n // speed: [2, 10, 3, 1 ,5, 8] and efficiency: [5, 4, 3, 9, 7, 2]\n // after sort, it becomes\n // candidates: [{9, 1}, {7 ,5}, {5, 2}, {4, 10}, {3, 3}, {2, 8}]\n long speedSum = 0, ans = 0;\n // we use priority queue here with greater<int> to store the sum\n // i.e min heap (the smallest element goes on the top)\n priority_queue <int, vector<int>, greater<int>> pq;\n // iterate each pair\n for (auto& [e, s] : candidates) {\n // put the speed to priority queue\n pq.push(s);\n // add to speedSum\n speedSum += s;\n // we only need to choose at most k engineers\n // hence if the queue size is greater than k\n // we need to remove a candidate\n if (pq.size() > k) {\n // who to remove? of course the one with smallest speed\n speedSum -= pq.top();\n pq.pop();\n }\n // calculate the performance\n ans = max(ans, speedSum * e);\n }\n return ans % MOD;\n }\n};\n```\n\n**Python**\n\n```py\n# Time Complexity: O(N * (logN + logK)) \n# Space Complexity: O(N + K)\n# where N is the total number of candidates and K is the size of team\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n MOD = 10 ** 9 + 7\n # build tuples ( efficiency, speed ) so that we can sort it later\n candidates = zip(efficiency, speed)\n # default sort mode is ascending. use `reverse = True` to sort in descending\n candidates = sorted(candidates, key=lambda x: x[0], reverse=True)\n # Using Example 1: \n # speed: [2, 10, 3, 1 ,5, 8] and efficiency: [5, 4, 3, 9, 7, 2]\n # after sort, it becomes\n # candidates: [(9, 1), (7 ,5), (5, 2), (4, 10), (3, 3), (2, 8)]\n speedSum, ans = 0, 0\n # in python, it usually refers to heap \n heap = []\n # iterate each tuple\n for e, s in candidates:\n # put the speed to heap\n heapq.heappush(heap, s)\n # add to speedSum\n speedSum += s\n # we only need to choose at most k engineers\n # hence if the queue size is greater than k\n # we need to remove a candidate\n if len(heap) > k:\n # who to remove? of course the one with smallest speed\n speedSum -= heapq.heappop(heap)\n # calculate the performance\n ans = max(ans, speedSum * e)\n return ans % MOD\n``` | 116 | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | maximum-performance-of-a-team | 0 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n**C++**\n\n```cpp\n// Time Complexity: O(N * (logN + logK)) \n// Space Complexity: O(N + K)\n// where N is the total number of candidates and K is the size of team\nclass Solution {\npublic:\n int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {\n int MOD = 1e9 + 7;\n vector<pair<int, int>> candidates(n);\n // we build the pair { efficiency, speed } so that we can sort it later\n for (int i = 0; i < n; i++) candidates[i] = { efficiency[i], speed[i] };\n // sort candidates in descending order\n sort(candidates.rbegin(), candidates.rend());\n // Using Example 1: \n // speed: [2, 10, 3, 1 ,5, 8] and efficiency: [5, 4, 3, 9, 7, 2]\n // after sort, it becomes\n // candidates: [{9, 1}, {7 ,5}, {5, 2}, {4, 10}, {3, 3}, {2, 8}]\n long speedSum = 0, ans = 0;\n // we use priority queue here with greater<int> to store the sum\n // i.e min heap (the smallest element goes on the top)\n priority_queue <int, vector<int>, greater<int>> pq;\n // iterate each pair\n for (auto& [e, s] : candidates) {\n // put the speed to priority queue\n pq.push(s);\n // add to speedSum\n speedSum += s;\n // we only need to choose at most k engineers\n // hence if the queue size is greater than k\n // we need to remove a candidate\n if (pq.size() > k) {\n // who to remove? of course the one with smallest speed\n speedSum -= pq.top();\n pq.pop();\n }\n // calculate the performance\n ans = max(ans, speedSum * e);\n }\n return ans % MOD;\n }\n};\n```\n\n**Python**\n\n```py\n# Time Complexity: O(N * (logN + logK)) \n# Space Complexity: O(N + K)\n# where N is the total number of candidates and K is the size of team\nclass Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n MOD = 10 ** 9 + 7\n # build tuples ( efficiency, speed ) so that we can sort it later\n candidates = zip(efficiency, speed)\n # default sort mode is ascending. use `reverse = True` to sort in descending\n candidates = sorted(candidates, key=lambda x: x[0], reverse=True)\n # Using Example 1: \n # speed: [2, 10, 3, 1 ,5, 8] and efficiency: [5, 4, 3, 9, 7, 2]\n # after sort, it becomes\n # candidates: [(9, 1), (7 ,5), (5, 2), (4, 10), (3, 3), (2, 8)]\n speedSum, ans = 0, 0\n # in python, it usually refers to heap \n heap = []\n # iterate each tuple\n for e, s in candidates:\n # put the speed to heap\n heapq.heappush(heap, s)\n # add to speedSum\n speedSum += s\n # we only need to choose at most k engineers\n # hence if the queue size is greater than k\n # we need to remove a candidate\n if len(heap) > k:\n # who to remove? of course the one with smallest speed\n speedSum -= heapq.heappop(heap)\n # calculate the performance\n ans = max(ans, speedSum * e)\n return ans % MOD\n``` | 116 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Python Priority Queue Solution | maximum-performance-of-a-team | 0 | 1 | ```\nclass Solution:\n def maxPerformance(self, n, speed, efficiency, k):\n h = []\n res = sSum = 0\n for e, s in sorted(zip(efficiency, speed), reverse=1):\n heapq.heappush(h, s)\n sSum += s\n if len(h) > k:\n sSum -= heapq.heappop(h)\n res = max(res, sSum * e)\n return res % (10**9 + 7)\n``` | 2 | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. |
Python Priority Queue Solution | maximum-performance-of-a-team | 0 | 1 | ```\nclass Solution:\n def maxPerformance(self, n, speed, efficiency, k):\n h = []\n res = sSum = 0\n for e, s in sorted(zip(efficiency, speed), reverse=1):\n heapq.heappush(h, s)\n sSum += s\n if len(h) > k:\n sSum -= heapq.heappop(h)\n res = max(res, sSum * e)\n return res % (10**9 + 7)\n``` | 2 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Met this problem in my interview!!! (Python3 greedy with heap) | maximum-performance-of-a-team | 0 | 1 | Update: Very similar question: [857](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/)\n\nI met this problem in today\'s online interview, but sadly I never did this before and finally I solved this under some hints given by the interviewer. Here I share my ideas as a review.\n\nAt the begining the constraint of K was concelled that the team can be composed by any number of the N engineers. This is a simpler version of this problem. The greedy strategy of the simpler version is that we sort the engineers in descending order of efficiencies and check every team that composed by the top X engineers, X from 1 to N. Why this is correct? Let\'s say after sorting, the speeds are [s1, s2, ..., sN], and the efficiencies are [e1, e2, ..., eN], where we have e1 >= e2 >= ... >= eN. Consider the best team with minmum efficiency ei, it must be composed by the top i engineers because they are all the engineers with efficiencies >= ei which maximize the sum of speeds. So this leads to the greedy strategy. Code is given bellow.\n```Python\nclass Solution:\n def maxPerformance_simple(self, n, speed, efficiency):\n \n people = sorted(zip(speed, efficiency), key=lambda x: -x[1])\n \n result, sum_speed = 0, 0\n \n for s, e in people:\n sum_speed += s\n result = max(result, sum_speed * e)\n \n return result # % 1000000007\n```\nThen the constraint of K came as a follow-up question. From the simpler version, it should be easier to derive the idea of this question. We still want to check the best team with minimum efficiency ei, but this time we can only have K engineers, so this means we have to find the top K speeds and this can be realized by a very classic algorithm that uses a min heap to find the top K elements of an array. Solution code is given below.\n```Python\nclass Solution:\n def maxPerformance(self, n, speed, efficiency, k):\n \n people = sorted(zip(speed, efficiency), key=lambda x: -x[1])\n \n result, sum_speed = 0, 0\n min_heap = []\n\t\t\n for i, (s, e) in enumerate(people):\n if i < k:\n sum_speed += s\n heapq.heappush(min_heap, s)\n elif s > min_heap[0]:\n sum_speed += s - heapq.heappushpop(min_heap, s)\n else:\n continue # don\'t have to update result since top k speeds are not changed and efficiency goes down\n \n result = max(result, sum_speed * e)\n \n return result # % 1000000007\n``` | 60 | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. |
Met this problem in my interview!!! (Python3 greedy with heap) | maximum-performance-of-a-team | 0 | 1 | Update: Very similar question: [857](https://leetcode.com/problems/minimum-cost-to-hire-k-workers/)\n\nI met this problem in today\'s online interview, but sadly I never did this before and finally I solved this under some hints given by the interviewer. Here I share my ideas as a review.\n\nAt the begining the constraint of K was concelled that the team can be composed by any number of the N engineers. This is a simpler version of this problem. The greedy strategy of the simpler version is that we sort the engineers in descending order of efficiencies and check every team that composed by the top X engineers, X from 1 to N. Why this is correct? Let\'s say after sorting, the speeds are [s1, s2, ..., sN], and the efficiencies are [e1, e2, ..., eN], where we have e1 >= e2 >= ... >= eN. Consider the best team with minmum efficiency ei, it must be composed by the top i engineers because they are all the engineers with efficiencies >= ei which maximize the sum of speeds. So this leads to the greedy strategy. Code is given bellow.\n```Python\nclass Solution:\n def maxPerformance_simple(self, n, speed, efficiency):\n \n people = sorted(zip(speed, efficiency), key=lambda x: -x[1])\n \n result, sum_speed = 0, 0\n \n for s, e in people:\n sum_speed += s\n result = max(result, sum_speed * e)\n \n return result # % 1000000007\n```\nThen the constraint of K came as a follow-up question. From the simpler version, it should be easier to derive the idea of this question. We still want to check the best team with minimum efficiency ei, but this time we can only have K engineers, so this means we have to find the top K speeds and this can be realized by a very classic algorithm that uses a min heap to find the top K elements of an array. Solution code is given below.\n```Python\nclass Solution:\n def maxPerformance(self, n, speed, efficiency, k):\n \n people = sorted(zip(speed, efficiency), key=lambda x: -x[1])\n \n result, sum_speed = 0, 0\n min_heap = []\n\t\t\n for i, (s, e) in enumerate(people):\n if i < k:\n sum_speed += s\n heapq.heappush(min_heap, s)\n elif s > min_heap[0]:\n sum_speed += s - heapq.heappushpop(min_heap, s)\n else:\n continue # don\'t have to update result since top k speeds are not changed and efficiency goes down\n \n result = max(result, sum_speed * e)\n \n return result # % 1000000007\n``` | 60 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Python3 soln with detailed explanation and complexity analysis | maximum-performance-of-a-team | 0 | 1 | # Intution\nThe problem is easy to implement once you understand the intution.\n\nAt first, we will create a 2d array to hold our engineer\'s efficiency and speed, then we sort our 2d array in decending order of the efficiency. Then we start to iterate through our 2d array. \nWhen we iterate through our engineers array, we need to notice these things\n- one is that the min efficiency will always be the current element\'s efficiency during our iteration as the array is sorted in decending order of the engineers efficency\n- so at each iteration we know our current min efficency, then we add current engineer\'s speed to our total speed, and if our tot engineers exceed k, we substract the min speed from all the engineers we have at this state.\n - after this, we have our tot speed and our min eff of these k engineers, then we can get the max perf of the current group of engineers.\n - so we update our max performance at each step, then return it when we finish our loop.\n\nHope this helps, Upvote if it was helpful\n\n```\nclass Solution:\n # O(nlogn) time,\n # O(n) space,\n # Approach: heap, sorting\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n # we create a array of tuples, (efficiency[i], speed[i])\n engineers = [(efficiency[i], speed[i]) for i in range(n)]\n # we will sort the our array in descending order of the engineers efficiency\n engineers.sort(reverse=True)\n \n # we create variables to hold the max performance, and tot speed when we iterate through our engineers array\n # we will also have a min heap to store our min speed during our iteration, \n # poping the next min speed will be possible that way\n max_perf = 0\n min_heap = []\n tot_speed = 0\n \n for engineer in engineers:\n eng_speed = engineer[1]\n min_eff = engineer[0]\n \n # we add our current\n heapq.heappush(min_heap, eng_speed)\n tot_speed += eng_speed\n \n # if tot engnrs are more than k, we pop the slowest engineer\n if len(min_heap) > k:\n tot_speed -=heapq.heappop(min_heap)\n \n # we calculate the max perf we can get from this round of engineers\n curr_max = tot_speed * min_eff\n # update our max perf, \n max_perf = max(max_perf, curr_max)\n \n MOD = 10**9 + 7\n return max_perf % MOD\n``` | 1 | You are given two integers `n` and `k` and two integer arrays `speed` and `efficiency` both of length `n`. There are `n` engineers numbered from `1` to `n`. `speed[i]` and `efficiency[i]` represent the speed and efficiency of the `ith` engineer respectively.
Choose **at most** `k` different engineers out of the `n` engineers to form a team with the maximum **performance**.
The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.
Return _the maximum performance of this team_. Since the answer can be a huge number, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 2
**Output:** 60
**Explanation:**
We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) \* min(4, 7) = 60.
**Example 2:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 3
**Output:** 68
**Explanation:**
This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) \* min(5, 4, 7) = 68.
**Example 3:**
**Input:** n = 6, speed = \[2,10,3,1,5,8\], efficiency = \[5,4,3,9,7,2\], k = 4
**Output:** 72
**Constraints:**
* `1 <= k <= n <= 105`
* `speed.length == n`
* `efficiency.length == n`
* `1 <= speed[i] <= 105`
* `1 <= efficiency[i] <= 108` | The maximum value of nums.length is very large, but the maximum value of nums[i] is not. Count the number of times each value appears in nums. Brute force through every possible combination of values and count how many single divisor triplets can be made with that combination of values. |
Python3 soln with detailed explanation and complexity analysis | maximum-performance-of-a-team | 0 | 1 | # Intution\nThe problem is easy to implement once you understand the intution.\n\nAt first, we will create a 2d array to hold our engineer\'s efficiency and speed, then we sort our 2d array in decending order of the efficiency. Then we start to iterate through our 2d array. \nWhen we iterate through our engineers array, we need to notice these things\n- one is that the min efficiency will always be the current element\'s efficiency during our iteration as the array is sorted in decending order of the engineers efficency\n- so at each iteration we know our current min efficency, then we add current engineer\'s speed to our total speed, and if our tot engineers exceed k, we substract the min speed from all the engineers we have at this state.\n - after this, we have our tot speed and our min eff of these k engineers, then we can get the max perf of the current group of engineers.\n - so we update our max performance at each step, then return it when we finish our loop.\n\nHope this helps, Upvote if it was helpful\n\n```\nclass Solution:\n # O(nlogn) time,\n # O(n) space,\n # Approach: heap, sorting\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n # we create a array of tuples, (efficiency[i], speed[i])\n engineers = [(efficiency[i], speed[i]) for i in range(n)]\n # we will sort the our array in descending order of the engineers efficiency\n engineers.sort(reverse=True)\n \n # we create variables to hold the max performance, and tot speed when we iterate through our engineers array\n # we will also have a min heap to store our min speed during our iteration, \n # poping the next min speed will be possible that way\n max_perf = 0\n min_heap = []\n tot_speed = 0\n \n for engineer in engineers:\n eng_speed = engineer[1]\n min_eff = engineer[0]\n \n # we add our current\n heapq.heappush(min_heap, eng_speed)\n tot_speed += eng_speed\n \n # if tot engnrs are more than k, we pop the slowest engineer\n if len(min_heap) > k:\n tot_speed -=heapq.heappop(min_heap)\n \n # we calculate the max perf we can get from this round of engineers\n curr_max = tot_speed * min_eff\n # update our max perf, \n max_perf = max(max_perf, curr_max)\n \n MOD = 10**9 + 7\n return max_perf % MOD\n``` | 1 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
🔥[Python 3] Bucket sort O(n) with optimisation, beats 98.6 % 🥷🏼 | find-the-distance-value-between-two-arrays | 0 | 1 | Encouraged by [220. Contains Duplicate III (hard)](https://leetcode.com/problems/contains-duplicate-iii/solutions/3546546/python-bucketsort-o-n-beat-98-with-comments/)\n\n```python3 []\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n res, buckets = 0, dict() # (minVa, maxVal)\n \n def getKey(val):\n return val // d\n \n def addVal(val):\n key = getKey(val)\n #save only min and max value in bucket, others values not\n if key in buckets:\n if buckets[key][0] > val: buckets[key][0] = val\n elif buckets[key][1] < val: buckets[key][1] = val\n else:\n buckets[key] = [val, val]\n \n #initialize buckets \n for val in arr2: addVal(val)\n\n for val in arr1:\n key = getKey(val)\n if key in buckets: continue #in one bucket all values x < d\n #check sibling buckets\n if key - 1 in buckets and val - buckets[key-1][1] <= d: continue #maxVal from the left side is nearest\n if key + 1 in buckets and buckets[key+1][0] - val <= d: continue #minVal from the right side is nearest\n res += 1\n\n return res\n```\n\n | 11 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
🔥[Python 3] Bucket sort O(n) with optimisation, beats 98.6 % 🥷🏼 | find-the-distance-value-between-two-arrays | 0 | 1 | Encouraged by [220. Contains Duplicate III (hard)](https://leetcode.com/problems/contains-duplicate-iii/solutions/3546546/python-bucketsort-o-n-beat-98-with-comments/)\n\n```python3 []\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n res, buckets = 0, dict() # (minVa, maxVal)\n \n def getKey(val):\n return val // d\n \n def addVal(val):\n key = getKey(val)\n #save only min and max value in bucket, others values not\n if key in buckets:\n if buckets[key][0] > val: buckets[key][0] = val\n elif buckets[key][1] < val: buckets[key][1] = val\n else:\n buckets[key] = [val, val]\n \n #initialize buckets \n for val in arr2: addVal(val)\n\n for val in arr1:\n key = getKey(val)\n if key in buckets: continue #in one bucket all values x < d\n #check sibling buckets\n if key - 1 in buckets and val - buckets[key-1][1] <= d: continue #maxVal from the left side is nearest\n if key + 1 in buckets and buckets[key+1][0] - val <= d: continue #minVal from the right side is nearest\n res += 1\n\n return res\n```\n\n | 11 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Easy to understand for Python solve | find-the-distance-value-between-two-arrays | 0 | 1 | \n# Complexity\n- Time comple: 94.12 %\n- Space complexity: 80 %\n# Understanding\n- First I have sort arr2.\n- Then iterate arr1.\n- Search element that you need (BSA)\n- If there is no such value, increase the value of c by 1.\n- Loop until the element arr1 is finished.\n\n<h1><a href="https://leetcode.com/MAMuhammad571/">My account<a></h1>\n\n# Code\n```\nclass Solution:\n def is_left(self, n: int, arr: list[int], d: int):\n l, r = 0, len(arr)-1\n while l <= r:\n m = (l + r) // 2\n if abs(arr[m] - n) <= d:\n return True\n elif arr[m] > n:\n r = m - 1\n else:\n l = m + 1\n return False\n\n def is_right(self, n: int, arr: list[int], d: int):\n l, r = 0, len(arr)-1\n while l <= r:\n m = (l + r) // 2\n if abs(arr[m] - n) <= d:\n return True\n elif arr[m] < n:\n r = m - 1\n else:\n l = m + 1\n return False\n\n def findTheDistanceValue(self, arr1: list[int], arr2: list[int], d: int) -> int:\n arr2.sort()\n c = 0\n for i in arr1:\n if not self.is_left(i, arr2, d):\n if not self.is_right(i, arr2, d):\n print(i)\n c += 1\n return c\n``` | 1 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
Easy to understand for Python solve | find-the-distance-value-between-two-arrays | 0 | 1 | \n# Complexity\n- Time comple: 94.12 %\n- Space complexity: 80 %\n# Understanding\n- First I have sort arr2.\n- Then iterate arr1.\n- Search element that you need (BSA)\n- If there is no such value, increase the value of c by 1.\n- Loop until the element arr1 is finished.\n\n<h1><a href="https://leetcode.com/MAMuhammad571/">My account<a></h1>\n\n# Code\n```\nclass Solution:\n def is_left(self, n: int, arr: list[int], d: int):\n l, r = 0, len(arr)-1\n while l <= r:\n m = (l + r) // 2\n if abs(arr[m] - n) <= d:\n return True\n elif arr[m] > n:\n r = m - 1\n else:\n l = m + 1\n return False\n\n def is_right(self, n: int, arr: list[int], d: int):\n l, r = 0, len(arr)-1\n while l <= r:\n m = (l + r) // 2\n if abs(arr[m] - n) <= d:\n return True\n elif arr[m] < n:\n r = m - 1\n else:\n l = m + 1\n return False\n\n def findTheDistanceValue(self, arr1: list[int], arr2: list[int], d: int) -> int:\n arr2.sort()\n c = 0\n for i in arr1:\n if not self.is_left(i, arr2, d):\n if not self.is_right(i, arr2, d):\n print(i)\n c += 1\n return c\n``` | 1 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Binary Search and Brute Force Logic | find-the-distance-value-between-two-arrays | 0 | 1 | \n\n# Brute Force Approach\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in arr1:\n for j in arr2:\n if abs(i-j)<=d:\n count+=1\n break\n return len(arr1)-count\n #please upvote me it would encourage me alot\n\n\n```\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n arr2.sort()\n for i in range(len(arr1)):\n left,right=0,len(arr2)-1\n while left<=right:\n mid=(left+right)//2\n if abs(arr1[i]-arr2[mid])<=d:\n count+=1\n break\n elif arr1[i]<arr2[mid]:\n right=mid-1\n else:\n left=mid+1\n return len(arr1)-count\n```\n# please upvote me it would encourage me alot\n | 12 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
Binary Search and Brute Force Logic | find-the-distance-value-between-two-arrays | 0 | 1 | \n\n# Brute Force Approach\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n for i in arr1:\n for j in arr2:\n if abs(i-j)<=d:\n count+=1\n break\n return len(arr1)-count\n #please upvote me it would encourage me alot\n\n\n```\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n count=0\n arr2.sort()\n for i in range(len(arr1)):\n left,right=0,len(arr2)-1\n while left<=right:\n mid=(left+right)//2\n if abs(arr1[i]-arr2[mid])<=d:\n count+=1\n break\n elif arr1[i]<arr2[mid]:\n right=mid-1\n else:\n left=mid+1\n return len(arr1)-count\n```\n# please upvote me it would encourage me alot\n | 12 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Python 3 | Binary Search | find-the-distance-value-between-two-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe sort the second array and perform binary search on it $$M$$ times in order to count the results.\n\n# Complexity\n- Time complexity: $$O(min(N\\log(N), M\\log(N)))$$, where $$N$$ is the size of `arr2` and $$M$$ is the size of ``arr1``. First term is from sorting `arr2` and the second term is from querying the sorted array $$M$$ times.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$, probably taken by Python for the sorting.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2=sorted(arr2)\n res=0\n for num in arr1:\n idx = bisect.bisect_left(arr2, num)\n lower_within_limits = abs(arr2[min(len(arr2)-1, idx)]-num)>d\n higher_within_limits = abs(arr2[max(0, idx-1)]-num)>d\n if lower_within_limits and higher_within_limits:\n res+=1\n return res\n``` | 1 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
Python 3 | Binary Search | find-the-distance-value-between-two-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe sort the second array and perform binary search on it $$M$$ times in order to count the results.\n\n# Complexity\n- Time complexity: $$O(min(N\\log(N), M\\log(N)))$$, where $$N$$ is the size of `arr2` and $$M$$ is the size of ``arr1``. First term is from sorting `arr2` and the second term is from querying the sorted array $$M$$ times.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$, probably taken by Python for the sorting.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2=sorted(arr2)\n res=0\n for num in arr1:\n idx = bisect.bisect_left(arr2, num)\n lower_within_limits = abs(arr2[min(len(arr2)-1, idx)]-num)>d\n higher_within_limits = abs(arr2[max(0, idx-1)]-num)>d\n if lower_within_limits and higher_within_limits:\n res+=1\n return res\n``` | 1 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
C++/Python Best Approach solution | find-the-distance-value-between-two-arrays | 0 | 1 | #### C++\nRuntime: 15 ms, faster than 70.57% of C++ online submissions for Find the Distance Value Between Two Arrays.\nMemory Usage: 13.2 MB, less than 29.43% of C++ online submissions for Find the Distance Value Between Two Arrays.\n\n```\nclass Solution {\npublic:\n int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {\n int len = arr2.size();\n\t\tint count = 0;\n sort(arr2.begin(), arr2.end());\n \n for(int i = 0; i < arr1.size(); i++) {\n bool flag = false; \n int s = 0;\n\t\t\tint e = len - 1;\n\t\t\tint m;\n \n while(s <= e) {\n m = s + (e - s) / 2;\n if(abs(arr2[m] - arr1[i]) <= d) {\n flag = true;\n break;\n }\n \n else if(arr2[m] > arr1[i]) {\n e = m - 1;\n\t\t\t\t}\n \n else {\n s = m + 1;\n\t\t\t\t}\n }\n \n if(!flag) {\n count++;\n\t\t\t}\n }\n return count;\n }\n};\n```\nTime Complexity - O(LogN)\nSpace Complexity - O(1)\n\n#### Python\nRuntime: 155 ms, faster than 48.58% of Python3 online submissions for Find the Distance Value Between Two Arrays.\nMemory Usage: 14.1 MB, less than 41.69% of Python3 online submissions for Find the Distance Value Between Two Arrays.\n\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n distance = len(arr1)\n for num in arr1:\n start = 0\n end = len(arr2) - 1\n while start <= end:\n mid = (start+end)//2\n if abs(num- arr2[mid]) <= d:\n distance -= 1\n break\n elif arr2[mid] > num :\n end = mid-1\n elif arr2[mid] < num :\n start = mid+1\n return distance\n```\nTime Complexity - O(logN)\nSpace Complexity - O(1)\n\n##### If you like the solution and find it understandable, then do upvote it & Share it with others.\n##### If you found any error, any suggestions then do comment for any query\n##### Thanks alot ! Cheers to your coding | 2 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
C++/Python Best Approach solution | find-the-distance-value-between-two-arrays | 0 | 1 | #### C++\nRuntime: 15 ms, faster than 70.57% of C++ online submissions for Find the Distance Value Between Two Arrays.\nMemory Usage: 13.2 MB, less than 29.43% of C++ online submissions for Find the Distance Value Between Two Arrays.\n\n```\nclass Solution {\npublic:\n int findTheDistanceValue(vector<int>& arr1, vector<int>& arr2, int d) {\n int len = arr2.size();\n\t\tint count = 0;\n sort(arr2.begin(), arr2.end());\n \n for(int i = 0; i < arr1.size(); i++) {\n bool flag = false; \n int s = 0;\n\t\t\tint e = len - 1;\n\t\t\tint m;\n \n while(s <= e) {\n m = s + (e - s) / 2;\n if(abs(arr2[m] - arr1[i]) <= d) {\n flag = true;\n break;\n }\n \n else if(arr2[m] > arr1[i]) {\n e = m - 1;\n\t\t\t\t}\n \n else {\n s = m + 1;\n\t\t\t\t}\n }\n \n if(!flag) {\n count++;\n\t\t\t}\n }\n return count;\n }\n};\n```\nTime Complexity - O(LogN)\nSpace Complexity - O(1)\n\n#### Python\nRuntime: 155 ms, faster than 48.58% of Python3 online submissions for Find the Distance Value Between Two Arrays.\nMemory Usage: 14.1 MB, less than 41.69% of Python3 online submissions for Find the Distance Value Between Two Arrays.\n\n```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n arr2.sort()\n distance = len(arr1)\n for num in arr1:\n start = 0\n end = len(arr2) - 1\n while start <= end:\n mid = (start+end)//2\n if abs(num- arr2[mid]) <= d:\n distance -= 1\n break\n elif arr2[mid] > num :\n end = mid-1\n elif arr2[mid] < num :\n start = mid+1\n return distance\n```\nTime Complexity - O(logN)\nSpace Complexity - O(1)\n\n##### If you like the solution and find it understandable, then do upvote it & Share it with others.\n##### If you found any error, any suggestions then do comment for any query\n##### Thanks alot ! Cheers to your coding | 2 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Python3 | Solved Using Binary Search and Considering Range of Numbers | find-the-distance-value-between-two-arrays | 0 | 1 | ```\nclass Solution:\n #Time-Complexity: O(len(arr1)*2d*log(len(arr2)))\n #Space-Complexity: O(1)\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n #initialize ans variable!\n ans = 0\n #helper function will compute whether particular element is in given array of elements,\n #of at least size 1!\n \n #to apply helper function on arr2, we need to make sure it\'s sorted!\n arr2.sort()\n def helper(e, a):\n #involve binary search\n L, R = 0, len(a) - 1\n while L <= R:\n mid = (L+R) // 2\n if(a[mid] == e):\n return True\n elif(a[mid] > e):\n R = mid - 1\n continue\n else:\n L = mid + 1\n continue\n return False\n \n #iterate through each and every element in arr1!\n for num in arr1:\n #flag will indicate whether current num is able to contribute to distance value!\n flag = True\n #iterate through possible values w/ respect to num that will make it\n #not contribute to distance value between two arrays!\n for i in range(num - d, num+d+1):\n #check if current i is in arr2!\n #if so, set flag off and break!\n if(helper(i, arr2)):\n flag = False\n break\n #check boolean flag!\n if(flag):\n ans += 1\n return ans | 1 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
Python3 | Solved Using Binary Search and Considering Range of Numbers | find-the-distance-value-between-two-arrays | 0 | 1 | ```\nclass Solution:\n #Time-Complexity: O(len(arr1)*2d*log(len(arr2)))\n #Space-Complexity: O(1)\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n #initialize ans variable!\n ans = 0\n #helper function will compute whether particular element is in given array of elements,\n #of at least size 1!\n \n #to apply helper function on arr2, we need to make sure it\'s sorted!\n arr2.sort()\n def helper(e, a):\n #involve binary search\n L, R = 0, len(a) - 1\n while L <= R:\n mid = (L+R) // 2\n if(a[mid] == e):\n return True\n elif(a[mid] > e):\n R = mid - 1\n continue\n else:\n L = mid + 1\n continue\n return False\n \n #iterate through each and every element in arr1!\n for num in arr1:\n #flag will indicate whether current num is able to contribute to distance value!\n flag = True\n #iterate through possible values w/ respect to num that will make it\n #not contribute to distance value between two arrays!\n for i in range(num - d, num+d+1):\n #check if current i is in arr2!\n #if so, set flag off and break!\n if(helper(i, arr2)):\n flag = False\n break\n #check boolean flag!\n if(flag):\n ans += 1\n return ans | 1 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Python 89.32% Faster | find-the-distance-value-between-two-arrays | 0 | 1 | ```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n x=0\n for i in arr1:\n c=1\n for j in arr2:\n if abs(i-j)<=d:\n c=0\n break \n if c:\n x+=1\n return x\n``` | 2 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
Python 89.32% Faster | find-the-distance-value-between-two-arrays | 0 | 1 | ```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n x=0\n for i in arr1:\n c=1\n for j in arr2:\n if abs(i-j)<=d:\n c=0\n break \n if c:\n x+=1\n return x\n``` | 2 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
[Python] Iterative Binary Search Solution || Well Documented | find-the-distance-value-between-two-arrays | 0 | 1 | ```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n # binary search for diff <= d, if found return 0, else 1\n def binSearch(value: int) -> int:\n low, high = 0, len(arr2) - 1 \n\n # Repeat until the pointers low and high meet each other\n while low <= high: \n mid = (low + high) // 2\n\n if abs(value-arr2[mid]) <= d: \n return 0\n if v > arr2[mid]: \n low = mid + 1 # go right side\n else: \n high = mid - 1 # go left side\n \n # no such value found where diff <= d\n return 1\n\n # sort the array so that we can perform binary-search\n arr2.sort()\n\n # distance value count\n dValueCount = 0\n \n # search for diff <= d for each num \n for v in arr1:\n dValueCount += binSearch(v)\n return dValueCount\n```\nPlease UPVOTE\uD83D\uDC4D if you love\u2764\uFE0F this solution or learned something new.\nIf you have any question, feel free to ask.\n | 2 | Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_.
The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`.
**Example 1:**
**Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2
**Output:** 2
**Explanation:**
For arr1\[0\]=4 we have:
|4-10|=6 > d=2
|4-9|=5 > d=2
|4-1|=3 > d=2
|4-8|=4 > d=2
For arr1\[1\]=5 we have:
|5-10|=5 > d=2
|5-9|=4 > d=2
|5-1|=4 > d=2
|5-8|=3 > d=2
For arr1\[2\]=8 we have:
**|8-10|=2 <= d=2**
**|8-9|=1 <= d=2**
|8-1|=7 > d=2
**|8-8|=0 <= d=2**
**Example 2:**
**Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3
**Output:** 2
**Example 3:**
**Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6
**Output:** 1
**Constraints:**
* `1 <= arr1.length, arr2.length <= 500`
* `-1000 <= arr1[i], arr2[j] <= 1000`
* `0 <= d <= 100` | If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles. |
[Python] Iterative Binary Search Solution || Well Documented | find-the-distance-value-between-two-arrays | 0 | 1 | ```\nclass Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n # binary search for diff <= d, if found return 0, else 1\n def binSearch(value: int) -> int:\n low, high = 0, len(arr2) - 1 \n\n # Repeat until the pointers low and high meet each other\n while low <= high: \n mid = (low + high) // 2\n\n if abs(value-arr2[mid]) <= d: \n return 0\n if v > arr2[mid]: \n low = mid + 1 # go right side\n else: \n high = mid - 1 # go left side\n \n # no such value found where diff <= d\n return 1\n\n # sort the array so that we can perform binary-search\n arr2.sort()\n\n # distance value count\n dValueCount = 0\n \n # search for diff <= d for each num \n for v in arr1:\n dValueCount += binSearch(v)\n return dValueCount\n```\nPlease UPVOTE\uD83D\uDC4D if you love\u2764\uFE0F this solution or learned something new.\nIf you have any question, feel free to ask.\n | 2 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^ " corresponds to bitwise XOR operator.
**Example 2:**
**Input:** n = 4, start = 3
**Output:** 8
**Explanation:** Array nums is equal to \[3, 5, 7, 9\] where (3 ^ 5 ^ 7 ^ 9) = 8.
**Constraints:**
* `1 <= n <= 1000`
* `0 <= start <= 1000`
* `n == nums.length` | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Python - Easy HashMap Solution | Faster than 95% | cinema-seat-allocation | 0 | 1 | The main difference between this hashset solution and others is mutual exclusivity. \n\nInstead of going through arrangements of four, we go through arrangements of two. The middle seats count double, the outer seats count as one.\n\nThen we subtract the tally from the total number of possible solutions. If the cinema were empty, that number would be 2n. \n\nThat\'s actually my voice in the video. I sound like an international robot. \n\n[@easyCodingSolutions](https://youtu.be/o_EF3EQmjHM)\n\nhttps://youtu.be/o_EF3EQmjHM\n\n# Code\n```\nclass Solution:\n def maxNumberOfFamilies(self, n, reservedSeats):\n # Create a dictionary of sets to store the reserved seats by row\n seats = collections.defaultdict(set)\n # Iterate through the reserved seats\n for i,j in reservedSeats:\n # If the seat is an outside seat in the row, add it to tallies 0 and 1\n if j in {4,5}: \n seats[i].add(0) \n seats[i].add(1)\n # If the seat is a middle seat in the row, add it to tallies 1 and 2\n elif j in {6,7}: \n seats[i].add(1)\n seats[i].add(2)\n # If the seat is another type of seat, add it to the corresponding tally\n elif j in {8,9}: \n seats[i].add(2)\n elif j in {2,3}:\n seats[i].add(0)\n # Initialize the result to twice the number of rows\n res = 2*n\n # Iterate through the rows of seats\n for i in seats:\n # If a row has all three tallies, subtract two from the result\n if len(seats[i]) == 3: res -= 2\n # Otherwise, subtract one from the result\n else: res -= 1\n\n # Return the final result\n return res\n\n```\n\n | 21 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved.
_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
**Example 1:**
**Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\]
**Output:** 4
**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
**Example 2:**
**Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\]
**Output:** 2
**Example 3:**
**Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 10^9`
* `1 <= reservedSeats.length <= min(10*n, 10^4)`
* `reservedSeats[i].length == 2`
* `1 <= reservedSeats[i][0] <= n`
* `1 <= reservedSeats[i][1] <= 10`
* All `reservedSeats[i]` are distinct. | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
Python - Easy HashMap Solution | Faster than 95% | cinema-seat-allocation | 0 | 1 | The main difference between this hashset solution and others is mutual exclusivity. \n\nInstead of going through arrangements of four, we go through arrangements of two. The middle seats count double, the outer seats count as one.\n\nThen we subtract the tally from the total number of possible solutions. If the cinema were empty, that number would be 2n. \n\nThat\'s actually my voice in the video. I sound like an international robot. \n\n[@easyCodingSolutions](https://youtu.be/o_EF3EQmjHM)\n\nhttps://youtu.be/o_EF3EQmjHM\n\n# Code\n```\nclass Solution:\n def maxNumberOfFamilies(self, n, reservedSeats):\n # Create a dictionary of sets to store the reserved seats by row\n seats = collections.defaultdict(set)\n # Iterate through the reserved seats\n for i,j in reservedSeats:\n # If the seat is an outside seat in the row, add it to tallies 0 and 1\n if j in {4,5}: \n seats[i].add(0) \n seats[i].add(1)\n # If the seat is a middle seat in the row, add it to tallies 1 and 2\n elif j in {6,7}: \n seats[i].add(1)\n seats[i].add(2)\n # If the seat is another type of seat, add it to the corresponding tally\n elif j in {8,9}: \n seats[i].add(2)\n elif j in {2,3}:\n seats[i].add(0)\n # Initialize the result to twice the number of rows\n res = 2*n\n # Iterate through the rows of seats\n for i in seats:\n # If a row has all three tallies, subtract two from the result\n if len(seats[i]) == 3: res -= 2\n # Otherwise, subtract one from the result\n else: res -= 1\n\n # Return the final result\n return res\n\n```\n\n | 21 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Commented solutions, beats 97% Python/Java | cinema-seat-allocation | 1 | 1 | # Intuition\nIf we know the number of 4-person sections blocked in each row, we can determine the number available.\n\n# Approach\n\n1. Create a map from row numbers to blocked sections (\'left\', \'right\', \'middle\').\n2. Iterate over the reserved seats, updating the row record:\n 1. If the column is 2-5, add \'left\'.\n 2. If the column is 4-7, add \'middle\'.\n 3. If the column is 6-9, add \'right\'.\n3. Return the total of:\n 1. Two times the number of rows with no blocked sections\n 2. The number of available sections in each row with blocked sections\n 1. If 1 section is blocked, 1 is available (because sections overlap).\n 2. If 2 sections are blocked, 1 is available.\n 3. If 3 sections are blocked, none are available.\n\n\n# Complexity\n- Time complexity: $$O(k + n)$$ where\n - $k$ is the number of initial reservations\n - $n$ is the number of rows\n\n- Space complexity: $$O(r)$$ where $r$ is the number of rows with blocked seats\n\nIt is important that the data structure keeping track of blocked sections only has entries for partially occupied rows, not empty rows, or the time and memory limits may be exceeded.\n\n# Python Code\n```\nclass Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n # Each row has 3 possible group positions: \'left\', \'middle\', \'right\'.\n # We will keep track of which positions are unavailable (blocked).\n blocked = defaultdict(set)\n\n # Iterate over all reserved seats, saving blocked positions.\n for row, col in reservedSeats:\n if col in [2, 3, 4, 5]:\n blocked[row].add(\'left\')\n if col in [4, 5, 6, 7]:\n blocked[row].add(\'middle\')\n if col in [6, 7, 8, 9]:\n blocked[row].add(\'right\')\n \n # The variable total will hold the number of 4-person reservations available.\n # Initialize it with 2 per row having no seats blocked.\n total = 2 * (n - len(blocked))\n\n # Provide the number of sections available based on the number blocked.\n # For example, if 0 are blocked, 2 are available.\n numAvailable = {0: 2, 1: 1, 2: 1, 3: 0}\n \n # For each row with blocked sections, add the number of available sections.\n for numBlocked in blocked.values():\n total += numAvailable[len(numBlocked)]\n\n return total\n\n```\n\n# Java Code\n```\nclass Solution {\n public int maxNumberOfFamilies(int n, int[][] reservedSeats) {\n // Each row has 3 possible group positions: "left", "middle", and "right".\n // Keep track of which positions are unavailable (blocked).\n Map<Integer, Set<String>> blocked = new HashMap<>();\n\n // Iterate over all reserved seats, indicating which positions are blocked.\n for (int[] reservation : reservedSeats) {\n int row = reservation[0];\n int col = reservation[1];\n\n // Reservations in columns 1 and 10 don\'t block 4-person positions.\n if (col == 1 || col == 10) {\n continue;\n }\n\n // Retrieve the set for this row, creating it if it didn\'t exist.\n Set<String> set = blocked.computeIfAbsent(row, k -> new HashSet<>());\n\n // Add strings indicating which of the 3 positions are blocked.\n if (col >= 2 && col <= 5) {\n set.add("left");\n }\n if (col >= 4 && col <= 7) {\n set.add("middle");\n }\n if (col >= 6 && col <= 9) {\n set.add("right");\n }\n }\n\n // The variable total will hold the number of 4-person positions available.\n // Initialize it with 2 for each row that does not have any blocked positions.\n int total = 2 * (n - blocked.size());\n\n // Map the number of positions blocked to the number available.\n int[] numAvailable = {\n 2, // if no positions are blocked, 2 are available\n 1, // if one position is blocked, 1 is available\n 1, // if two positions are blocked, 1 is available\n 0 // if all 3 positions are blocked, none are available \n };\n\n // For each row having blocks, add the number of available positions.\n for (Set<String> blocks : blocked.values()) {\n total += numAvailable[blocks.size()];\n }\n \n return total;\n }\n}\n``` | 4 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved.
_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
**Example 1:**
**Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\]
**Output:** 4
**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
**Example 2:**
**Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\]
**Output:** 2
**Example 3:**
**Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 10^9`
* `1 <= reservedSeats.length <= min(10*n, 10^4)`
* `reservedSeats[i].length == 2`
* `1 <= reservedSeats[i][0] <= n`
* `1 <= reservedSeats[i][1] <= 10`
* All `reservedSeats[i]` are distinct. | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
Commented solutions, beats 97% Python/Java | cinema-seat-allocation | 1 | 1 | # Intuition\nIf we know the number of 4-person sections blocked in each row, we can determine the number available.\n\n# Approach\n\n1. Create a map from row numbers to blocked sections (\'left\', \'right\', \'middle\').\n2. Iterate over the reserved seats, updating the row record:\n 1. If the column is 2-5, add \'left\'.\n 2. If the column is 4-7, add \'middle\'.\n 3. If the column is 6-9, add \'right\'.\n3. Return the total of:\n 1. Two times the number of rows with no blocked sections\n 2. The number of available sections in each row with blocked sections\n 1. If 1 section is blocked, 1 is available (because sections overlap).\n 2. If 2 sections are blocked, 1 is available.\n 3. If 3 sections are blocked, none are available.\n\n\n# Complexity\n- Time complexity: $$O(k + n)$$ where\n - $k$ is the number of initial reservations\n - $n$ is the number of rows\n\n- Space complexity: $$O(r)$$ where $r$ is the number of rows with blocked seats\n\nIt is important that the data structure keeping track of blocked sections only has entries for partially occupied rows, not empty rows, or the time and memory limits may be exceeded.\n\n# Python Code\n```\nclass Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n # Each row has 3 possible group positions: \'left\', \'middle\', \'right\'.\n # We will keep track of which positions are unavailable (blocked).\n blocked = defaultdict(set)\n\n # Iterate over all reserved seats, saving blocked positions.\n for row, col in reservedSeats:\n if col in [2, 3, 4, 5]:\n blocked[row].add(\'left\')\n if col in [4, 5, 6, 7]:\n blocked[row].add(\'middle\')\n if col in [6, 7, 8, 9]:\n blocked[row].add(\'right\')\n \n # The variable total will hold the number of 4-person reservations available.\n # Initialize it with 2 per row having no seats blocked.\n total = 2 * (n - len(blocked))\n\n # Provide the number of sections available based on the number blocked.\n # For example, if 0 are blocked, 2 are available.\n numAvailable = {0: 2, 1: 1, 2: 1, 3: 0}\n \n # For each row with blocked sections, add the number of available sections.\n for numBlocked in blocked.values():\n total += numAvailable[len(numBlocked)]\n\n return total\n\n```\n\n# Java Code\n```\nclass Solution {\n public int maxNumberOfFamilies(int n, int[][] reservedSeats) {\n // Each row has 3 possible group positions: "left", "middle", and "right".\n // Keep track of which positions are unavailable (blocked).\n Map<Integer, Set<String>> blocked = new HashMap<>();\n\n // Iterate over all reserved seats, indicating which positions are blocked.\n for (int[] reservation : reservedSeats) {\n int row = reservation[0];\n int col = reservation[1];\n\n // Reservations in columns 1 and 10 don\'t block 4-person positions.\n if (col == 1 || col == 10) {\n continue;\n }\n\n // Retrieve the set for this row, creating it if it didn\'t exist.\n Set<String> set = blocked.computeIfAbsent(row, k -> new HashSet<>());\n\n // Add strings indicating which of the 3 positions are blocked.\n if (col >= 2 && col <= 5) {\n set.add("left");\n }\n if (col >= 4 && col <= 7) {\n set.add("middle");\n }\n if (col >= 6 && col <= 9) {\n set.add("right");\n }\n }\n\n // The variable total will hold the number of 4-person positions available.\n // Initialize it with 2 for each row that does not have any blocked positions.\n int total = 2 * (n - blocked.size());\n\n // Map the number of positions blocked to the number available.\n int[] numAvailable = {\n 2, // if no positions are blocked, 2 are available\n 1, // if one position is blocked, 1 is available\n 1, // if two positions are blocked, 1 is available\n 0 // if all 3 positions are blocked, none are available \n };\n\n // For each row having blocks, add the number of available positions.\n for (Set<String> blocks : blocked.values()) {\n total += numAvailable[blocks.size()];\n }\n \n return total;\n }\n}\n``` | 4 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
[Greedy] Constant space | cinema-seat-allocation | 0 | 1 | # Intuition\nNegate the rows one by one\n\n\n# Approach\n1. The maximum possile 4 person group that can sit in n rows are 2*n which is when no seat is reserved (2 4-person groups per row).\n1. Sort the seats so we can parse reserved seats of a single row together.\n2. Rules to negate:\n - If both isle2left and isle2right are reserved, then no 4 person group can be seated.\n - If isle1 and isle2right or isle2left and isle3 are reserved then again no 4 person group can be seated in this row.\n - If neither of the above 2 conditions are true then we check if atleast one of the 4 isles are booked. If yes, then only 1 4 person group can be seated.\n3. Once we have parsed all the reserved seats we return our result.\n\n# Complexity\n- Time complexity:\n$$O(KlogK)$$ *where K is length of reserved seats*\n\n- Space complexity:\n$$O(1)$$\n\n***If this was helpful, do upvote : )***\n\n# Code\n```\nclass Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n res = n*2\n j=0\n reservedSeats.sort()\n\n while j<len(reservedSeats):\n cur_row = reservedSeats[j][0]\n isle1,isle2left,isle2right,isle3=False,False,False,False\n while j<len(reservedSeats) and reservedSeats[j][0]==cur_row:\n seat = reservedSeats[j][1]\n if seat==2 or seat==3: isle1=True\n elif seat==4 or seat==5: isle2left=True\n elif seat==6 or seat==7: isle2right=True\n elif seat==8 or seat==9: isle3=True\n j+=1\n \n if (isle1 and isle2right)or(isle3 and isle2left)or(isle2left and isle2right):\n res-=2\n elif isle1 or isle2left or isle2right or isle3:\n res-=1\n\n return res\n``` | 5 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved.
_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
**Example 1:**
**Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\]
**Output:** 4
**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
**Example 2:**
**Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\]
**Output:** 2
**Example 3:**
**Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 10^9`
* `1 <= reservedSeats.length <= min(10*n, 10^4)`
* `reservedSeats[i].length == 2`
* `1 <= reservedSeats[i][0] <= n`
* `1 <= reservedSeats[i][1] <= 10`
* All `reservedSeats[i]` are distinct. | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
[Greedy] Constant space | cinema-seat-allocation | 0 | 1 | # Intuition\nNegate the rows one by one\n\n\n# Approach\n1. The maximum possile 4 person group that can sit in n rows are 2*n which is when no seat is reserved (2 4-person groups per row).\n1. Sort the seats so we can parse reserved seats of a single row together.\n2. Rules to negate:\n - If both isle2left and isle2right are reserved, then no 4 person group can be seated.\n - If isle1 and isle2right or isle2left and isle3 are reserved then again no 4 person group can be seated in this row.\n - If neither of the above 2 conditions are true then we check if atleast one of the 4 isles are booked. If yes, then only 1 4 person group can be seated.\n3. Once we have parsed all the reserved seats we return our result.\n\n# Complexity\n- Time complexity:\n$$O(KlogK)$$ *where K is length of reserved seats*\n\n- Space complexity:\n$$O(1)$$\n\n***If this was helpful, do upvote : )***\n\n# Code\n```\nclass Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n res = n*2\n j=0\n reservedSeats.sort()\n\n while j<len(reservedSeats):\n cur_row = reservedSeats[j][0]\n isle1,isle2left,isle2right,isle3=False,False,False,False\n while j<len(reservedSeats) and reservedSeats[j][0]==cur_row:\n seat = reservedSeats[j][1]\n if seat==2 or seat==3: isle1=True\n elif seat==4 or seat==5: isle2left=True\n elif seat==6 or seat==7: isle2right=True\n elif seat==8 or seat==9: isle3=True\n j+=1\n \n if (isle1 and isle2right)or(isle3 and isle2left)or(isle2left and isle2right):\n res-=2\n elif isle1 or isle2left or isle2right or isle3:\n res-=1\n\n return res\n``` | 5 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python simplest solution with explanations - faster than 90% | cinema-seat-allocation | 0 | 1 | **Like it? please upvote...**\n```\nclass Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n res = 0\n rows = defaultdict(list)\n # store in dict a list of seat numbers for each row:\n for seat in reservedSeats:\n rows[seat[0]].append(seat[1])\n \n for row in rows.keys():\n seat_nums = rows[row]\n \n # if there is only one reserved chair, there are two options:\n if len(seat_nums) == 1:\n res = res+2 if seat_nums[0] in [1, 10] else res+1\n \n else:\n\t\t\t\t# help list to find reserved seats in current row:\n help_list = [0]*10\n for seat in seat_nums:\n help_list[seat-1] = 1\n \n res_copy = res\n if help_list[1:5] == [0,0,0,0]: res+=1\n \n if help_list[5:9] == [0,0,0,0]: res+=1\n\n if res_copy == res and help_list[3:7] == [0,0,0,0]: res+=1\n\n # add two to res for each empty row\n return res + 2 * (n-len(rows.keys()))\n \n``` | 11 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved.
_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
**Example 1:**
**Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\]
**Output:** 4
**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
**Example 2:**
**Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\]
**Output:** 2
**Example 3:**
**Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 10^9`
* `1 <= reservedSeats.length <= min(10*n, 10^4)`
* `reservedSeats[i].length == 2`
* `1 <= reservedSeats[i][0] <= n`
* `1 <= reservedSeats[i][1] <= 10`
* All `reservedSeats[i]` are distinct. | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
Python simplest solution with explanations - faster than 90% | cinema-seat-allocation | 0 | 1 | **Like it? please upvote...**\n```\nclass Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n res = 0\n rows = defaultdict(list)\n # store in dict a list of seat numbers for each row:\n for seat in reservedSeats:\n rows[seat[0]].append(seat[1])\n \n for row in rows.keys():\n seat_nums = rows[row]\n \n # if there is only one reserved chair, there are two options:\n if len(seat_nums) == 1:\n res = res+2 if seat_nums[0] in [1, 10] else res+1\n \n else:\n\t\t\t\t# help list to find reserved seats in current row:\n help_list = [0]*10\n for seat in seat_nums:\n help_list[seat-1] = 1\n \n res_copy = res\n if help_list[1:5] == [0,0,0,0]: res+=1\n \n if help_list[5:9] == [0,0,0,0]: res+=1\n\n if res_copy == res and help_list[3:7] == [0,0,0,0]: res+=1\n\n # add two to res for each empty row\n return res + 2 * (n-len(rows.keys()))\n \n``` | 11 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
python solution, beats 70% and 90% respectively | cinema-seat-allocation | 0 | 1 | ```\nd = dict()\nl = 0\nfor i, j in reservedSeats:\n\tif(i not in d):\n\t\td[i] = 1<<(j-1)\n\t\tl += 1\n\telse:\n\t\td[i] = d[i] | 1<<(j-1)\nans = 2 * (n-l)\nfor index in d:\n\ti = d[index]\n\tt1 = (i>>5) & 15\n\tt2 = (i>>1) & 15\n\tif(t1 * t2 == 0):\n\t\tans += 1 + int(t1 + t2 == 0)\n\telse:\n\t\ttemp = (i>>3) & 15\n\t\tans += int(temp == 0)\nreturn ans\n```\n \n | 1 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved.
_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
**Example 1:**
**Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\]
**Output:** 4
**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
**Example 2:**
**Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\]
**Output:** 2
**Example 3:**
**Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 10^9`
* `1 <= reservedSeats.length <= min(10*n, 10^4)`
* `reservedSeats[i].length == 2`
* `1 <= reservedSeats[i][0] <= n`
* `1 <= reservedSeats[i][1] <= 10`
* All `reservedSeats[i]` are distinct. | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
python solution, beats 70% and 90% respectively | cinema-seat-allocation | 0 | 1 | ```\nd = dict()\nl = 0\nfor i, j in reservedSeats:\n\tif(i not in d):\n\t\td[i] = 1<<(j-1)\n\t\tl += 1\n\telse:\n\t\td[i] = d[i] | 1<<(j-1)\nans = 2 * (n-l)\nfor index in d:\n\ti = d[index]\n\tt1 = (i>>5) & 15\n\tt2 = (i>>1) & 15\n\tif(t1 * t2 == 0):\n\t\tans += 1 + int(t1 + t2 == 0)\n\telse:\n\t\ttemp = (i>>3) & 15\n\t\tans += int(temp == 0)\nreturn ans\n```\n \n | 1 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Easy | Python Solution | Hashmaps | sort-integers-by-the-power-value | 0 | 1 | # Code\n```\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n def getPow(num, ans):\n if num == 1:\n return ans\n if num % 2 == 0:\n num = num // 2\n else:\n num = 3 * num + 1\n ans += 1\n return getPow(num, ans)\n maps = {i:getPow(i, 0) for i in range(lo, hi+1)}\n ans = [k for k, v in sorted(maps.items(), key=lambda a:a[1])]\n return ans[k-1]\n\n``` | 1 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Easy | Python Solution | Hashmaps | sort-integers-by-the-power-value | 0 | 1 | # Code\n```\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n def getPow(num, ans):\n if num == 1:\n return ans\n if num % 2 == 0:\n num = num // 2\n else:\n num = 3 * num + 1\n ans += 1\n return getPow(num, ans)\n maps = {i:getPow(i, 0) for i in range(lo, hi+1)}\n ans = [k for k, v in sorted(maps.items(), key=lambda a:a[1])]\n return ans[k-1]\n\n``` | 1 | Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1. Implement the FindElements class: | Use DFS to traverse the binary tree and recover it. Use a hashset to store TreeNode.val for finding. |
Runtime 887 ms Beats 29.79%, Memory 16.4 MB Beats 87.38% | sort-integers-by-the-power-value | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the k-th number in a sequence generated using a specific rule.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach in the given code is to iterate through the range from `lo` to `hi` (inclusive). For each number `i` in the range, a power value is calculated based on a specific rule. The rule states that if `i` is even, it is divided by 2 and the power value is incremented by 1. If `i` is odd, it is multiplied by 3 and 1 is added, and the power value is incremented by 1. The power values for all numbers in the range are stored in a dictionary.\n\nAfter calculating the power values, the dictionary is sorted based on the power values in ascending order. Finally, the k-th element in the sorted list is returned as the result.\n\n# Complexity\n- Time complexity: O((`hi` - `lo` + 1) * log(`hi` - `lo` + 1)), where `hi` and `lo` are the given input numbers. The code iterates through the range from `lo` to `hi` and sorts the power values dictionary, which takes additional log(hi - lo + 1) time complexity.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(hi - lo), where hi and lo are the given input numbers. The code stores the power values in a dictionary, which can have at most `hi` - `lo` + 1 elements.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n power_values = {}\n for i in range(lo,hi+1):\n \n x=i\n power = 0\n while x!=1:\n if x%2==0:\n x = x / 2\n power += 1\n else:\n x = 3 * x + 1\n power += 1\n power_values[i]=power\n sort_power_values = sorted(power_values.items(), key=lambda x:x[1])\n return sort_power_values[k-1][0]\n``` | 1 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Runtime 887 ms Beats 29.79%, Memory 16.4 MB Beats 87.38% | sort-integers-by-the-power-value | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the k-th number in a sequence generated using a specific rule.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach in the given code is to iterate through the range from `lo` to `hi` (inclusive). For each number `i` in the range, a power value is calculated based on a specific rule. The rule states that if `i` is even, it is divided by 2 and the power value is incremented by 1. If `i` is odd, it is multiplied by 3 and 1 is added, and the power value is incremented by 1. The power values for all numbers in the range are stored in a dictionary.\n\nAfter calculating the power values, the dictionary is sorted based on the power values in ascending order. Finally, the k-th element in the sorted list is returned as the result.\n\n# Complexity\n- Time complexity: O((`hi` - `lo` + 1) * log(`hi` - `lo` + 1)), where `hi` and `lo` are the given input numbers. The code iterates through the range from `lo` to `hi` and sorts the power values dictionary, which takes additional log(hi - lo + 1) time complexity.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(hi - lo), where hi and lo are the given input numbers. The code stores the power values in a dictionary, which can have at most `hi` - `lo` + 1 elements.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n power_values = {}\n for i in range(lo,hi+1):\n \n x=i\n power = 0\n while x!=1:\n if x%2==0:\n x = x / 2\n power += 1\n else:\n x = 3 * x + 1\n power += 1\n power_values[i]=power\n sort_power_values = sorted(power_values.items(), key=lambda x:x[1])\n return sort_power_values[k-1][0]\n``` | 1 | Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1. Implement the FindElements class: | Use DFS to traverse the binary tree and recover it. Use a hashset to store TreeNode.val for finding. |
easy python | sort-integers-by-the-power-value | 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 po(self,x):\n if(x==1):\n return(0)\n a=0\n if(x%2==0):\n a=self.po(x//2)\n else:\n a=self.po(x*3+1)\n return(a+1)\n def getKth(self, lo: int, hi: int, k: int) -> int:\n ot=[]\n for i in range(lo,hi+1):\n ot.append([i,self.po(i)])\n newara=sorted(ot, key = lambda x:x[1])\n return(newara[k-1][0])\n``` | 1 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
easy python | sort-integers-by-the-power-value | 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 po(self,x):\n if(x==1):\n return(0)\n a=0\n if(x%2==0):\n a=self.po(x//2)\n else:\n a=self.po(x*3+1)\n return(a+1)\n def getKth(self, lo: int, hi: int, k: int) -> int:\n ot=[]\n for i in range(lo,hi+1):\n ot.append([i,self.po(i)])\n newara=sorted(ot, key = lambda x:x[1])\n return(newara[k-1][0])\n``` | 1 | Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1. Implement the FindElements class: | Use DFS to traverse the binary tree and recover it. Use a hashset to store TreeNode.val for finding. |
Python Elegant & Short | 99.3% faster | 4 lines | sorting + lru_cache | sort-integers-by-the-power-value | 0 | 1 | \n\n def getKth(self, lo: int, hi: int, k: int) -> int:\n return sorted(range(lo, hi + 1), key=self.power)[k - 1]\n\n @classmethod\n @lru_cache(maxsize=None)\n def power(cls, n: int) -> int:\n if n == 1:\n return 1\n return cls.power(3*n + 1 if n & 1 else n >> 1) + 1\n | 4 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Python Elegant & Short | 99.3% faster | 4 lines | sorting + lru_cache | sort-integers-by-the-power-value | 0 | 1 | \n\n def getKth(self, lo: int, hi: int, k: int) -> int:\n return sorted(range(lo, hi + 1), key=self.power)[k - 1]\n\n @classmethod\n @lru_cache(maxsize=None)\n def power(cls, n: int) -> int:\n if n == 1:\n return 1\n return cls.power(3*n + 1 if n & 1 else n >> 1) + 1\n | 4 | Given a binary tree with the following rules: Now the binary tree is contaminated, which means all treeNode.val have been changed to -1. Implement the FindElements class: | Use DFS to traverse the binary tree and recover it. Use a hashset to store TreeNode.val for finding. |
O(N) time and space commented and explained | pizza-with-3n-slices | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom the hints where it is stated that the first in the array is next to the last in the array we can actually consider the problem as a divide and conquer of size 1. Our division is on the end and the front of the array. We can consider the case where we start from 1 instead of zero and go to the end, thus not touching the zero slice, and we can consider the case going from start until just before the end. This reduces our complexity greatly. \n\nThen, we can consider just what it will mean to have a fair split of 3n slices. This actually means we can shift our focus down to only sizes of num slices // 3, reducing our state to 167 at most (slices length is at most 500). This lets us utilize a fairly expensive bottom up approach for much less than if we had to do so with the 500 instead. \n\nFinally, as each current dpa array only depends on the prior array, we can reduce our state from n * fair split to just n, thus giving our final space saving needed. \n\nIn total then our process is \n1. determine the total number of slices \n2. determine the fair split (num slices // 3) \n3. set up previous and current dpa of size of fair split + 1 of 0 to start\n4. consider case from 1 forward to end of slices \n5. determine next dpa as [0] + [max(current state, prior state + this slice for selection in range 1 to fair split + 1)]\n6. set prior and current to current and next \n7. the final candidate in current is the first candidate for maximum sum of slice sizes \n8. conduct 3-7 with case of 0 to second to last slice inclusive as case 2\n9. return max of candidate 1 and candidate 2 \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet num slices = len of slices \nSet fair split as num slices // 3 \nset up a previous dpa and current dpa as [0] * (fair split + 1)\nloop over each slice_i in slices[1:] \n- build next dpa as [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split+1)]\n- set previous dpa, current dpa to current dpa, next dpa \ncandidate 1 is current dpa at fair split \nreset previous and current dpa \nloop over each slice_i in slices[:-1]\n- build next dpa as [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split+1)]\n- set previous dpa, current dpa to current dpa, next dpa \ncandidate 2 is current dpa at fair split \n\nreturn max of candidate 1 and candidate 2 \n\n# Complexity\n- Time complexity : O(N) \n - fair split runs in time n to build previous and current dpa\n - next dpa runs in time n to build next dpa \n - slice loops run in time 3n to go over all slices \n - within which you do work of size n for next dpa \n - we do two slice loops \n - So total is (3n * n ) * 2 = 8n = n \n\n- Space complexity : O(N) \n - previous, current, and next dpa all take space N \n\n# Code\n```\nclass Solution:\n def maxSizeSlices(self, slices: List[int]) -> int :\n # determine the number of slices \n num_slices = len(slices)\n # and the amount for a fair split of 3n \n fair_split = num_slices//3\n # set up a dpa previous and current \n previous_dpa = [0]*(fair_split + 1)\n current_dpa = [0]*(fair_split + 1)\n # process from slice 1 forward \n for slice_i in slices[1:] : \n # determine next appropriately as current value or prior + this slice for state in range 1 to fair split + 1\n next_dpa = [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split + 1)]\n # prior and current are now current and next \n previous_dpa, current_dpa = current_dpa, next_dpa\n # slot in candidate 1 found when going from 1 forward to the end \n candidate_1 = current_dpa[fair_split]\n # reset \n previous_dpa = [0]*(fair_split + 1)\n current_dpa = [0]*(fair_split + 1)\n # process from slice i up to but not including final slice \n for slice_i in slices[:-1] : \n # determine next appropriately as current value or prior value + this slice in range \n next_dpa = [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split + 1)]\n # update previous and current to current and next respectively \n previous_dpa, current_dpa = current_dpa, next_dpa\n # slot in candidate 2 found when going up to but not at the last item \n candidate_2 = current_dpa[fair_split]\n # take the best of both worlds \n return max(candidate_1, candidate_2) \n``` | 1 | There is a pizza with `3n` slices of varying size, you and your friends will take slices of pizza as follows:
* You will pick **any** pizza slice.
* Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
* Your friend Bob will pick the next slice in the clockwise direction of your pick.
* Repeat until there are no more slices of pizzas.
Given an integer array `slices` that represent the sizes of the pizza slices in a clockwise direction, return _the maximum possible sum of slice sizes that you can pick_.
**Example 1:**
**Input:** slices = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
**Example 2:**
**Input:** slices = \[8,9,8,6,1,1\]
**Output:** 16
**Explanation:** Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
**Constraints:**
* `3 * n == slices.length`
* `1 <= slices.length <= 500`
* `1 <= slices[i] <= 1000` | Represent the state as DP[pos][mod]: maximum possible sum starting in the position "pos" in the array where the current sum modulo 3 is equal to mod. |
O(N) time and space commented and explained | pizza-with-3n-slices | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom the hints where it is stated that the first in the array is next to the last in the array we can actually consider the problem as a divide and conquer of size 1. Our division is on the end and the front of the array. We can consider the case where we start from 1 instead of zero and go to the end, thus not touching the zero slice, and we can consider the case going from start until just before the end. This reduces our complexity greatly. \n\nThen, we can consider just what it will mean to have a fair split of 3n slices. This actually means we can shift our focus down to only sizes of num slices // 3, reducing our state to 167 at most (slices length is at most 500). This lets us utilize a fairly expensive bottom up approach for much less than if we had to do so with the 500 instead. \n\nFinally, as each current dpa array only depends on the prior array, we can reduce our state from n * fair split to just n, thus giving our final space saving needed. \n\nIn total then our process is \n1. determine the total number of slices \n2. determine the fair split (num slices // 3) \n3. set up previous and current dpa of size of fair split + 1 of 0 to start\n4. consider case from 1 forward to end of slices \n5. determine next dpa as [0] + [max(current state, prior state + this slice for selection in range 1 to fair split + 1)]\n6. set prior and current to current and next \n7. the final candidate in current is the first candidate for maximum sum of slice sizes \n8. conduct 3-7 with case of 0 to second to last slice inclusive as case 2\n9. return max of candidate 1 and candidate 2 \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet num slices = len of slices \nSet fair split as num slices // 3 \nset up a previous dpa and current dpa as [0] * (fair split + 1)\nloop over each slice_i in slices[1:] \n- build next dpa as [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split+1)]\n- set previous dpa, current dpa to current dpa, next dpa \ncandidate 1 is current dpa at fair split \nreset previous and current dpa \nloop over each slice_i in slices[:-1]\n- build next dpa as [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split+1)]\n- set previous dpa, current dpa to current dpa, next dpa \ncandidate 2 is current dpa at fair split \n\nreturn max of candidate 1 and candidate 2 \n\n# Complexity\n- Time complexity : O(N) \n - fair split runs in time n to build previous and current dpa\n - next dpa runs in time n to build next dpa \n - slice loops run in time 3n to go over all slices \n - within which you do work of size n for next dpa \n - we do two slice loops \n - So total is (3n * n ) * 2 = 8n = n \n\n- Space complexity : O(N) \n - previous, current, and next dpa all take space N \n\n# Code\n```\nclass Solution:\n def maxSizeSlices(self, slices: List[int]) -> int :\n # determine the number of slices \n num_slices = len(slices)\n # and the amount for a fair split of 3n \n fair_split = num_slices//3\n # set up a dpa previous and current \n previous_dpa = [0]*(fair_split + 1)\n current_dpa = [0]*(fair_split + 1)\n # process from slice 1 forward \n for slice_i in slices[1:] : \n # determine next appropriately as current value or prior + this slice for state in range 1 to fair split + 1\n next_dpa = [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split + 1)]\n # prior and current are now current and next \n previous_dpa, current_dpa = current_dpa, next_dpa\n # slot in candidate 1 found when going from 1 forward to the end \n candidate_1 = current_dpa[fair_split]\n # reset \n previous_dpa = [0]*(fair_split + 1)\n current_dpa = [0]*(fair_split + 1)\n # process from slice i up to but not including final slice \n for slice_i in slices[:-1] : \n # determine next appropriately as current value or prior value + this slice in range \n next_dpa = [0] + [max(current_dpa[j], previous_dpa[j-1] + slice_i) for j in range(1, fair_split + 1)]\n # update previous and current to current and next respectively \n previous_dpa, current_dpa = current_dpa, next_dpa\n # slot in candidate 2 found when going up to but not at the last item \n candidate_2 = current_dpa[fair_split]\n # take the best of both worlds \n return max(candidate_1, candidate_2) \n``` | 1 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Easy to understand for beginners #easiest | create-target-array-in-the-given-order | 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. -->\nI just followed the question. We want target array of length of nums.\nthen want to put nums on index. I used insert(index_to_insert, element_to_insert)\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 createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n ls =[] \n for i in range(len(nums)):\n ls.insert(index[i],nums[i])\n return ls\n \n``` | 1 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "
**Explanation:** The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
**Example 2:**
**Input:** num = "100 ", k = 1
**Output:** "010 "
**Explanation:** It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
**Example 3:**
**Input:** num = "36789 ", k = 1000
**Output:** "36789 "
**Explanation:** We can keep the number without any swaps.
**Constraints:**
* `1 <= num.length <= 3 * 104`
* `num` consists of only **digits** and does not contain **leading zeros**.
* `1 <= k <= 109` | Simulate the process and fill corresponding numbers in the designated spots. |
Easy to understand for beginners #easiest | create-target-array-in-the-given-order | 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. -->\nI just followed the question. We want target array of length of nums.\nthen want to put nums on index. I used insert(index_to_insert, element_to_insert)\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 createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n ls =[] \n for i in range(len(nums)):\n ls.insert(index[i],nums[i])\n return ls\n \n``` | 1 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. | We represent the search state as (player_row, player_col, box_row, box_col). You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player. |
Python | Using insert and without insert | very Easy | create-target-array-in-the-given-order | 0 | 1 | Note:-*If you have any doubt, Free to ask me, Please **Upvote** if you like it.*\n##### **Read comments for better understanding**\n**With insert**\n```\n arr=[]\n for n,i in zip(nums,index): \n arr.insert(i,n)\n return arr\n```\n**Without insert**\n```\n arr = []\n for n,i in zip(nums,index): \n arr[i:i] = [n]\n return arr\n``` | 119 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "
**Explanation:** The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
**Example 2:**
**Input:** num = "100 ", k = 1
**Output:** "010 "
**Explanation:** It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
**Example 3:**
**Input:** num = "36789 ", k = 1000
**Output:** "36789 "
**Explanation:** We can keep the number without any swaps.
**Constraints:**
* `1 <= num.length <= 3 * 104`
* `num` consists of only **digits** and does not contain **leading zeros**.
* `1 <= k <= 109` | Simulate the process and fill corresponding numbers in the designated spots. |
Python | Using insert and without insert | very Easy | create-target-array-in-the-given-order | 0 | 1 | Note:-*If you have any doubt, Free to ask me, Please **Upvote** if you like it.*\n##### **Read comments for better understanding**\n**With insert**\n```\n arr=[]\n for n,i in zip(nums,index): \n arr.insert(i,n)\n return arr\n```\n**Without insert**\n```\n arr = []\n for n,i in zip(nums,index): \n arr[i:i] = [n]\n return arr\n``` | 119 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. | We represent the search state as (player_row, player_col, box_row, box_col). You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player. |
Runtime 38 ms || Beats 60.14% || Create Target Array in the Given Order | create-target-array-in-the-given-order | 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 createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n target=[]\n j=0\n for i in index:\n target.insert(i,nums[j])\n j+=1\n return target\n``` | 1 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "
**Explanation:** The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
**Example 2:**
**Input:** num = "100 ", k = 1
**Output:** "010 "
**Explanation:** It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
**Example 3:**
**Input:** num = "36789 ", k = 1000
**Output:** "36789 "
**Explanation:** We can keep the number without any swaps.
**Constraints:**
* `1 <= num.length <= 3 * 104`
* `num` consists of only **digits** and does not contain **leading zeros**.
* `1 <= k <= 109` | Simulate the process and fill corresponding numbers in the designated spots. |
Runtime 38 ms || Beats 60.14% || Create Target Array in the Given Order | create-target-array-in-the-given-order | 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 createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n target=[]\n j=0\n for i in index:\n target.insert(i,nums[j])\n j+=1\n return target\n``` | 1 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. | We represent the search state as (player_row, player_col, box_row, box_col). You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player. |
Very easy | create-target-array-in-the-given-order | 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 createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n l=[]\n for i,j in zip(nums,index):\n l.insert(j,i)\n return l \n \n``` | 1 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "
**Explanation:** The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
**Example 2:**
**Input:** num = "100 ", k = 1
**Output:** "010 "
**Explanation:** It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
**Example 3:**
**Input:** num = "36789 ", k = 1000
**Output:** "36789 "
**Explanation:** We can keep the number without any swaps.
**Constraints:**
* `1 <= num.length <= 3 * 104`
* `num` consists of only **digits** and does not contain **leading zeros**.
* `1 <= k <= 109` | Simulate the process and fill corresponding numbers in the designated spots. |
Very easy | create-target-array-in-the-given-order | 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 createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n l=[]\n for i,j in zip(nums,index):\n l.insert(j,i)\n return l \n \n``` | 1 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. | We represent the search state as (player_row, player_col, box_row, box_col). You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player. |
Easy Python Solution - Explained! | create-target-array-in-the-given-order | 0 | 1 | \n# Code\n```\nclass Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n # Initialize an empty list to store the target array\n target = []\n # Iterate through each element in the input lists\n for i in range(len(nums)):\n # Check if the index value matches the current length of the target list\n if index[i] == len(target):\n # If the index is at the end, simply append the current number to the target\n target.append(nums[i])\n else:\n # If the index is not at the end, insert the current number at the specified index\n # This is done by slicing the target list and inserting the number in the middle\n target = target[:index[i]] + [nums[i]] + target[index[i]:]\n # Return the final target array\n return target\n\n``` | 3 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "
**Explanation:** The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
**Example 2:**
**Input:** num = "100 ", k = 1
**Output:** "010 "
**Explanation:** It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
**Example 3:**
**Input:** num = "36789 ", k = 1000
**Output:** "36789 "
**Explanation:** We can keep the number without any swaps.
**Constraints:**
* `1 <= num.length <= 3 * 104`
* `num` consists of only **digits** and does not contain **leading zeros**.
* `1 <= k <= 109` | Simulate the process and fill corresponding numbers in the designated spots. |
Easy Python Solution - Explained! | create-target-array-in-the-given-order | 0 | 1 | \n# Code\n```\nclass Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n # Initialize an empty list to store the target array\n target = []\n # Iterate through each element in the input lists\n for i in range(len(nums)):\n # Check if the index value matches the current length of the target list\n if index[i] == len(target):\n # If the index is at the end, simply append the current number to the target\n target.append(nums[i])\n else:\n # If the index is not at the end, insert the current number at the specified index\n # This is done by slicing the target list and inserting the number in the middle\n target = target[:index[i]] + [nums[i]] + target[index[i]:]\n # Return the final target array\n return target\n\n``` | 3 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. | We represent the search state as (player_row, player_col, box_row, box_col). You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player. |
Python - Using insert() and without insert() | create-target-array-in-the-given-order | 0 | 1 | **Using the insert function:**\n\n```\nclass Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n target =[]\n for i in range(len(nums)):\n target.insert(index[i], nums[i])\n return target\n```\n\n**Without using the insert function:**\n```\nclass Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n target =[]\n for i in range(len(nums)):\n if index[i] == len(target) :\n target.append(nums[i])\n else:\n target = target[:index[i]] + [nums[i]] + target[index[i]:]\n return target\n```\n | 40 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "
**Explanation:** The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.
**Example 2:**
**Input:** num = "100 ", k = 1
**Output:** "010 "
**Explanation:** It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.
**Example 3:**
**Input:** num = "36789 ", k = 1000
**Output:** "36789 "
**Explanation:** We can keep the number without any swaps.
**Constraints:**
* `1 <= num.length <= 3 * 104`
* `num` consists of only **digits** and does not contain **leading zeros**.
* `1 <= k <= 109` | Simulate the process and fill corresponding numbers in the designated spots. |
Python - Using insert() and without insert() | create-target-array-in-the-given-order | 0 | 1 | **Using the insert function:**\n\n```\nclass Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n target =[]\n for i in range(len(nums)):\n target.insert(index[i], nums[i])\n return target\n```\n\n**Without using the insert function:**\n```\nclass Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n target =[]\n for i in range(len(nums)):\n if index[i] == len(target) :\n target.append(nums[i])\n else:\n target = target[:index[i]] + [nums[i]] + target[index[i]:]\n return target\n```\n | 40 | A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box. Your task is to move the box 'B' to the target position 'T' under the following rules: Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1. | We represent the search state as (player_row, player_col, box_row, box_col). You need to count only the number of pushes. Then inside of your BFS check if the box could be pushed (in any direction) given the current position of the player. |
[Python3] Short Easy Solution | four-divisors | 0 | 1 | ```\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor = set() \n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divisor.add(num//i)\n divisor.add(i)\n if len(divisor) > 4: \n break\n \n if len(divisor) == 4:\n res += sum(divisor)\n return res \n``` | 25 | Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`.
**Example 1:**
**Input:** nums = \[21,4,7\]
**Output:** 32
**Explanation:**
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
**Example 2:**
**Input:** nums = \[21,21\]
**Output:** 64
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 104`
* `1 <= nums[i] <= 105` | null |
[Python3] Short Easy Solution | four-divisors | 0 | 1 | ```\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor = set() \n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divisor.add(num//i)\n divisor.add(i)\n if len(divisor) > 4: \n break\n \n if len(divisor) == 4:\n res += sum(divisor)\n return res \n``` | 25 | Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge.
Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot.
A **binary matrix** is a matrix with all cells equal to `0` or `1` only.
A **zero matrix** is a matrix with all cells equal to `0`.
**Example 1:**
**Input:** mat = \[\[0,0\],\[0,1\]\]
**Output:** 3
**Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
**Example 2:**
**Input:** mat = \[\[0\]\]
**Output:** 0
**Explanation:** Given matrix is a zero matrix. We do not need to change it.
**Example 3:**
**Input:** mat = \[\[1,0,0\],\[1,0,0\]\]
**Output:** -1
**Explanation:** Given matrix cannot be a zero matrix.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 3`
* `mat[i][j]` is either `0` or `1`. | Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors. |
Simple Sieve of Eratosthenes Method | four-divisors | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThree Things to remeber- All odd numbers have only odd divisors, all perfect squares will have odd number of divisors, you are checking for four divisors (You know two of them already-one and the number itself)\nIam sure there will be better solutions, check them out but this can help you get started \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the number is a perfect square if yes move ahead,then check if the number is a even number or odd number -> if even you need to check both even and odd divisors and if odd you can simply check for odd divisors only\nThe Time and Space Complexity could be wrong please feel free to correct me in the comments IAM STILL LEARNING \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(len(nums)*\u221AM) M being the hightest element in the list\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) we are using constanst time \n\n# Code\n```\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n sum1=0\n for i in range(len(nums)):\n if (nums[i]**0.5)==int(nums[i]**0.5):\n continue\n elif nums[i]%2==0:\n counter=0\n sum2=0\n for j in range(2,int(nums[i]**0.5)+1):\n if counter>2:\n break\n elif nums[i]%j==0:\n counter+=1\n kekw=nums[i]//j\n sum2=sum2+j\n if counter==1:\n sum2=sum2+kekw\n sum1=sum1+sum2+1+nums[i]\n else:\n counter=0\n sum3=0\n for j in range(3,int(nums[i]**0.5)+1,2):\n if counter>2:\n break\n elif nums[i]%j==0:\n counter+=1\n kekw=nums[i]//j\n sum3=sum3+j\n if counter==1:\n sum3=sum3+kekw\n sum1=sum1+sum3+1+nums[i]\n return sum1\n``` | 0 | Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`.
**Example 1:**
**Input:** nums = \[21,4,7\]
**Output:** 32
**Explanation:**
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
**Example 2:**
**Input:** nums = \[21,21\]
**Output:** 64
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 104`
* `1 <= nums[i] <= 105` | null |
Simple Sieve of Eratosthenes Method | four-divisors | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThree Things to remeber- All odd numbers have only odd divisors, all perfect squares will have odd number of divisors, you are checking for four divisors (You know two of them already-one and the number itself)\nIam sure there will be better solutions, check them out but this can help you get started \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the number is a perfect square if yes move ahead,then check if the number is a even number or odd number -> if even you need to check both even and odd divisors and if odd you can simply check for odd divisors only\nThe Time and Space Complexity could be wrong please feel free to correct me in the comments IAM STILL LEARNING \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(len(nums)*\u221AM) M being the hightest element in the list\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) we are using constanst time \n\n# Code\n```\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n sum1=0\n for i in range(len(nums)):\n if (nums[i]**0.5)==int(nums[i]**0.5):\n continue\n elif nums[i]%2==0:\n counter=0\n sum2=0\n for j in range(2,int(nums[i]**0.5)+1):\n if counter>2:\n break\n elif nums[i]%j==0:\n counter+=1\n kekw=nums[i]//j\n sum2=sum2+j\n if counter==1:\n sum2=sum2+kekw\n sum1=sum1+sum2+1+nums[i]\n else:\n counter=0\n sum3=0\n for j in range(3,int(nums[i]**0.5)+1,2):\n if counter>2:\n break\n elif nums[i]%j==0:\n counter+=1\n kekw=nums[i]//j\n sum3=sum3+j\n if counter==1:\n sum3=sum3+kekw\n sum1=sum1+sum3+1+nums[i]\n return sum1\n``` | 0 | Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge.
Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot.
A **binary matrix** is a matrix with all cells equal to `0` or `1` only.
A **zero matrix** is a matrix with all cells equal to `0`.
**Example 1:**
**Input:** mat = \[\[0,0\],\[0,1\]\]
**Output:** 3
**Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
**Example 2:**
**Input:** mat = \[\[0\]\]
**Output:** 0
**Explanation:** Given matrix is a zero matrix. We do not need to change it.
**Example 3:**
**Input:** mat = \[\[1,0,0\],\[1,0,0\]\]
**Output:** -1
**Explanation:** Given matrix cannot be a zero matrix.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 3`
* `mat[i][j]` is either `0` or `1`. | Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors. |
Python Easy Solution | four-divisors | 0 | 1 | # Code\n```\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n \n main_sum = 0\n\n for num in nums: #loop over list to find divisors\n divisor = 0\n\n for var in range(2,int(sqrt(num))+1): #basic way to find divisor of a number\n if num % var == 0:\n if divisor == 0:\n divisor = var\n else:\n divisor = 0\n break\n if divisor > 0 and divisor * divisor < num:\n main_sum += 1 + num + divisor + num//divisor\n\n return main_sum\n``` | 0 | Given an integer array `nums`, return _the sum of divisors of the integers in that array that have exactly four divisors_. If there is no such integer in the array, return `0`.
**Example 1:**
**Input:** nums = \[21,4,7\]
**Output:** 32
**Explanation:**
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answer is the sum of divisors of 21 only.
**Example 2:**
**Input:** nums = \[21,21\]
**Output:** 64
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 104`
* `1 <= nums[i] <= 105` | null |
Python Easy Solution | four-divisors | 0 | 1 | # Code\n```\nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n \n main_sum = 0\n\n for num in nums: #loop over list to find divisors\n divisor = 0\n\n for var in range(2,int(sqrt(num))+1): #basic way to find divisor of a number\n if num % var == 0:\n if divisor == 0:\n divisor = var\n else:\n divisor = 0\n break\n if divisor > 0 and divisor * divisor < num:\n main_sum += 1 + num + divisor + num//divisor\n\n return main_sum\n``` | 0 | Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge.
Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot.
A **binary matrix** is a matrix with all cells equal to `0` or `1` only.
A **zero matrix** is a matrix with all cells equal to `0`.
**Example 1:**
**Input:** mat = \[\[0,0\],\[0,1\]\]
**Output:** 3
**Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.
**Example 2:**
**Input:** mat = \[\[0\]\]
**Output:** 0
**Explanation:** Given matrix is a zero matrix. We do not need to change it.
**Example 3:**
**Input:** mat = \[\[1,0,0\],\[1,0,0\]\]
**Output:** -1
**Explanation:** Given matrix cannot be a zero matrix.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 3`
* `mat[i][j]` is either `0` or `1`. | Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.