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 ... | 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 a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
Python 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 ... | 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 =... | 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)$$ --... | 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 a... | You cannot do anything about colsum[i] = 2 case or colsum[i] = 0 case. Then you put colsum[i] = 1 case to the upper row until upper has reached. Then put the rest into lower row. Fill 0 and 2 first, then fill 1 in the upper row or lower row in turn but be careful about exhausting permitted 1s in each row. |
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)$$ --... | 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 =... | 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 us... | 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:*... | 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 us... | 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 ... | 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... | 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:*... | 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... | 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 ... | 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 li... | 1 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:*... | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
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 li... | 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 ... | 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 ... | 2 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:*... | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
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 ... | 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 ... | 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 re... | 1 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:*... | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
Python 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 re... | 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 ... | 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... | 2 | Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_.
A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column.
**Example 1:**
**Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\]
**Output:*... | Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid. |
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... | 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 ... | 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:*... | 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 ... | 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(matr... | 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:*... | 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(matr... | 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 ... | 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 incremen... | 1 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max... | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
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 ... | 1 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max... | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
Python || 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... | 2 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max... | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
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... | 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 `max... | 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 `sel... | 1 | Design a stack that supports increment operations on its elements.
Implement the `CustomStack` class:
* `CustomStack(int maxSize)` Initializes the object with `maxSize` which is the maximum number of elements in the stack.
* `void push(int x)` Adds `x` to the top of the stack if the stack has not reached the `max... | Note that words.length is small. This means you can iterate over every subset of words (2^N). |
Very Simple Solution 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... | 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 ... | 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+righ... | 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 ... | 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... | 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 ... | 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 bala... | 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 ... | 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 balanceBS... | 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 ... | 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 ... | 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 ... | 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 be... | 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 ... | 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 ... | 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 ... | 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... | 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 ... | 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 ... | 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` en... | 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 ... | 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` ... | 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 -... | 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` en... | 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 -... | 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` ... | 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 R... | 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` en... | 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 R... | 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` ... | 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 ... | 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` en... | 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 ... | 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` ... | 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 constra... | 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` en... | 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 constra... | 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` ... | 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... | 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` en... | 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... | 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` ... | 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(... | 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... | 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... |
🔥[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(... | 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\] w... | 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/MAMuhammad... | 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... | 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... |
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/MAMuhammad... | 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\] w... | 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)-... | 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... | 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... |
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)-... | 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\] w... | 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``.... | 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... | 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... |
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``.... | 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\] w... | 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, vec... | 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... | 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... |
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, vec... | 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\] w... | 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 ... | 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... | 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... |
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 ... | 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\] w... | 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 ... | 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... | 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... |
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 ... | 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\] w... | 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 ... | 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... | 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... |
[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 ... | 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\] w... | 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 cinem... | 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... | 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 cinem... | 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 additio... | 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 \'le... | 4 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with... | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
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 \'le... | 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 additio... | 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... | 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... | 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... | 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 additio... | 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(se... | 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... | 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(se... | 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 additio... | 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\... | 1 | A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with... | Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way. |
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\... | 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 additio... | 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 ... | 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:
*... | 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 ... | 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` t... | 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:
*... | 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` t... | 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)$$ --... | 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:
*... | 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)$$ --... | 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:\... | 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:
*... | 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:\... | 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 ... | 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 yo... | 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 ... | 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 withou... | 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... |
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# Complexit... | 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 "... | 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# Complexit... | 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 th... | 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... | 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 "... | 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... | 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 th... | 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)$$ --... | 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 "... | 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)$$ --... | 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 th... | 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)$$ --... | 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 "... | 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)$$ --... | 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 th... | 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 i... | 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 "... | 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 i... | 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 th... | 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... | 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 "... | 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... | 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 th... | 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 ... | 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... | 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 ... | 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... | 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 bet... | 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... | 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 bet... | 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... | 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 %... | 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... | 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 %... | 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... | 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.