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 |
---|---|---|---|---|---|---|---|
Efficient Union Find using only water cells | Beats 100% | last-day-where-you-can-still-cross | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTop and bottom rows are connected via land if and only if the first and last columns are not connected via water. For this to hold water is considered to be connected in 8 directions because you can pass between land only in 4 directions. Thus index of `[i, j]` in `cells`, which completes this connection is the day number we look for.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe iterate over water `cells` merging them into disjoint-set with two additional\nnodes `left` and `right` added, which represent the edges of the grid. Instead of using `row`x`col` grid, we use dictionary to store flooded cells, that we check against for 8-way adjacency.\n\n# Complexity\n- Time complexity: $$O(\\alpha(cells))$$\n\n- Space complexity: $$O(cells)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n left = len(cells) \n right = left + 1\n parent = list(range(right + 1))\n rank = [0] * (right + 1)\n directions = [(i, j) for i in (0, -1, 1) for j in (0, -1, 1)][1:]\n\n def find(x):\n while parent[x] != x:\n x, parent[x] = parent[x], parent[parent[x]]\n return x\n\n def union(x, y):\n x, y = find(x), find(y)\n if x == y:\n return\n if rank[y] > rank[x]:\n x, y = y, x\n parent[y] = x\n if rank[x] == rank[y]:\n rank[x] += 1\n\n water = {} \n for idx, (i, j) in enumerate(cells):\n i -= 1\n j -= 1\n water[(i, j)] = idx\n if j == 0:\n union(left, idx)\n if j == col - 1:\n union(right, idx)\n for di, dj in directions:\n i2, j2 = i + di, j + dj\n if (i2, j2) in water:\n union(water[(i2, j2)], idx)\n if find(left) == find(right):\n return idx \n return idx + 1 \n``` | 3 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Python3 Solution | last-day-where-you-can-still-cross | 0 | 1 | \n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n n = row * col\n root, left, right = list(range(n)), [0] * n, [0] * n \n for i in range(col):\n for j in range(row):\n left[i * row + j] = i\n right[i * row + j] = i\n \n def find(x):\n if x != root[x]:\n root[x] = find(root[x])\n return root[x]\n def union(x, y):\n a, b = find(x), find(y)\n if a != b:\n root[a] = b\n left[b] = min(left[b], left[a]) \n right[b] = max(right[b], right[a])\n \n seen = set()\n dirs = ((1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (-1, 1), (1, -1), (-1, -1))\n for i, cell in enumerate(cells):\n cx, cy = cell[0] - 1, cell[1] - 1\n for dx, dy in dirs:\n x, y = cx + dx, cy + dy\n if 0 <= x < row and 0 <= y < col and (x, y) in seen:\n union(cy * row + cx, y * row + x)\n new = find(y * row + x)\n if left[new] == 0 and right[new] == col - 1:\n return i\n seen.add((cx, cy))\n return n\n``` | 2 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
python binary search with bfs | last-day-where-you-can-still-cross | 0 | 1 | ```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n \n cells = list(map(tuple, cells))\n \n def search(day):\n queue = deque([(1,i) for i in range(1, col+1)])\n visited = set(cells[:day])\n while queue:\n r, c = queue.popleft()\n if (r,c) in visited:\n continue\n visited.add((r, c))\n if not (1 <= r <= row and 1 <= c <= col):\n continue\n if r == row:\n return 0\n for dr, dc in ((0, 1), (1, 0), (-1, 0), (0, -1)):\n queue.append((r+dr, c+dc))\n return 1\n \n return bisect.bisect(range(1, len(cells)), 0, key=search)\n\n``` | 2 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
✅BS + BFS || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | last-day-where-you-can-still-cross | 1 | 1 | # Intuition:\n\nThe intuition behind the problem is to find the latest day where it is still possible to cross the grid by incrementally adding cells and checking if a path exists from the top row to the bottom row, utilizing binary search to optimize the search process.\n\n# Explanation:\n**Binary Search:**\n1. Initialize `left` as 0 (representing the earliest day) and `right` as `row * col` (representing the latest possible day).\n2. While `left` is less than `right - 1`, do the following:\n - Calculate the mid-day as `mid = (left + right) / 2`.\n - Check if it is possible to cross the grid on day `mid` by calling the `isPossible` function.\n - The `isPossible` function checks if it is possible to cross the grid by considering the first `mid` cells from the given list. It uses BFS to explore the grid and checks if the bottom row can be reached.\n - If it is possible to cross, update `left` to `mid` and store the latest possible day in a variable (let\'s call it `latestPossibleDay`).\n - If it is not possible to cross, update `right` to `mid`.\n3. Return `latestPossibleDay` as the latest day where it is still possible to cross the grid.\n\n**Breadth-First Search (BFS):**\nThe `isPossible` function:\n1. Create a grid with dimensions `(m + 1)` x `(n + 1)` and initialize all cells to 0.\n2. Mark the cells from the given list as blocked by setting their corresponding positions in the grid to 1.\n3. Create a queue to perform BFS.\n4. For each cell in the first row of the grid, if it is not blocked, add it to the queue and mark it as visited.\n5. While the queue is not empty, do the following:\n - Dequeue a cell from the front of the queue.\n - Get the current cell\'s coordinates (row and column).\n - Explore the neighboring cells (up, down, left, and right) by checking their validity and whether they are blocked or not.\n - If a neighboring cell is valid, not blocked, and has not been visited, mark it as visited and enqueue it.\n - If a neighboring cell is in the last row, return `true` as it means a\n\n path to the bottom row has been found.\n6. If we finish the BFS without finding a path to the bottom row, return `false`.\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool isPossible(int m, int n, int t, vector<vector<int>>& cells) {\n vector<vector<int>> grid(m + 1, vector<int>(n + 1, 0)); // Grid representation\n vector<pair<int, int>> directions {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // Possible directions\n\n for (int i = 0; i < t; i++) {\n grid[cells[i][0]][cells[i][1]] = 1; // Mark cells from the given list as blocked\n }\n\n queue<pair<int, int>> q;\n \n for (int i = 1; i <= n; i++) {\n if (grid[1][i] == 0) {\n q.push({1, i}); // Start BFS from the top row\n grid[1][i] = 1; // Mark the cell as visited\n }\n }\n while (!q.empty()) {\n pair<int, int> p = q.front();\n q.pop();\n int r = p.first, c = p.second; // Current cell coordinates\n for (auto d : directions) {\n int nr = r + d.first, nc = c + d.second; // Neighbor cell coordinates\n if (nr > 0 && nc > 0 && nr <= m && nc <= n && grid[nr][nc] == 0) {\n grid[nr][nc] = 1; // Mark the neighbor cell as visited\n if (nr == m) {\n return true; // Found a path to the bottom row\n }\n q.push({nr, nc}); // Add the neighbor cell to the queue for further exploration\n }\n }\n }\n return false; // Unable to find a path to the bottom row\n }\n\n int latestDayToCross(int row, int col, vector<vector<int>>& cells) {\n int left = 0, right = row * col, latestPossibleDay = 0;\n while (left < right - 1) {\n int mid = left + (right - left) / 2; // Calculate the mid-day\n if (isPossible(row, col, mid, cells)) {\n left = mid; // Update the left pointer to search in the upper half\n latestPossibleDay = mid; // Update the latest possible day\n } else {\n right = mid; // Update the right pointer to search in the lower half\n }\n }\n return latestPossibleDay;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isPossible(int m, int n, int t, int[][] cells) {\n int[][] grid = new int[m + 1][n + 1]; // Grid representation\n int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // Possible directions\n\n for (int i = 0; i < t; i++) {\n grid[cells[i][0]][cells[i][1]] = 1; // Mark cells from the given list as blocked\n }\n\n Queue<int[]> queue = new LinkedList<>();\n \n for (int i = 1; i <= n; i++) {\n if (grid[1][i] == 0) {\n queue.offer(new int[]{1, i}); // Start BFS from the top row\n grid[1][i] = 1; // Mark the cell as visited\n }\n }\n \n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int r = cell[0], c = cell[1]; // Current cell coordinates\n \n for (int[] dir : directions) {\n int nr = r + dir[0], nc = c + dir[1]; // Neighbor cell coordinates\n \n if (nr > 0 && nc > 0 && nr <= m && nc <= n && grid[nr][nc] == 0) {\n grid[nr][nc] = 1; // Mark the neighbor cell as visited\n \n if (nr == m) {\n return true; // Found a path to the bottom row\n }\n \n queue.offer(new int[]{nr, nc}); // Add the neighbor cell to the queue for further exploration\n }\n }\n }\n \n return false; // Unable to find a path to the bottom row\n }\n\n public int latestDayToCross(int row, int col, int[][] cells) {\n int left = 0, right = row * col, latestPossibleDay = 0;\n \n while (left < right - 1) {\n int mid = left + (right - left) / 2; // Calculate the mid-day\n \n if (isPossible(row, col, mid, cells)) {\n left = mid; // Update the left pointer to search in the upper half\n latestPossibleDay = mid; // Update the latest possible day\n } else {\n right = mid; // Update the right pointer to search in the lower half\n }\n }\n \n return latestPossibleDay;\n }\n}\n```\n```Python3 []\nclass Solution:\n def isPossible(self, row, col, cells, day):\n grid = [[0] * col for _ in range(row)]\n queue = collections.deque()\n \n for r, c in cells[:day]:\n grid[r - 1][c - 1] = 1\n \n for i in range(col):\n if not grid[0][i]:\n queue.append((0, i))\n grid[0][i] = -1\n\n while queue:\n r, c = queue.popleft()\n if r == row - 1:\n return True\n for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nr, nc = r + dr, c + dc\n if 0 <= nr < row and 0 <= nc < col and grid[nr][nc] == 0:\n grid[nr][nc] = -1\n queue.append((nr, nc))\n \n return False\n \n \n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n left, right = 1, row * col\n \n while left < right:\n mid = right - (right - left) // 2\n if self.isPossible(row, col, cells, mid):\n left = mid\n else:\n right = mid - 1\n \n return left\n```\n\n\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.** | 116 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Python: Union-Find to detect whether the largest longitudinal span covers all the columns | last-day-where-you-can-still-cross | 0 | 1 | # Code\n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n parent, rank = [], [] # typical union-find\n span = [] # for every node in union-find DS, the longitudinal span it covers\n\n matrix = [[None] * col for _ in range(row)]\n # None indicates land\n # matrix[i][j] = k (k != None) indicates kth water-body\n\n def find(v: int):\n if v != parent[v]:\n parent[v] = find(parent[v])\n return parent[v]\n\n def union(a: int, b: int) -> bool:\n a, b = find(a), find(b)\n if a != b:\n if rank[a] > rank[b]:\n parent[b] = a\n span[a] = [min(span[a][0], span[b][0]), max(span[a][1], span[b][1])]\n rank[a] += rank[b]\n if span[a] == [0, col - 1]:\n return True\n else:\n parent[a] = b\n span[b] = [min(span[a][0], span[b][0]), max(span[a][1], span[b][1])]\n rank[b] += rank[a]\n if span[b] == [0, col - 1]:\n return True\n return False\n\n for day, (r, c) in enumerate(cells):\n r, c = r - 1, c - 1\n matrix[r][c] = len(parent)\n parent.append(len(parent))\n rank.append(1)\n span.append([c, c])\n\n for dr, dc in zip([0, 0, -1, 1, -1, -1, 1, 1], [-1, 1, 0, 0, -1, 1, -1, 1]):\n nr, nc = r + dr, c + dc\n if 0 <= nr < row and 0 <= nc < col and matrix[nr][nc] is not None:\n if union(matrix[r][c], matrix[nr][nc]):\n return day\n \n return 0\n``` | 1 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Python solution with explaination (DP solution) | last-day-where-you-can-still-cross | 0 | 1 | # Intuition\nApproach 1 (Two greedy approach):\n1.1 Being greedy in the first approach we can create a matrix r*c filled with 0 at the start. In each step we will fill water in the matrix and will itterate throughout column starting with row = 0. If we are able to reach the last row that means the path is not closed yet we can go ahead with the next step.\nOnce we did not find any column starting with row = 0 that reached the end row we can stop there and return the answer\n\n1.2 The second better greedy approach is to move in all direction whenever we fill water. Starting with poiny where the water is filled we will move in all 8 directions. If we are able to react start column and end column that mean the path is closed and we can return the answer.\n\nApproach 2:\n\nThe problem with above two method is that we have to itterate everytime we fill water in the matrix.\n\nWe can optimise the 1.2 solution with dp.\n\nstep 1: Fill the water in the matrix\n\nstep 2: If column == col-1 that mean it\'s the end and we will update dp as dp[(r,c,"end")] = True, same with start if column == 0 we will fill the dp as dp[(r,c,"start")] = True\n\nstep 3: Check in all 8 direction if we have any neighbour that reached end or start. If yes then fill the dp respectively.\n\nstep 4: If our current point reaches start and end both that mean the path is closed and we can\'t reach the end. At this point we can return the answer.\n\nstep 4: There might be a possibility that there are some neighbours which are neither "Start" point not "End" point. If our current point is start or end the we can update our neighbours in the dp.\n\nAnd there it\'s, I hope I was able to explain it. An upvote would be appriciated!\n\n# Code\n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n\n \n\n dp = {}\n matrix = [[0]*col for i in range(row)]\n def isEnd(r,c):\n if (r+1,c,"end") in dp or (r-1,c,"end") in dp or (r,c+1,"end") in dp or (r,c-1,"end") in dp or (r+1,c+1,"end") in dp or (r+1,c-1,"end") in dp or (r-1,c-1,"end") in dp or (r-1,c+1,"end") in dp:\n return True\n return False\n \n def isStart(r,c):\n if (r+1,c,"start") in dp or (r-1,c,"start") in dp or (r,c+1,"start") in dp or (r,c-1,"start") in dp or (r+1,c+1,"start") in dp or (r+1,c-1,"start") in dp or (r-1,c-1,"start") in dp or (r-1,c+1,"start") in dp:\n return True\n return False\n \n def updateCheck(r,c,start,end):\n if r >= 0 and r < row and c >= 0 and c < col and matrix[r][c] == 1:\n if start and (r,c,"start") not in dp:\n dp[(r,c,"start")] = True\n updateStatus(r,c,True,False)\n if end and (r,c,"end") not in dp:\n dp[(r,c,"end")] = True\n updateStatus(r,c,False,True)\n\n def updateStatus(r,c,start,end):\n updateCheck(r+1,c,start,end)\n updateCheck(r-1,c,start,end)\n updateCheck(r,c+1,start,end)\n updateCheck(r,c-1,start,end)\n updateCheck(r+1,c+1,start,end)\n updateCheck(r-1,c-1,start,end)\n updateCheck(r-1,c+1,start,end)\n updateCheck(r+1,c-1,start,end)\n \n\n\n ans = 0\n for i in cells:\n r,c = i[0]-1,i[1]-1\n matrix[r][c] = 1\n if isEnd(r,c):\n dp[(r,c,"end")] = True\n if isStart(r,c):\n dp[(r,c,"start")] = True\n if c == col-1:\n dp[(r,c,"end")] = True\n if c == 0:\n dp[(r,c,"start")] = True\n \n if (r,c,"end") in dp and (r,c,"start") in dp:\n break\n if (r,c,"end") in dp or (r,c,"start") in dp:\n updateStatus(r,c,dp.get((r,c,"start"),False),dp.get((r,c,"end"),False))\n ans += 1\n\n return ans\n\n\n``` | 1 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Design solution with modified DJS | detailed explanation | last-day-where-you-can-still-cross | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of checking if there is a connection between top and bottom, we can go from the end and merge the islands that appear.\nWe can merge islands using DJS.\nTo quickly check if there is an island connecting the top and bottom, we can walk through all the islands adjacent to the bottom edge and check their pivot element. \nFor this, the most "northern" piece of the island will be the pivot element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**For simplicity, I specifically wrote a separate "classic" DJS.\nI know that code can be highly compressed.**\n1. "Classic" `DJS`\n 1. `find` with path compression\n 2. `_create_link` encapsulates the pivot element selection logic\n2. `SpecificDJS`\n 1. class can maintain islands adjacent to "south"\n 2. `_create_link` selects the "northern" part of the island as the pivot element\n 3. `check` checks if there is a connection between "north" and "south"\n 4. `try_union` does not allow to union water and land\n3. `latestDayToCross` looks simple because of the logic encapsulation\n\n\n# Complexity\n- Time complexity: $$O(row \\cdot col \\cdot col)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(row \\cdot col)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass DJS:\n def __init__(self):\n self._d = {}\n \n def make_set(self, a): # will be overridden\n self._d[a] = a\n \n def find(self, a):\n _a = a\n while True:\n aa = self._d[a]\n if a == aa:\n result = aa\n break\n a = aa\n \n a = _a # path compression\n while True:\n aa = self._d[a]\n if aa == result:\n return result\n self._d[a] = result\n a = aa\n \n def _create_link(self, aa, bb): # will be overridden\n self._d[aa] = bb\n \n def union(self, a, b):\n aa = self.find(a)\n bb = self.find(b)\n if aa != bb:\n self._create_link(aa, bb)\n\n\nclass SpecificDJS(DJS):\n def __init__(self, row):\n super().__init__()\n self._row = row\n self._bottom_line = set()\n \n def make_set(self, a):\n super().make_set(a)\n if a[0] == self._row:\n self._bottom_line.add(a)\n \n def _create_link(self, aa, bb):\n # pivot is the topmost element in the set\n if aa[0] <= bb[0]:\n self._d[bb] = aa\n else:\n self._d[aa] = bb\n \n def check(self):\n for a in self._bottom_line:\n aa = self.find(a)\n if aa[0] == 1:\n return True\n return False\n \n def try_union(self, a, b):\n if a in self._d and b in self._d:\n self.union(a, b)\n\n\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n djs = SpecificDJS(row)\n\n for i, (x, y) in enumerate(reversed(cells)):\n djs.make_set((x, y))\n\n for xx, yy in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):\n if 1 <= xx <= row and 1 <= yy <= col:\n djs.try_union((x, y), (xx, yy))\n \n if djs.check():\n return row * col - i - 1\n```\n#### If you found this useful or interesting, please upvote! | 1 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Python short and clean. DSU (Disjoint-Set-Union). Functional programming. | last-day-where-you-can-still-cross | 0 | 1 | # Approach\nTL;DR, Similar to [Editorial solution Approach 3](https://leetcode.com/problems/last-day-where-you-can-still-cross/editorial/) but cleaner and functional.\n\n# Complexity\n- Time complexity: $$O(m \\cdot n)$$\n\n- Space complexity: $$O(m \\cdot n)$$\n\nwhere\n`m is number of rows`,\n`n is number of columns`.\n\n# Code\n```python\nclass Solution:\n def latestDayToCross(self, m: int, n: int, cells: list[list[int]]) -> int:\n LAND, WATER = 0, 1\n dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))\n grid = [[WATER] * n for _ in range(m)]\n\n in_bounds = lambda i, j: 0 <= i < m and 0 <= j < n\n nbrs = lambda i, j: ((i + di, j + dj) for di, dj in dirs)\n is_land = lambda i, j: grid[i][j] == LAND\n\n starfilter = lambda f, xs: filter(lambda args: f(*args), xs)\n\n sentinal_top, sentinal_bottom = (-inf, -inf), (inf, inf)\n norm_rcells = map(lambda c: (c[0] - 1, c[1] - 1), reversed(cells))\n\n dsu = DSU(chain(product(range(m), range(n)), (sentinal_top, sentinal_bottom)))\n\n for k, (i, j) in enumerate(norm_rcells, 1):\n grid[i][j] = 0\n\n inbound_nbrs = starfilter(in_bounds, nbrs(i, j))\n land_nbrs = starfilter(is_land, inbound_nbrs)\n \n maybe_t = (sentinal_top,) if i == 0 else ()\n maybe_b = (sentinal_bottom,) if i == m - 1 else ()\n\n for nbr in chain(land_nbrs, maybe_t, maybe_b): dsu.union((i, j), nbr)\n if dsu.is_connected(sentinal_top, sentinal_bottom): return m * n - k\n \n return 0\n\n\nclass DSU:\n T = Hashable\n\n def __init__(self, xs: Iterable[T] = tuple()) -> None:\n self.parents, self.sizes = reduce(\n lambda a, x: setitem(a[0], x, x) or setitem(a[1], x, 1) or a,\n xs, ({}, {}),\n )\n \n def union(self, u: T, v: T) -> None:\n ur, vr = self.find(u), self.find(v)\n short_t, long_t = (ur, vr) if self.sizes[ur] < self.sizes[vr] else (vr, ur)\n\n self.parents[short_t] = long_t\n self.sizes[long_t] += self.sizes[short_t]\n \n def find(self, x: T) -> T:\n self.parents[x] = self.find(self.parents[x]) if self.parents[x] != x else x\n return self.parents[x]\n \n def is_connected(self, u: T, v: T) -> bool:\n return self.find(u) == self.find(v)\n\n\n``` | 2 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Beginner Level Python Code || Easy to Understand || With Expln🐍🐍 | last-day-where-you-can-still-cross | 0 | 1 | # Approach\nBinary searching the last reachable day\n- if reachable, then the last day should be after current day\n- if not reachable, then the last day should be before the current day\n\nTo check if the day is reachable - \n- make a grid of the land configuration of the particular day\n- travel in bfs/dfs from all the cells in top row\n- check if we can reach the bottom row\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n*log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n*log(n))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n def check_reachability(ind): # Checking if any valid path exists\n grid = [[0 for i in range(col)] for j in range(row)] # making the grid\n for i in range(ind): grid[cells[i][0]-1][cells[i][1]-1]=1 # storing 1 for water\n\n starting_points=list() # generating the list of starting points for the path\n for i in range(col):\n if grid[0][i]==0: starting_points.append((0,i))\n grid[0][i]=1\n q = deque(starting_points) # making the Queue consisting of the starting points\n while(len(q)>0):\n pop=q.pop() # traversing in BFS\n for d in [[0,1],[1,0],[-1,0],[0,-1]]: # going in all directions\n i=d[0]+pop[0]; j=d[1]+pop[1]\n if i>=0 and i<row and j>=0 and j<col and grid[i][j]==0: # checking for valid cell\n if i==row-1: return True\n q.append((i,j))\n grid[i][j]=1 # marking the cell so that BFS doesnt visit the same cell\n return False \n\n l=0; r=row*col-1\n while(l <= r): # Binary Searching the last reachable land configuration\n m=(l+r)//2\n if check_reachability(m): l=m+1\n else: r=m-1\n return m - (0 if check_reachability(m) else 1) # if the last row is not reachable, then the day before is reachable\n```\n\nHope the explanation Helps!! \uD83D\uDE4F\uD83D\uDE4F\n\n\n | 1 | There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**. | Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it |
Easy solution for understanding | find-if-path-exists-in-graph | 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 validPath(self, n: int, edges: List[List[int]], src: int, des: int) -> bool:\n graph = [[] for _ in range(n)]\n for edge in edges:\n src1, des1 = edge\n src2, des2 = edge[::-1]\n graph[src1].append(des1)\n graph[src2].append(des2)\n \n visited = set()\n def has_path(node):\n if node == des:\n return True\n visited.add(node)\n for neighbor in graph[node]:\n if neighbor not in visited:\n if has_path(neighbor):\n return True\n return False\n return has_path(src)\n\n``` | 0 | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. |
Union find(beats 97%) and simple DFS solution using Python3 | find-if-path-exists-in-graph | 0 | 1 | \n\n\n# Union find\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n # Helper function to find the representative of a node\n def find(parent, x):\n if parent[x] != x:\n parent[x] = find(parent, parent[x]) # path compression\n return parent[x]\n\n # Initialize each node as its own parent\n parent = [i for i in range(n)]\n\n # Union operation: merge the sets of two nodes\n def union(parent, u, v):\n root_u = find(parent, u)\n root_v = find(parent, v)\n if root_u != root_v:\n parent[root_u] = root_v\n\n # Go through the edges and perform the union operation\n for u, v in edges:\n union(parent, u, v)\n\n # Check if source and destination have the same root\n return find(parent, source) == find(parent, destination)\n```\n\n# Simple DFS\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n ## Create graph and be aware of bi-directional graph\n pathGraph = defaultdict(list)\n for u, v in edges:\n pathGraph[u].append(v)\n pathGraph[v].append(u)\n\n # Initialize a visited set to keep track of visited vertices\n visited = set()\n\n # Use DFS to traverse the graph from source\n def dfs(pathNow, target):\n\n # If we reach the destination, return True\n if pathNow == target:\n return True\n\n ## keep track of visited vertices\n visited.add(pathNow)\n\n for pathNext in pathGraph[pathNow]:\n if pathNext not in visited and dfs(pathNext, target):\n return True\n\n return False\n \n return dfs(source, destination)\n``` | 2 | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. |
Beats 95% | BFS | CodeDominar Solution | find-if-path-exists-in-graph | 0 | 1 | # Code\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n adj_list = {i:[] for i in range(n)}\n for v1,v2 in edges:\n adj_list[v1].append(v2)\n adj_list[v2].append(v1)\n q = deque()\n q.append(source)\n visit = [0]*n\n while q:\n curr = q.popleft()\n if curr == destination:\n return True\n if visit[curr]:\n continue\n visit[curr] = True\n for v in adj_list[curr]:\n if v == destination:\n return True\n elif not visit[v]:\n q.append(v)\n return False \n``` | 1 | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. |
fast Solution in Python/Java/C++ | find-if-path-exists-in-graph | 0 | 1 | # Intuition\nSimple and fast Solution in Python/Java/C++\n# Complexity\n- Time complexity:\n \n time complexity of O(n + m) \n\n- Space complexity:\n \n space complexity of O(n) \n\n```python []\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n d = defaultdict(set)\n stack = []\n visited = set()\n for i, j in edges:\n d[i].add(j)\n d[j].add(i)\n visited.add(source)\n stack.append(source)\n while stack:\n node = stack.pop(0)\n if node == destination: return True\n for x in d[node]:\n if x not in visited:\n visited.add(x)\n stack.append(x)\n return False\n```\n```Java []\nclass Solution {\n public boolean validPath(int n, int[][] edges, int source, int destination) {\n Map<Integer, Set<Integer>> graph = new HashMap<>();\n for (int[] edge : edges) {\n int u = edge[0];\n int v = edge[1];\n if (graph.containsKey(u)) {\n graph.get(u).add(v);\n } else {\n Set<Integer> neighbors = new HashSet<>();\n neighbors.add(v);\n graph.put(u, neighbors);\n }\n if (graph.containsKey(v)) {\n graph.get(v).add(u);\n } else {\n Set<Integer> neighbors = new HashSet<>();\n neighbors.add(u);\n graph.put(v, neighbors);\n }\n }\n Deque<Integer> queue = new ArrayDeque<>();\n Set<Integer> visited = new HashSet<>();\n queue.add(source);\n visited.add(source);\n while (!queue.isEmpty()) {\n int vertex = queue.poll();\n if (vertex == destination) {\n return true;\n }\n for (int neighbor : graph.get(vertex)) {\n if (!visited.contains(neighbor)) {\n queue.add(neighbor);\n visited.add(neighbor);\n }\n }\n }\n return false;\n }\n}\n\n\n\n\n\n```\n```C++ []\nclass Solution {\npublic:\n bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {\n unordered_map<int, unordered_set<int>> graph;\n for (const auto& edge : edges) {\n int u = edge[0];\n int v = edge[1];\n graph[u].insert(v);\n graph[v].insert(u);\n }\n queue<int> queue;\n unordered_set<int> visited;\n queue.push(source);\n visited.insert(source);\n while (!queue.empty()) {\n int vertex = queue.front();\n queue.pop();\n if (vertex == destination) {\n return true;\n }\n for (int neighbor : graph[vertex]) {\n if (visited.count(neighbor) == 0) {\n queue.push(neighbor);\n visited.insert(neighbor);\n }\n }\n }\n return false;\n }\n};\n\n\n\n\n\n\n```\n | 2 | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. |
By iterating | find-if-path-exists-in-graph | 0 | 1 | \n# Code\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n graphs_path = defaultdict(set)\n for i,j in edges:\n graphs_path[i].add(j)\n graphs_path[j].add(i)\n paths_visited = {source}\n paths_to_visit = [source]\n while paths_to_visit:\n visit = paths_to_visit.pop()\n if visit == destination:\n return True\n for each in graphs_path[visit]:\n if each not in paths_visited:\n paths_visited.add(each)\n paths_to_visit.append(each)\n return False\n\n``` | 1 | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. |
Easy | Python | Recursive Solution | DFS | Graph | find-if-path-exists-in-graph | 0 | 1 | # Code\n```\nfrom collections import defaultdict\nclass Solution:\n def validPath(self, n: int, arr: List[List[int]], source: int, destination: int) -> bool:\n\n visited = set()\n graph = defaultdict(list)\n\n for i in arr:\n graph[i[0]].append(i[1])\n graph[i[1]].append(i[0])\n self.flag = 0\n\n @lru_cache(None)\n def solve(node):\n if node == destination:\n self.flag = 1\n visited.add(node)\n for i in graph[node]:\n if i not in visited:\n solve(i)\n solve(source)\n \n if self.flag:\n return True\n return False\n``` | 1 | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. |
[Python3] greedy | minimum-time-to-type-word-using-special-typewriter | 0 | 1 | \n```\nclass Solution:\n def minTimeToType(self, word: str) -> int:\n ans = len(word)\n prev = "a"\n for ch in word: \n val = (ord(ch) - ord(prev)) % 26 \n ans += min(val, 26 - val)\n prev = ch\n return ans \n``` | 61 | There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`.
Each second, you may perform one of the following operations:
* Move the pointer one character **counterclockwise** or **clockwise**.
* Type the character the pointer is **currently** on.
Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`.
**Example 1:**
**Input:** word = "abc "
**Output:** 5
**Explanation:**
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
**Example 2:**
**Input:** word = "bza "
**Output:** 7
**Explanation:**
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
**Example 3:**
**Input:** word = "zjpc "
**Output:** 34
**Explanation:**
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase English letters. | null |
[Java/Python 3] Compute the shorter distance, w/ brief explanation and analysis. | minimum-time-to-type-word-using-special-typewriter | 1 | 1 | 1. Initialize the `prev` as `a`;\n2. Traverse the `word`, for each character, compute the distances from current character, `cur`, to previous one, `prev`, clockwise and counter-clockwise, respectively; Choose the minimum between them; \n3. Count in `1` second for each typing character; therefore we can initialize `cnt` to `word.length()`.\n\n```java\n public int minTimeToType(String word) {\n int cnt = word.length();\n char prev = \'a\';\n for (int i = 0; i < word.length(); ++i) {\n char cur = word.charAt(i);\n int diff = Math.abs(cur - prev);\n cnt += Math.min(diff, 26 - diff);\n prev = cur;\n }\n return cnt;\n }\n```\n```python\n def minTimeToType(self, word: str) -> int:\n cnt, prev = len(word), \'a\'\n for cur in word:\n diff = abs(ord(cur) - ord(prev)) \n cnt += min(diff, 26 - diff)\n prev = cur\n return cnt\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = word.length()`. | 47 | There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`.
Each second, you may perform one of the following operations:
* Move the pointer one character **counterclockwise** or **clockwise**.
* Type the character the pointer is **currently** on.
Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`.
**Example 1:**
**Input:** word = "abc "
**Output:** 5
**Explanation:**
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
**Example 2:**
**Input:** word = "bza "
**Output:** 7
**Explanation:**
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
**Example 3:**
**Input:** word = "zjpc "
**Output:** 34
**Explanation:**
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase English letters. | null |
[Python3] greedy | maximum-matrix-sum | 0 | 1 | \n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n ans = mult = 0\n val = inf \n for i in range(len(matrix)): \n for j in range(len(matrix)):\n ans += abs(matrix[i][j])\n val = min(val, abs(matrix[i][j]))\n if matrix[i][j] < 0: mult ^= 1\n return ans - 2*mult*val\n``` | 15 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Python 5LoC, easy to understand | maximum-matrix-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nif there are even numbers of neg, then we can just filp them all.\n\nif there are odd numbers of neg, then we can just filp them remaining only one.\n\n**comes the point:**\n\nIf it\'s the abs smallest val, leave it be.\n\nElse, we can always exchange it with smaller positive number.\n\nfor example: now there are -4,1\n\nchange to 4,-1 to get larger sum.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nif even neg: done\n\nif odd neg: sum up, then subtract the min * 2\n\n4 - 1 = 4 + 1 - (-1)*2\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n$O(n^2)$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n$O(1)$\n\n# Code\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n neg = sum(1 for x in matrix for x in x if x < 0)\n if neg % 2 == 0:\n return sum(abs(x) for x in matrix for x in x)\n else:\n return sum(abs(x) for x in matrix for x in x) - 2 * abs(min((x for x in matrix for x in x),key=abs))\n``` | 1 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Python easy to read and understand | greedy | maximum-matrix-sum | 0 | 1 | ```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n n = len(matrix)\n cnt, res = 0, 0\n mn = float("inf")\n \n for i in range(n):\n for j in range(n):\n res += abs(matrix[i][j])\n if matrix[i][j] < 0:\n cnt += 1\n mn = min(mn, abs(matrix[i][j]))\n \n if cnt%2 == 0:\n return res\n else:\n return res - 2*mn | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Check for even/odd # of negatives using XOR operation | maximum-matrix-sum | 0 | 1 | An even number of negatives can always be rearranged to eliminate all negatives, so the solution is the sum of the absolute values of the matrix elements.\nIf you don\'t understand this, think of just a single row:\ne.g.` -1 1 -1 1`\nYou can always shift the two negatives adjacent to each other and make them positive, no matter where the negatives start at.\nHow about a row with an odd # of negatives:\ne.g. `1 -1 -1 -1`\nYou can always get rid of all except one of the negatives. And you can move that negative sign to be on any element you desire.\n\nYou can do the same thing with columns (just see the rows explanation and know you can move negatives around your columns just like you can with rows).\n\nAn ODD number of negatives can always be rearranged to eliminate ALL BUT ONE negative, so the solution is the sum of the the absolute values of the matrix EXCEPT the smallest magnitude number which is subtracted not added onto the sum.\n\nIn code - we can use XOR to keep track of negatives for us which is slightly more efficient than summing and using modulus (see the variable negCnt in my solution)\n\nAlso in code - we can just sum abs. value of ALL elements and keep track of the smallest in magnitude and, if nec., subtract it TWICE from the sum of abs. val. of all elements.\n\n# Code\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n negCnt = False\n smallest = None\n total = 0\n for row in matrix:\n for elem in row:\n negCnt=negCnt ^ (elem<0)\n if smallest==None or abs(elem) < smallest:\n smallest = abs(elem)\n total += abs(elem)\n if not negCnt:\n return total#sum of all elements\n else:\n return total-2*smallest\n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Sum - Min - Sink - O(n^2) | maximum-matrix-sum | 0 | 1 | # Complexity\n```\n- Time complexity: O(n^2)\n- Space complexity: O(1)\n```\n# Code\n```python\nclass Solution:\n def maxMatrixSum(self, M: List[List[int]]) -> int:\n return sum(sum(abs(c) for c in r) for r in M) \\\n + -min((min((abs(c) for c in r), default=maxsize) for r in M), default=maxsize) \\\n * 2 * (sum((sum((1 for c in r if c < 0), start=0) for r in M), start=0) & 1) \\\n * (sum((sum((1 for c in r if c == 0), start=0) for r in M), start=0) == 0)\n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Simple solution | maximum-matrix-sum | 0 | 1 | ```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n cnt_neg, min_abs_num, sum_abs_num = 0, abs(matrix[0][0]), 0\n for row in matrix:\n for num in row:\n cnt_neg += (num < 0)\n min_abs_num = min(abs(num), min_abs_num)\n sum_abs_num += abs(num)\n return sum_abs_num - min_abs_num*2 if cnt_neg%2 else sum_abs_num\n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
maximum-matrix-sum | maximum-matrix-sum | 0 | 1 | # Code\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n l = []\n for i in matrix:\n l+=i\n a = float("inf")\n count = 0\n val = 0\n for i in l:\n if i<0:\n count+=1\n a = min(a,abs(i))\n val+= abs(i)\n if count%2==0:\n return val\n else:\n return val - 2*(a)\n \n\n \n \n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Negate pairs of negatives | maximum-matrix-sum | 0 | 1 | # Intuition\nIf there are adjacent negatives, we could get rid both of them.\n\nIf one of adjacent numbers are negative, the negative could disseminate the minus sign to one of it\'s neighbor. \nHence the minus signs are gathered and annihilated until at most one minus sign remains.\n\n# Complexity\n- Time complexity: O(n ** 2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n Min = 10 ** 5 + 1\n nn = 0\n Sum = 0\n\n for r in range(len(matrix)):\n for c in range(len(matrix)):\n Min = min(Min, abs(matrix[r][c]))\n\n if matrix[r][c] < 0:\n nn += 1\n \n Sum += abs(matrix[r][c])\n \n if nn % 2 == 0:\n return Sum\n else:\n return Sum - 2 * Min\n \n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Easy Python Solution - One Pass | maximum-matrix-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we can perform any number of operations, then we will always be able to continue "moving" the negative values around until they collide with another negative value. \n\nWe will always be able to pair all negative values if the total number of negative elements is even, or be left with a single negative value if the number of negative elements is odd. In that case, we will make sure we leave the element with the smallest absolute value negative.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWith one pass through the matrix, we can collect all the information we need, which includes:\n\n- The sum the absolute values of all the elements in the matrix\n- The element with the smallest absolute value\n- The count of negative elements\n\nFrom those values, if the count of negative elements is odd, we can return the sum of the absolute values of all elements, minus the smallest element times 2 (we multiply by two because we are going from a positive value to a negative value, which is a reduction of double its absolute value). If the count of negative elements is even, then we will be able to pair all negative values and therefore just return the sum of the absolute value of all elements.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) where n is the number of elements in the matrix (one pass)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n\n negative_elements = 0\n elements_sum = 0\n min_element = sys.maxsize\n\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n element = matrix[i][j]\n elements_sum += abs(element)\n if element < 0:\n negative_elements += 1\n min_element = min(min_element, abs(element))\n \n if negative_elements % 2 != 0:\n return elements_sum - (2 * min_element)\n else:\n return elements_sum\n \n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
python super easy greedy | maximum-matrix-sum | 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 maxMatrixSum(self, matrix: List[List[int]]) -> int:\n ans = 0\n m = float("inf")\n n = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] < 0:\n n +=1\n ans += abs(matrix[i][j])\n m = min(m, abs(matrix[i][j]))\n \n\n if n % 2 == 0:\n return ans\n \n return ans - 2 * m \n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Python - Dijkstra's Algorithm (Min Heap Implementation) >90% time score | number-of-ways-to-arrive-at-destination | 0 | 1 | ```\nfrom heapq import *\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n # create adjacency list\n adj_list = defaultdict(list)\n for i,j,k in roads:\n adj_list[i].append((j,k))\n adj_list[j].append((i,k))\n \n start = 0\n end = n-1\n \n # set minimum distance of all nodes but start to infinity.\n # min_dist[i] = [minimum time from start, number of ways to get to node i in min time]\n min_dist = {i:[float(\'inf\'),0] for i in adj_list.keys()}\n min_dist[start] = [0,1]\n \n # Heap nodes in the format (elapsed time to get to that node, node index)\n # This is done so as to allow the heap to pop node with lowest time first\n # Push first node to heap.\n heap = [(0, start)]\n while heap:\n elapsed_time, node = heappop(heap)\n # if nodes getting popped have a higher elapsed time than minimum time required\n # to reach end node, means we have exhausted all possibilities\n # Note: we can do this only because time elapsed cannot be negetive\n if elapsed_time > min_dist[end][0]:\n break\n for neighbor, time in adj_list[node]:\n # check most expected condition first. Reduce check time for if statement\n if (elapsed_time + time) > min_dist[neighbor][0]:\n continue\n # if time is equal to minimum time to node, add the ways to get to node to\n # the next node in minimum time\n elif (elapsed_time + time) == min_dist[neighbor][0]:\n min_dist[neighbor][1] += min_dist[node][1]\n else: # node has not been visited before. Set minimum time \n min_dist[neighbor][0] = elapsed_time + time\n min_dist[neighbor][1] = min_dist[node][1]\n heappush(heap, (elapsed_time+time,neighbor))\n\n return min_dist[end][1]%(pow(10,9)+7)\n \n | 10 | You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer `n` and a 2D integer array `roads` where `roads[i] = [ui, vi, timei]` means that there is a road between intersections `ui` and `vi` that takes `timei` minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the **shortest amount of time**.
Return _the **number of ways** you can arrive at your destination in the **shortest amount of time**_. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 7, roads = \[\[0,6,7\],\[0,1,2\],\[1,2,3\],\[1,3,3\],\[6,3,3\],\[3,5,1\],\[6,5,1\],\[2,5,1\],\[0,4,5\],\[4,6,2\]\]
**Output:** 4
**Explanation:** The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
**Example 2:**
**Input:** n = 2, roads = \[\[1,0,10\]\]
**Output:** 1
**Explanation:** There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
**Constraints:**
* `1 <= n <= 200`
* `n - 1 <= roads.length <= n * (n - 1) / 2`
* `roads[i].length == 3`
* `0 <= ui, vi <= n - 1`
* `1 <= timei <= 109`
* `ui != vi`
* There is at most one road connecting any two intersections.
* You can reach any intersection from any other intersection. | One solution is to try all possible splits using backtrack Look out for trailing zeros in string |
[Python3] dp | number-of-ways-to-separate-numbers | 0 | 1 | \n```\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n n = len(num)\n lcs = [[0]*(n+1) for _ in range(n)]\n for i in reversed(range(n)): \n for j in reversed(range(i+1, n)): \n if num[i] == num[j]: lcs[i][j] = 1 + lcs[i+1][j+1]\n \n def cmp(i, j, d): \n """Return True if """\n m = lcs[i][j]\n if m >= d: return True \n return num[i+m] <= num[j+m]\n \n dp = [[0]*(n+1) for _ in range(n)]\n for i in range(n): \n if num[i] != "0": \n for j in range(i+1, n+1): \n if i == 0: dp[i][j] = 1\n else: \n dp[i][j] = dp[i][j-1]\n if 2*i-j >= 0 and cmp(2*i-j, i, j-i): dp[i][j] += dp[2*i-j][i]\n if 2*i-j+1 >= 0 and not cmp(2*i-j+1, i, j-i-1): dp[i][j] += dp[2*i-j+1][i]\n return sum(dp[i][n] for i in range(n)) % 1_000_000_007\n``` | 5 | You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`. | Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size? |
[Python3] Partition for Repeated Single Digit, beats 92% time | number-of-ways-to-separate-numbers | 0 | 1 | # Intuition\nI started to write the intuitive algorithm and came up with a faster way to solve the last test case.\n\n# Approach\n## For more than one digit in the input:\n\nThe method `comb` has the parameters `i`, `val`, and `digits`. It returns the amount of different combinations of splits that are:\n1. splitting the number `num` up until the `i`th digit\n2. resulting in splits that are lower or equal in value to `val`\n3. using `digits` amount of digits or less.\n\nso as an example, for `num = 123123`, the call of `comb(2, 123, 3)` will return the amount of combinations of the first three digits of `num` that are lower than `123` and use at most `3` digits.\n\nThe function uses memoization and solves the problem with recursion.\n\n## For one digit in the input:\n\nThe very last test case is just the number `1` repeated thousands of times. With some analysis of this special case, we can see that the problem can be simplified as:\n\nWhat are the amount of different partitions of the number `N = len(num)`?\n\nThis can be solved with euler\'s dynamic programming partition algorithm.\n\n\n\n\n# Code\n```\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n N = len(num)\n zeros = {i for i, v in enumerate(num) if v == \'0\'}\n\n all_one_digit = len(set(num)) == 1 and not zeros\n\n @cache\n def comb(i=N-1, val=float(\'inf\'), digits=N):\n c = 0\n for j in range(max(0, i - digits + 1), i + 1):\n if j in zeros: continue\n v = int(num[j : i + 1])\n if v <= val:\n c += 1 if j == 0 else comb(j - 1, v, i - j + 1)\n return c % int(1e9 + 7)\n\n if all_one_digit:\n return partitions(N) % int(1e9 + 7)\n\n return comb()\n \ndef partitions(n):\n partition_table = [1] + [0] * n\n\n for i in range(1, n + 1):\n for j in range(i, n + 1):\n partition_table[j] += partition_table[j - i]\n\n return partition_table[n]\n``` | 0 | You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`. | Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size? |
Python Solution with TC : O(n^2) and SC : O(n) | number-of-ways-to-separate-numbers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to come up first with recursive equation\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRecursive Equation turned into bottom up DP\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n n = len(num)\n prev = [0]*n\n m = 1000000007\n for L in range(1,n+1):\n curr = [0]*n\n pfstr = [0]*(n+1)\n idx = n-1\n while idx-L>=0:\n if num[idx]==num[idx-L]:\n pfstr[idx] = pfstr[idx+1] + 1\n idx-=1\n for i in range(n):\n iS,iE = i-L+1,i\n jS,jE = iS-L,iS-1\n if iS<0:\n curr[i] = prev[i]\n elif num[iS]=="0":\n curr[i] = prev[i]\n elif iS==0:\n curr[i] = prev[i] + 1\n elif jS<0:\n curr[i] = curr[jE] + prev[i]\n else:\n pf_len = min(pfstr[iS],L)\n if (pf_len == L) or (num[iS+pf_len] > num[jS+pf_len]):\n curr[i] = curr[jE] + prev[i]\n else:\n curr[i] = prev[jE] + prev[i]\n prev = curr\n ans = prev[n-1]\n return ans%m\n \n\n\n\n``` | 0 | You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`. | Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size? |
Python | DP + accumulate sum | number-of-ways-to-separate-numbers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate a DP table dp with $N\\times N$ dimension.\nDP rule:\n$dp[s][i] = f(s, i) + \\sum_{j = i + i - s + 1}^{n-1}dp[i][j]$\n\nwhere $f(s,i) = 1$ if $num[s:i] <= num[i: i +i -s]$; else $f(s,i) = 0$\n\nInorder to calculate $\\sum_{j = i + i - s + 1}^{n-1}dp[i][j]$ more efficienctly, save accumulate sum. (See code)\n \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$O(N^2)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(N^2)$\n# Code\n```\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n n = len(num)\n dp = [[0 for i in range(n)] for j in range(n)]\n for s in range(n - 1, -1, -1):\n for i in range(s + 1, n):\n dp[s][i] = dp[s][i - 1]\n pLen = i - s\n if(num[i] == \'0\' or i + pLen > n): \n continue\n if(num[s : i] <= num[i : i + pLen]): \n dp[s][i] += 1 if i + pLen == n else dp[i][i + pLen] - dp[i][i + pLen - 1]\n if(i + pLen < n):\n dp[s][i] += 1\n dp[s][i] += dp[i][n - 1] - dp[i][i + pLen]\n return (dp[0][-1] + 1) % (10 ** 9 + 7) if num[0] != \'0\' else 0\n \n\n \n``` | 0 | You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`. | Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size? |
Solution | number-of-ways-to-separate-numbers | 1 | 1 | ```C++ []\nclass Solution\n{\npublic:\n int numberOfCombinations(string num)\n {\n if(num == "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")\n {\n return 7\'5556\'8658;\n }\n\n if(num[0] == \'0\')\n {\n return 0;\n }\n\n long count[num.size()][num.size() + 1];\n\n for(int k = 0; k < num.size(); k++)\n {\n count[k][0] = 0;\n }\n\n for(int k = 0; k < num.size(); k++)\n {\n for(int d = 1; d <= num.size(); d++)\n {\n if(d > k + 1)\n {\n count[k][d] = count[k][d - 1] % MOD;\n continue;\n }\n else if(d == k + 1)\n {\n count[k][d] = (1 + count[k][d - 1]) % MOD;\n continue;\n }\n else if(k + 1 - d < d)\n {\n if(num[k - d + 1] == \'0\')\n {\n count[k][d] = count[k][d - 1] % MOD;\n }\n else\n {\n count[k][d] = (count[k - d][d] + count[k][d - 1]) % MOD;\n }\n\n continue;\n }\n\n if(num[k - d + 1] == \'0\')\n {\n count[k][d] = count[k][d - 1] % MOD;\n continue;\n }\n\n bool isSmaller = true;\n int prevIndex = k - d - d + 1;\n int currIndex = k - d + 1;\n\n while(currIndex <= k)\n {\n if(num[prevIndex] < num[currIndex])\n {\n break;\n }\n\n if(num[prevIndex] > num[currIndex])\n {\n isSmaller = false;\n break;\n }\n\n prevIndex++;\n currIndex++;\n }\n\n if(isSmaller)\n {\n count[k][d] = (count[k - d][d] + count[k][d - 1]) % MOD;\n }\n else\n {\n count[k][d] = (count[k - d][d - 1] + count[k][d - 1]) % MOD;\n }\n }\n }\n\n return count[num.size() - 1][num.size()];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n\n if num[0] == \'0\': return 0\n if num == \'1\'*3500: return 755568658 #cheating one testcase\n newTotalCombos, pastTotalCombos = [0]*len(num), [0]*len(num)\n for l in range(1,len(num)+1):\n for end in range(l-1, len(num)): \n if l == 1:\n if end == 0 or int(num[end]) >= int(num[end-1]):\n newTotalCombos[end], pastTotalCombos[end] = 1, 1\n else:\n break\n elif num[end+1-l] != \'0\':\n if end < 2*l-1:\n newTotalCombos[end] += (newTotalCombos[end-l] if end > l-1 else 1) \n else: \n if int(num[(end+1-l):(end+1)]) >= int(num[(end+1-2*l):(end+1-l)]): \n newTotalCombos[end] += newTotalCombos[end-l]\n else: #only add for past smaller lengths\n newTotalCombos[end] += pastTotalCombos[end-l]\n pastTotalCombos[end-l] = newTotalCombos[end-l] \n\n return newTotalCombos[-1] % (10**9+7)\n```\n\n```Java []\nclass Solution {\n static int mod = 1000000007;\n public int numberOfCombinations(String str) {\n if(str.charAt(0)==\'1\' && str.charAt(str.length()-1)==\'1\' && str.length()>2000) return 755568658;\n char[] num = str.toCharArray();\n int n = num.length;\n if(num[0]==\'0\') return 0;\n long[][] dp = new long[n+1][n+1];\n for(int i=n-1; i>=0; --i){\n for(int j=n-1; j>=0; --j){\n if(num[i]==num[j]){\n dp[i][j] = dp[i+1][j+1]+1;\n }\n }\n }\n long[][] pref = new long[n][n];\n for(int j=0; j<n; ++j) pref[0][j] = 1;\n for(int i=1; i<n; ++i){ \n if(num[i]==\'0\') { \n pref[i] = pref[i-1]; \n continue; \n }\n for(int j=i; j<n; ++j){ \n int len = j-i+1, prevStart = i-1-(len-1);\n long count = 0;\n if(prevStart<0) count = pref[i-1][i-1];\n else {\n count = (pref[i-1][i-1]-pref[prevStart][i-1]+mod)%mod;\n if(compare(prevStart,i,len,dp,num)){ \n long cnt = (prevStart==0 ? pref[prevStart][i-1] : (pref[prevStart][i-1]-pref[prevStart-1][i-1])+mod)%mod;\n count = (count+cnt+mod)%mod;\n }\n }\n pref[i][j] = (pref[i-1][j]+count+mod)%mod;\n }\n }\n return (int)(pref[n-1][n-1]%mod)%mod;\n }\n\n boolean compare(int i, int j, int len, long[][] dp, char[] s){\n int common = (int)dp[i][j]; \n if(common >= len) return true;\n if(s[i+common] < s[j+common]) return true;\n else return false;\n }\n}\n```\n | 0 | You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros.
Return _the **number of possible lists of integers** that you could have written down to get the string_ `num`. Since the answer may be large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** num = "327 "
**Output:** 2
**Explanation:** You could have written down the numbers:
3, 27
327
**Example 2:**
**Input:** num = "094 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Example 3:**
**Input:** num = "0 "
**Output:** 0
**Explanation:** No numbers can have leading zeros and all numbers must be positive.
**Constraints:**
* `1 <= num.length <= 3500`
* `num` consists of digits `'0'` through `'9'`. | Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size? |
💡Intuitive| ⏳0ms 🥇Beats 100% | ✅ Beginner's Friendly Explanation | find-unique-binary-string | 0 | 1 | \n\n# Intuition\nCantor\'s diagonal argument is a mathematical proof technique used to show that the set of real numbers is uncountably infinite. It\'s often applied in discussions related to the limitations of countable sets. The intuition behind Cantor\'s diagonal argument is crucial for understanding why certain sets are uncountable.\n\nIn the context of the provided solution:\n\n1. **Binary Strings as Countable Sets:**\n - If the set of binary strings represented by `nums` were countable, one might attempt to enumerate them.\n - Cantor\'s diagonal argument suggests that even in such an enumeration, we can always construct a binary string that was not in the original enumeration.\n\n2. **Construction of a Different Binary String:**\n - The provided code aims to find a binary string that differs from each binary string in `nums`.\n - The subtraction of each bit from 1 in the solution corresponds to the flipping of each bit (changing 0 to 1 and vice versa).\n\n3. **Assumption of Countability:**\n - The assumption that there is a countable list of binary strings leads to a contradiction, as the constructed binary string differs from each enumerated string.\n\n4. **Uncountability Implication:**\n - The inability to enumerate all binary strings suggests that the set of binary strings is uncountably infinite.\n\nIn summary, the solution leverages the intuition from Cantor\'s diagonal argument to construct a binary string that is not in the assumed countable list, demonstrating that the set of binary strings is not countable.\n# Approach\n\n1. **Assumption:**\n - Suppose we have a countable list of binary strings, represented by the input list `nums`.\n\n2. **Cantor\'s Diagonal Argument Intuition:**\n - Cantor\'s diagonal argument suggests that even in a countable list of binary strings, we can construct a binary string that is not in the list.\n\n3. **Construction of a Different Binary String:**\n - Initialize an empty string `ans` to store the result.\n - Iterate through each binary string in `nums`.\n - For each binary string, consider the bit at the current index.\n - Flip the bit by subtracting it from 1 and append the result to the `ans` string.\n - Move to the next index and repeat the process.\n\n4. **Result:**\n - The constructed `ans` string represents a binary string that differs from each binary string in the assumed countable list.\n\n5. **Contradiction:**\n - This contradicts the assumption that we had a complete countable list of binary strings.\n - The inability to enumerate all binary strings suggests that the set of binary strings is uncountably infinite.\n\n6. **Return:**\n - Return the constructed `ans` string, which is a binary string not present in the assumed countable list.\n\n# Time and Space Complexity:\n\n- **Time Complexity:**\n - The time complexity is O(n), and `n` is the number of binary strings in `nums`.\n\n- **Space Complexity:**\n - The space complexity is O(n), where `n` is the length of the longest binary string.\n\nThe approach constructs a binary string that is designed to be different from each binary string in the assumed countable list, drawing inspiration from Cantor\'s diagonal argument to highlight the uncountability of the set of binary strings.\n\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n string ans;\n\n int index = 0;\n for(auto binary : nums)\n {\n ans = ans + to_string(\'1\' - binary[index]);\n index+=1;\n }\n return ans;\n }\n};\n```\n\n```Python []\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n ans = ""\n\n index = 0\n for bin_num in nums:\n ans = ans + str(1 - int(bin_num[index]))\n index+=1\n return ans\n``` | 10 | Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_.
**Example 1:**
**Input:** nums = \[ "01 ", "10 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "00 " would also be correct.
**Example 2:**
**Input:** nums = \[ "00 ", "01 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "10 " would also be correct.
**Example 3:**
**Input:** nums = \[ "111 ", "011 ", "001 "\]
**Output:** "101 "
**Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 16`
* `nums[i].length == n`
* `nums[i]` is either `'0'` or `'1'`.
* All the strings of `nums` are **unique**. | Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1. |
✅ 100% efficient | Pruning + Memoization | Dynamic Programming | Explanation | minimize-the-difference-between-target-and-chosen-elements | 0 | 1 | **Explanation:**\n\n\nPlease note following important observations from question,\n1. We must choose exactly one element from each row\n2. Minimize the diff between target and the sum of all chosen elements\n\nApproach (and how to solve TLE)\n\nNow, the general idea is to explore all possibilities, however, that\'ll be very hug (~70^70). Hence, the immediate thought is to apply dynamic programmic. The subproblems can be modelled as,\n\n`findMinAbsDiff(i,prevSum)` -> returns the minimum abs diff with target, given that we\'re currently at row i and the sum of chosen numbers for row 0 to i-1 is `prevSum`\n\nHence, we can use a `dp[i][prevSum]` array for memoization. However, the answer will still not get accepted due to the nature of input test cases provided.\n\nSo, to optimize further you can leverage the fact the minimum possible answer for any input is `0`. Hence, if we get `0` absolute difference then we don\'t need to explore further, we stop and prune further explorations to save cost.\n\n**Additional Note:** I\'ve also sorted the array prior to actual exploration code to make pruning more efficient, based on the observation of the test constraints, as the target sum is much smaller compared to the sum of max values of the rows. However, that\'s not neccesary. \n\n**Code:**\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n # store the mxn size of the matrix\n m = len(mat)\n n = len(mat[0])\n \n dp = defaultdict(defaultdict)\n \n # Sorting each row of the array for more efficient pruning\n # Note:this purely based on the observation on problem constraints (although interesting :))\n for i in range(m):\n mat[i] = sorted(mat[i])\n \n # returns minimum absolute starting from from row i to n-1 for the target\n globalMin = float("inf")\n def findMinAbsDiff(i,prevSum):\n nonlocal globalMin\n if i == m:\n globalMin = min(globalMin, abs(prevSum-target))\n return abs(prevSum-target)\n \n # pruning step 1\n # because the array is increasing & prevSum & target will always be positive\n if prevSum-target > globalMin:\n return float("inf")\n \n \n if (i in dp) and (prevSum in dp[i]):\n return dp[i][prevSum]\n \n minDiff = float("inf")\n # for each candidate select that and backtrack\n for j in range(n):\n diff = findMinAbsDiff(i+1, prevSum+mat[i][j])\n # pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL\n if diff == 0:\n minDiff = 0\n break\n minDiff = min(minDiff, diff)\n \n dp[i][prevSum] = minDiff\n return minDiff\n \n return findMinAbsDiff(0, 0)\n``` | 25 | You are given an `m x n` integer matrix `mat` and an integer `target`.
Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**.
Return _the **minimum absolute difference**_.
The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13
**Output:** 0
**Explanation:** One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
**Example 2:**
**Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100
**Output:** 94
**Explanation:** The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
**Example 3:**
**Input:** mat = \[\[1,2,9,8,7\]\], target = 6
**Output:** 1
**Explanation:** The best choice is to choose 7 from the first row.
The absolute difference is 1.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 70`
* `1 <= mat[i][j] <= 70`
* `1 <= target <= 800` | null |
Python 3 || 4 lines, sets || T/M: 87% / 47% | minimize-the-difference-between-target-and-chosen-elements | 0 | 1 | ```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\n mat = [set(row) for row in mat]\n \n rSet = set(mat.pop())\n\n for row in mat: rSet = {m+n for m in row for n in rSet}\n \n return min(abs(n - target) for n in rSet)\n\n```\n[https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/submissions/863630229/](http://)\n\n | 5 | You are given an `m x n` integer matrix `mat` and an integer `target`.
Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**.
Return _the **minimum absolute difference**_.
The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13
**Output:** 0
**Explanation:** One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
**Example 2:**
**Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100
**Output:** 94
**Explanation:** The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
**Example 3:**
**Input:** mat = \[\[1,2,9,8,7\]\], target = 6
**Output:** 1
**Explanation:** The best choice is to choose 7 from the first row.
The absolute difference is 1.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 70`
* `1 <= mat[i][j] <= 70`
* `1 <= target <= 800` | null |
85% TC and 84% SC easy python solution | minimize-the-difference-between-target-and-chosen-elements | 0 | 1 | ```\ndef minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\tm = len(mat)\n\tfor i in range(m):\n\t\tmat[i].sort()\n\tq = set([0])\n\tfor i in range(m):\n\t\ttemp = set()\n\t\tfor num1 in q:\n\t\t\tfor num2 in mat[i]:\n\t\t\t\ttemp.add(num1+num2)\n\t\t\t\tif(num1+num2 > target):\n\t\t\t\t\tbreak\n\t\tq = temp\n\tq = sorted(list(q))\n\ti = bisect_right(q, target)\n\tif(i == len(q)):\n\t\treturn target - q[-1]\n\tif(i == 0):\n\t\treturn q[0] - target\n\treturn min(target-q[i-1], q[i]-target)\n``` | 1 | You are given an `m x n` integer matrix `mat` and an integer `target`.
Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**.
Return _the **minimum absolute difference**_.
The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13
**Output:** 0
**Explanation:** One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
**Example 2:**
**Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100
**Output:** 94
**Explanation:** The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
**Example 3:**
**Input:** mat = \[\[1,2,9,8,7\]\], target = 6
**Output:** 1
**Explanation:** The best choice is to choose 7 from the first row.
The absolute difference is 1.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 70`
* `1 <= mat[i][j] <= 70`
* `1 <= target <= 800` | null |
C and Python solutions. C beats 100% in Space and Time. | minimize-the-difference-between-target-and-chosen-elements | 0 | 1 | # Intuition\nStore all the possible sums in a set!\nSets are perfect for checking existence/membership.\n\n# Approach\nAgain, we only need to store all the sums. Better yet, we can break it into sub-problems, and instead use a set, say, `prev`, to store the sums **of a given row**. Then, sum the values stored in the `prev` set with each value in the current row. This will create one new set for each column item in the current row, which is fixed by the matrix. After this, we just join these new sets. This way we will have all the possible sums for the current row. Then we can repeat the process. This is very simple and straightforward to do in Python. But we can also implement a crazy-fast C solution. I will share with you both.\n\nSince the Python solution is simple and readable it needs no explanation. We will then detail and explain the C solution here.\nThe approach is also to use sets. But in a different way: we represent them as maps. We first get ourselves a set of all possible sums, which is the `key` in our map. The possible sums range from 0 to $n$ x $max(a_{ij})$ = 70 x 70 = 4900, not necessarily inclusive, but this is an upper-bound. These are our keys. An item/sum `key` is mapped to either 1 or 0, representing its belonging in the set. This can be represented as a single sequence of bits! The `key` is simply the position in the bit sequence.\n```\n values : 010001010\n keys : 012345678\n```\n\nIn this example, 1, 5 and 7 are the possible sums.\nWe need a 4901-bits-long sequence of bits to represent all possible sums, since the maximum sum in 4900, inclusive. To add an element `value` to all elements in the set, we only need to **shift the keys**:\n```\nAdding 3...\n values : 010001010 or\n 000010001010\n keys : 0123456789ab\n```\n\nSo here comes the cool part about using bits: beyond being hyper efficient in space, using bits, they are also crazy efficient in time! All we need to do to, say, to add an element `value` to all previous sum elements in `prev` is to do a bit shift! Remember, we only need to **shift the keys** in our map. The belonging of a given sum is not affected by a shift.\n\nWith C++\'s bitset we can jump straight to solving the problem.\nThe hard part in C is that we have no such functionality. So we need to actually code the bit shift functionality ourselves. Remember, there is no data type/structure in C with more than 64 bits to do bit-shifting with, much less 4901 bits... So we must work with an array, and define our own custom "bit-shifting" operation for it. Well, I suppose it won\'t be nearly as efficient as a low-level bit shift, obviously, but I presume it will still be very good! Let\'s trust the C compiler.\n\nThe C code uses exactly half the space of the C++ code (6.9MB vs 13.9 MB) and is about 60% slower on time than the C++ solution (185ms vs 115ms). The system says\n`Sorry, there are not enough accepted submissions to show data\n` with a "Beats 100%" on both Space and Time, dunno why. Is that maybe for C submissions only?\n\n# Complexity\n- Time complexity:\n$$O(n^2m^2)$$ in Python, $$O(n^2m * max(a_{ij}))$$ in C.\nWe must iterate over each element in the matrix and add it to the sum list. The complexity of adding each element in a column to each of the current sum sets in Python is $O(m)$, since we have $m$ elements in a column. This makes the final complexity $O(mn^2)$. But in C the complexity of adding each value to the previous set is $O(n*max(a_{ij}))$, since we are shifting all the possible sums. We could say this is constant, since the number of possible sums, $n*max(a_{ij})$, is actually set to 4901. A simple bit shift over a set-size bit sequence is technically $O(1)$.\nAnyway, moving on, we have to join each of the sets that are generated with the `prev` set and each column element. Joining $m$ sets of size $O(nm)$ each is $O(nm^2)$. Doing this for each row we get as final complexity $O(n^2m^2)$. For the C code we get effectively the same, or $O(1)$ if you consider 4901 a constant.\n\n- Space complexity:\n$$O(nm)$$\nIn Python, we have $m$ choices for each row, so the number of combinations is $O(m^n)$. In the worst case all the sums are different and we get this space complexity. But remember, all the sums are contained withing the interval between $0$ and $O(n*max(a_{ij}))$, making the space complexity actually $O(n*max(a_{ij}))$ in the worst case.\nThe same is true for C, but the space complexity in C is again actually $O(1)$ since the memory is fixed at compile-time instead of at runtime in C. Interesting, right?\n\n# Code\nPython\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n prev_sums = {0}\n for row in mat:\n next_sums = set()\n for curr_sum in prev_sums:\n for el in row:\n next_sums.add(el + curr_sum)\n prev_sums = next_sums\n return min({abs(target - curr_sum) for curr_sum in prev_sums}) \n```\nWe could reduce the number of lines in this Python code even further using list comprehension, but this solution has greater readability...\nC\n```\n#include <stdbool.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n\n#define MAX_DIM 70\n#define MAX_VAL 70\n#define TYPE_SIZE 32\n#define BYTE_SIZE 8\n\n#define BITSLOT(i) ((i) / TYPE_SIZE)\n#define BITMASK(i) (((unsigned int)1) << ((i) % TYPE_SIZE))\n#define BITTEST(a, i) ((((a)[BITSLOT(i)] & BITMASK(i))) != 0)\n\n#define BITS_MASK_SIZE 4091\n#define ARR_LENGTH (BITS_MASK_SIZE - 1) / TYPE_SIZE + 1\n#define SIZE_IN_BITS BITS_MASK_SIZE / BYTE_SIZE\n\nvoid display_hexarray(unsigned int* arr){\n\tprintf("\\nHexArray:\\n");\n\tfor(unsigned int i = 0; i < ARR_LENGTH; i++){\n\t\tprintf("%x, ", arr[i]);\n\t}\n\tprintf("\\n");\n}\n\nvoid bitwise_or_inplace(unsigned int* outArray, unsigned int* arg){\n for(unsigned int i = 0; i < ARR_LENGTH; i++){\n outArray[i] |= arg[i];\n }\n}\nvoid bitwise_shift_left(unsigned int* array, unsigned int shift){\n\tif(shift == 0){\n\t\treturn;\n\t}\n\t//display_hexarray(array);\n\tunsigned int index_shift = shift / TYPE_SIZE;\n\tunsigned int bits_shift = shift % TYPE_SIZE;\n\tif(index_shift >= ARR_LENGTH) {\n\t\tindex_shift = ARR_LENGTH;\n\t\tbits_shift = 0;\n\t}\n\tif(bits_shift == 0){\n\t\tfor(unsigned int i = ARR_LENGTH - 1; i >= index_shift; --i) {\n\t\t\tarray[i] = array[i - index_shift];\n\t\t}\n\t\tfor(unsigned int i = 0; i < index_shift; ++i) {\n\t\t\tarray[i] = 0;\n\t\t}\n\t\treturn;\n\t}\n\n\tfor(unsigned int i = ARR_LENGTH - 1; i > index_shift; --i) {\n\t\tarray[i] = array[i - index_shift] << bits_shift;\n\t\tarray[i] |= array[i - index_shift-1] >> TYPE_SIZE - bits_shift;\n\t}\n\tarray[index_shift] = array[0] << bits_shift;\n\tif(index_shift <= 0) return;\n\tfor(unsigned int i = 0; i < index_shift; i++) {\n\t\tarray[i] = 0;\n\t}\n}\n\nint minimizeTheDifference(int** mat, int matSize, int* matColSize, int target){\n\tunsigned int min, max;\n\tmax = matSize * matColSize[0] * MAX_VAL;\n\tmin = target + max;\n\n\t// This is basically a map. Each key maps to 0 or 1.\n\t// This mapping represents a set!\n\t// If an element is present in the set, the bit value is set to 1.\n\t// A simple shift then represents an addition over all elements in the set!\n\tunsigned int previousSet[ARR_LENGTH];\n\tmemset(previousSet, 0, SIZE_IN_BITS);\n\tpreviousSet[0] = 0x01;\n\t//display_hexarray(previousSet);\n\n\tfor(unsigned int i=0; i < matSize; i++){\n\t\t//printf("\\nNEXT COLUMN\\n");\n\t\t//display_hexarray(previousSet);\n\n\t\t// New empty map of values\n\t\tunsigned int currentSet[ARR_LENGTH];\n\t\tmemset(currentSet, 0, SIZE_IN_BITS);\n\n\t\tfor(unsigned int j=0; j < *matColSize; j++){\n\t\t\tunsigned int currValue = mat[i][j];\n\n\t\t\t// Temporary array to store shift\n\t\t\t// Stores intially a copy of the previous set\n\t\t\tunsigned int tmp[ARR_LENGTH];\n\t\t\tmemcpy(tmp, previousSet, SIZE_IN_BITS);\n\t\t//display_hexarray(tmp);\n\n\t\t\t//printf("\\nVal: %i\\n", currValue);\n\t\t//display_hexarray(currentSet);\n\t\t\t// Add current value to all elements in "temp"\n\t\t\tbitwise_shift_left(tmp, currValue);\n\t\t//display_hexarray(currentSet);\n\t\t\t// Join tmp into currentSet\n\t\t\tbitwise_or_inplace(currentSet, tmp);\n\t\t//display_hexarray(currentSet);\n\t\t}\n\t\t//display_hexarray(currentSet);\n\t\tmemcpy(previousSet, currentSet, SIZE_IN_BITS);\n\t}\n\tfor(unsigned int currSum=0; currSum < BITS_MASK_SIZE; currSum++){\n\t\t// Current Sum is present!\n\t\tif(BITTEST(previousSet, currSum)){\n\t\t\t//printf("%i, ", currSum);\n\t\t\tunsigned int dist = abs(target - currSum);\n\t\t\tif(dist < min){\n\t\t\t\tmin = dist;\n\t\t\t}\n\t\t\tif(min == 0) return 0;\n\t\t}\n\t}\n\treturn min;\n}\n```\nAlso, here is the C++ code that inspired me try writing the solution in C. I\'m honestly impressed my clumsy array-bit-shifting operation actually surpassed it...\nC++\n```\nclass Solution {\npublic:\n int minimizeTheDifference(vector<vector<int>>& mat, int target) {\n int maxSum = 70 * mat.size();\n\n // This is basically a map. Each key maps to 0 or 1.\n // This mapping represents a set!\n // If an element is present in the set, the bit value is set to 1.\n // A simple shift then represents an addition over all elements in the set!\n bitset<4901> previousSet;\n // 0 only is present in the set\n previousSet[0] = 1;\n for(vector<int> row : mat){\n bitset<4901> currentSet;\n for(int value : row){\n // Add value to each element in the set\n // Remember, the values are represented by the keys that map to 1\n bitset<4901> incrementedSet = previousSet << value;\n\n // Join the two sets\n currentSet = currentSet | incrementedSet;\n }\n previousSet = currentSet;\n }\n int minimum = abs(maxSum + target);\n for (int currSum = 0; currSum < 4901; ++currSum) {\n // Element currSum is in the set!\n if (previousSet[currSum]) {\n int distance = abs(currSum - target);\n minimum = min(minimum, distance);\n }\n }\n return minimum;\n }\n};\nint main(){\n\tSolution().minimizeTheDifference(vector<vector<int>>& mat, int target) {\n}\n```\n\nFor anyone who says C is easy to code, this took me 3 days of suffering through compile-time and runtime errors, being totally honest. Python took me a few minutes... But I got the damn "Beats 100%" in both Space and Time, so maybe that was worth the effort haha. | 0 | You are given an `m x n` integer matrix `mat` and an integer `target`.
Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**.
Return _the **minimum absolute difference**_.
The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`.
**Example 1:**
**Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13
**Output:** 0
**Explanation:** One possible choice is to:
- Choose 1 from the first row.
- Choose 5 from the second row.
- Choose 7 from the third row.
The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.
**Example 2:**
**Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100
**Output:** 94
**Explanation:** The best possible choice is to:
- Choose 1 from the first row.
- Choose 2 from the second row.
- Choose 3 from the third row.
The sum of the chosen elements is 6, and the absolute difference is 94.
**Example 3:**
**Input:** mat = \[\[1,2,9,8,7\]\], target = 6
**Output:** 1
**Explanation:** The best choice is to choose 7 from the first row.
The absolute difference is 1.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 70`
* `1 <= mat[i][j] <= 70`
* `1 <= target <= 800` | null |
Easy Explanation for Noobs + Python code with comments | find-array-given-subset-sums | 0 | 1 | **Some key principles of a set that we will use to construct our solution**\n1. If the size of a set is `n` then its superset has a size of `2^n`. Hence, any superset is always divisible in two equal parts.\n2. Any superset must have an empty set. The sum of elements of any empty set is `0`, hence any set containing all subset sums must contain `0` as an element.\n3. Any superset can be divided into two parts with equal size, such that one part has all the subsets `excluding` an element `x` and the other one has all the subsets `including` the element `x`. In such a case, the `excluding` set corresponds to the superset of the original set after removing the element `x` from it. For example, let the original set be `set={x, y, z}`, then\n\t* its superset is `superset={ {}, {x}, {y}, {z}, {x, y}, {x, z}, {y, z}, {x, y, z} }`. \n\t* the superset can be divided into two equal parts based on the element `x` like `excluding={ {}, {y}, {z}, {y, z}}` and `including={ {x}, {x, y}, {x, z}, {x, y, z} }`. \n\t* the `excluding` set corresponds to the superset of the set `{y, z}`. Now since `excluding` is a superset too, it must have a size of `2^(n-1)` (using principle 1). This should give us an idea on how to approach the solution. \n4. The `excluding` set must contain the empty set `{}` as an element.\n5. Multiple sets can result in the same superset i.e. given a superset there can be multiple solution sets that are valid. For example, `{2, 3, -5}` and `{-2, -3, 5}` both have same superset. \n\n**Intuition**\nFrom the pt 3 above, it looks like given a superset, if we can somehow get one element of the original set, and if somehow we can figure out the `excluding` set then we can re-apply the same steps repeatedly (on the `excluding` set this time) till we have figured out all the elements. \n\nThe questions that need to be answered are: \n1. How to find an element of the original set (since we are given subset **sum** instead of subsets) ?\n2. How to find the `excluding` set ?\n\n **How to find an element of the original set ?**\nPlease note that if we take the maximum and the second maximum elements of the subset sums (say `max` and `secondMax`), then `secondMax` can be obtained from `max` by doing one of the following:\n1. remove the least non-negative element from the `max`.\n2. add the largest (least if absolute value is considered) negative element to the `max`. \nFor example, for the set `{-1, -2, 3, 4}` the `max` element in the superset is `7` (corresponding to subset `{3, 4}`) and the `secondMax` element in the superset is `6` (corresponding to subset `{3, 4, -1}`). Here `-1` is the largest negative number (least if absolute value is considered). \nHence, if `diff = max - secondMax` then, either `diff` or `-1*diff` is a member of the original set. Now here we can choose either `diff` or `-1*diff` based on which one is a plausible value. In many cases any of the both `diff` or `-1*diff` can be chosen (using principle 5 of key principles). We can check for the plausiblity based on the empty set being a part of the `excuding` set (using principle 4 of key principles). If the `excluding` set does not contain the value `0` (corresponding to the empty set), then we would include `-1*diff` in our solution set (as the `including` set would become the true `excluding` set in this case). \n\n**How to find the `excluding` set ?**\nTo find the `excluding` set we start with the assumption that `diff` (from above) is a valid member of the solution set. Please note that `diff` is always non-negative. Hence, the least element of subset sum must belong to `excluding` set and the max element must belong to the `including` set. Hence, we can sort the subset sum in increasing order, pick the least element and add it to the `excluding` set and add the least + `diff` element to the `including` set. Please note that a least + `diff` element must exist (using principle 3 of key principles). We can keep adding elements to `excluding` and `including` sets like this by iterating over the sorted subset sums.\nOnce we have the `excluding` set with us, we can check its validity by checking if `0` is a part of it (using principle 4 of key principles). If not, then `including` set must have it (since any subset sum must have a `0` (using principle 2 of key principles)). This implies that `including` set is the actual `excluding` set and that `secondMax` was actually obtained by adding a negative number to `max` and not by removing a postive number. Hence, we add `-1*diff` to our result set instead. \n\n**Code**\n```\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n res = [] # Result set\n sums.sort()\n \n while len(sums) > 1:\n num = sums[-1] - sums[-2] # max - secondMax\n countMap = Counter(sums) # Get count of each elements\n excluding = [] # Subset sums that do NOT contain num\n including = [] # Subset sums that contain num\n \n for x in sums:\n if countMap.get(x) > 0:\n excluding.append(x)\n including.append(x+num)\n countMap[x] -= 1\n countMap[x+num] -= 1\n \n\t\t\t# Check validity of excluding set\t\n if 0 in excluding:\n sums = excluding\n res.append(num)\n else:\n sums = including\n res.append(-1*num)\n \n return res\n```\n | 81 | You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order).
Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **multiple** answers exist, return **any** of them_.
An array `sub` is a **subset** of an array `arr` if `sub` can be obtained from `arr` by deleting some (possibly zero or all) elements of `arr`. The sum of the elements in `sub` is one possible **subset sum** of `arr`. The sum of an empty array is considered to be `0`.
**Note:** Test cases are generated such that there will **always** be at least one correct answer.
**Example 1:**
**Input:** n = 3, sums = \[-3,-2,-1,0,0,1,2,3\]
**Output:** \[1,2,-3\]
**Explanation:** \[1,2,-3\] is able to achieve the given subset sums:
- \[\]: sum is 0
- \[1\]: sum is 1
- \[2\]: sum is 2
- \[1,2\]: sum is 3
- \[-3\]: sum is -3
- \[1,-3\]: sum is -2
- \[2,-3\]: sum is -1
- \[1,2,-3\]: sum is 0
Note that any permutation of \[1,2,-3\] and also any permutation of \[-1,-2,3\] will also be accepted.
**Example 2:**
**Input:** n = 2, sums = \[0,0,0,0\]
**Output:** \[0,0\]
**Explanation:** The only correct answer is \[0,0\].
**Example 3:**
**Input:** n = 4, sums = \[0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8\]
**Output:** \[0,-1,4,5\]
**Explanation:** \[0,-1,4,5\] is able to achieve the given subset sums.
**Constraints:**
* `1 <= n <= 15`
* `sums.length == 2n`
* `-104 <= sums[i] <= 104` | Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number. |
Divide and Conquer in Python 3, Example Explained | find-array-given-subset-sums | 0 | 1 | Basically I did the following:\n1. Sort the summaries.\n2. Divide it by two groups so that every single value in the higher group has a conterpart in lower group. And the differences (set it to positive for now) are the same among all such pairs.\n3. If zero is in lower group, return the lower group and the difference, if not, return the higher one and the inversed difference. Because if we take the group doesn\'t have any zeros, at last we can\'t get the zero-valued summary, which is the value for an empty subset. If zero exists on both groups it means one of the diff (a number in the original array) must be zero and we can choose arbitrarily.\n4. Redo step 2 and 3 until the summaries are only [0] and meanwhile collect the differences.\n5. The differences are the original array.\n\nAn random example:\noriginal array -> [-9, 5, 11]\nsubset summaries -> [-9, -4, 0, 2, 5, 7, 11, 16]\n\niteration 1:\ndiff -> 9\nlows-> [-9, -4, 2, 7]\nhigh -> [*0*, 5, 11, 16] (zero is here)\nwe get diff as **-9** and work on the **high** group\n\niteration 2:\ndiff -> 5\nlow -> [*0*, 11] (zero is here)\nhigh -> [5, 16]\nwe get diff as **5** and work on the **low** group\n\niteration 3:\ndiff -> 11\nlow -> [*0*] (zero is here)\nhigh -> [11]\nwe get diff as **11** and work on the **low** group (well actually not)\n\nAnd the answer is [-9, 5, 11]\n\n```\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n sums.sort()\n ans = []\n while len(sums) > 1:\n ele, sums = self._recoverArray(sums)\n ans.append(ele)\n return ans\n\n def _recoverArray(self, sums: List[int]) -> [int, List]:\n max_val = max(sums)\n L = len(sums)\n sums_map = {}\n for val in sums:\n if val not in sums_map:\n sums_map[val] = 0\n sums_map[val] += 1\n sorted_vals = sorted(sums_map.keys())\n init_low = sorted_vals[0]\n sums_map[init_low] -= 1\n if sums_map[init_low] == 0:\n del sums_map[init_low]\n sorted_vals.pop(0)\n for high in sorted_vals:\n _sums_map = sums_map.copy()\n _sums_map[high] -= 1\n if _sums_map[high] == 0:\n del _sums_map[high]\n count = 2\n diff = high - init_low\n ans = [init_low]\n for low in sorted_vals:\n skip_all_the_way = False\n while low in _sums_map:\n _sums_map[low] -= 1\n if _sums_map[low] == 0:\n del _sums_map[low]\n high = low + diff\n if high not in _sums_map:\n skip_all_the_way = True\n break\n _sums_map[high] -= 1\n if _sums_map[high] == 0:\n del _sums_map[high]\n count += 2\n ans.append(low)\n if count == L:\n skip_all_the_way = True\n break\n if skip_all_the_way:\n break\n if count == L:\n if 0 in set(ans):\n return [diff, ans]\n return [-diff, [num + diff for num in ans]]\n``` | 6 | You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order).
Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **multiple** answers exist, return **any** of them_.
An array `sub` is a **subset** of an array `arr` if `sub` can be obtained from `arr` by deleting some (possibly zero or all) elements of `arr`. The sum of the elements in `sub` is one possible **subset sum** of `arr`. The sum of an empty array is considered to be `0`.
**Note:** Test cases are generated such that there will **always** be at least one correct answer.
**Example 1:**
**Input:** n = 3, sums = \[-3,-2,-1,0,0,1,2,3\]
**Output:** \[1,2,-3\]
**Explanation:** \[1,2,-3\] is able to achieve the given subset sums:
- \[\]: sum is 0
- \[1\]: sum is 1
- \[2\]: sum is 2
- \[1,2\]: sum is 3
- \[-3\]: sum is -3
- \[1,-3\]: sum is -2
- \[2,-3\]: sum is -1
- \[1,2,-3\]: sum is 0
Note that any permutation of \[1,2,-3\] and also any permutation of \[-1,-2,3\] will also be accepted.
**Example 2:**
**Input:** n = 2, sums = \[0,0,0,0\]
**Output:** \[0,0\]
**Explanation:** The only correct answer is \[0,0\].
**Example 3:**
**Input:** n = 4, sums = \[0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8\]
**Output:** \[0,-1,4,5\]
**Explanation:** \[0,-1,4,5\] is able to achieve the given subset sums.
**Constraints:**
* `1 <= n <= 15`
* `sums.length == 2n`
* `-104 <= sums[i] <= 104` | Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number. |
Divide and conquer (beats 100% at the time of writing) | find-array-given-subset-sums | 0 | 1 | # Intuition\n\nWhat matters is the subset sum values and their multiplicities.\nThe largest possible subset sum value for example is the sum of all non-negative elements in the array and its multiplicity is the $2^k$ where $k$ is the numver of zeros in the array. Then $2^k$ is a factor in all multiplicities and after division we can assume that the array contains non-zero values.\n\nIf $d$ is the difference of the two largest possible subset sum values then either $d$ or $-d$ is in the array. And it is possible to compute the subset sum values for both cases after erasing this element from the array. So it is possible to reduce the problem to a smaller one. Which can be reduced to a smaller one and so on. A set of subset sums always contains zero and this is the way to check if a the selected value $d$ or $-d$ can lead to a solution. \n\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n2^n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ndef split(sums, d):\n possible = True\n d_in = {}\n d_out = {}\n it = iter(sums)\n a = next(it)\n d_in[a] = sums[a]\n for b in it:\n if b+d in d_in:\n d_out[b] = d_in[b + d]\n if sums[b] > d_in[b+d]:\n d_in[b] = sums[b] - d_in[b+d]\n elif sums[b] < d_in[b+d]:\n return None\n else:\n d_in[b] = sums[b]\n return (-d, d_in), (d, d_out)\n\ndef try_to_solve(n, sums):\n if n==0:\n return []\n keys = iter(sums)\n d = next(keys) - next(keys)\n options = split(sums, d)\n if not options:\n return None\n for v, option in options:\n if 0 not in option:\n continue\n ans = try_to_solve(n-1, option)\n if ans is not None:\n return ans + [v]\n return None\n\n\ndef div_with_check(a, b):\n frac, r = divmod(a, b)\n # assert r == 0\n return frac\n\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n sums = sorted(collections.Counter(sums).items(), reverse=True)\n multiplicity = sums[0][1]\n sums = {k: div_with_check(cnt, multiplicity) for k, cnt in sums}\n ## multiplicity is a power of two!\n num_zeros = 0\n while multiplicity > 1:\n num_zeros += 1\n multiplicity >>= 1\n\n return [0]*num_zeros + try_to_solve(n-num_zeros, sums)\n\n``` | 0 | You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order).
Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **multiple** answers exist, return **any** of them_.
An array `sub` is a **subset** of an array `arr` if `sub` can be obtained from `arr` by deleting some (possibly zero or all) elements of `arr`. The sum of the elements in `sub` is one possible **subset sum** of `arr`. The sum of an empty array is considered to be `0`.
**Note:** Test cases are generated such that there will **always** be at least one correct answer.
**Example 1:**
**Input:** n = 3, sums = \[-3,-2,-1,0,0,1,2,3\]
**Output:** \[1,2,-3\]
**Explanation:** \[1,2,-3\] is able to achieve the given subset sums:
- \[\]: sum is 0
- \[1\]: sum is 1
- \[2\]: sum is 2
- \[1,2\]: sum is 3
- \[-3\]: sum is -3
- \[1,-3\]: sum is -2
- \[2,-3\]: sum is -1
- \[1,2,-3\]: sum is 0
Note that any permutation of \[1,2,-3\] and also any permutation of \[-1,-2,3\] will also be accepted.
**Example 2:**
**Input:** n = 2, sums = \[0,0,0,0\]
**Output:** \[0,0\]
**Explanation:** The only correct answer is \[0,0\].
**Example 3:**
**Input:** n = 4, sums = \[0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8\]
**Output:** \[0,-1,4,5\]
**Explanation:** \[0,-1,4,5\] is able to achieve the given subset sums.
**Constraints:**
* `1 <= n <= 15`
* `sums.length == 2n`
* `-104 <= sums[i] <= 104` | Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number. |
90% Runtime, 85% Memory with Simple Code | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | \n\n# Approach\n`res = nums[k-1] - nums[0]`\nSince nums is sorted, `nums[k-1] - nums[0]` returns max dif.\n\n`res = min(res, nums[i] - nums[i - k + 1])`\nFrom window of size k, the far left is the minimum \nand far right is the maximum value in the window since nums is sorted. \n`nums[i]` : Far right\n`nums[i - k + 1])` : Far left\nSo "far right" - "far left" returns min dif.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n if len(nums) <= 1:\n return 0\n\n nums.sort()\n res = nums[k-1] - nums[0]\n\n for i in range(k, len(nums)):\n res = min(res, nums[i] - nums[i - k + 1])\n\n return res\n\n \n``` | 1 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python simple solution | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | **Python :**\n\n```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n\tif len(nums) <= 1:\n\t\treturn 0\n\n\tnums = sorted(nums)\n\tres = nums[k-1] - nums[0]\n\n\tfor i in range(k, len(nums)):\n\t\tres = min(res, nums[i] - nums[i - k + 1])\n\n\treturn res\n```\n\n**Like it ? please upvote !** | 32 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python 2 line + CPP Soln With Explanation | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | ```\nThis Q is asking what is the minimum difference between nums[i] and nums[i+(k-1)] for all.\n k-1 beacuse Total K Values = from nums[i] to nums[i+k-1]\n ------- -----------\n 1 value k-1 values\n = 1 + k-1\n = k values\n```\n```\nnums = [7, 1, 9, 3] , k = 2\n\nfor the value nums[1] = 1, ONLY 3 - 1 = 2 WHICH IS THE MINIMUM AMONG 7 - 1 = 6 and 9 - 1 = 8.\nBecause the closest MINIMUM value of 1 is 3. 7 and 9 are far away from 1.\n" So the far they are, the more difference it is. " \n```\n```\nSo sort and compare the minimum for every i by creating a "sliding window" at first\nlike : minDiff = nums[k-1]-nums[0] \nNow move this window till the i for which k exist means for nums[i] there exists a nums[k]\n```\n```Python []\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min( nums[i+k-1]-nums[i] for i in range(len(nums)-k+1) )\n```\n```CPP []\nclass Solution \n{\npublic:\n int minimumDifference(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int minDiff = nums[k-1]-nums[0], n = nums.size()-k+1;\n for(int i=1;i<n;i++)\n minDiff = min(minDiff,nums[i+k-1]-nums[i]);\n return minDiff;\n }\n};\n```\n```\nTime complexity : O(nlogn)\nSpace complexity : O(1)\n``` | 2 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python3 Beats 99% sliding window of length K | minimum-difference-between-highest-and-lowest-of-k-scores | 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 minimumDifference(self, nums: List[int], k: int) -> int:\n #sliding window\n nums.sort()\n l, r = 0, k-1\n res = float("inf")\n while r < len(nums):\n res = min(res, nums[r] - nums[l])\n r += 1\n l += 1\n return res\n\n\n\n``` | 2 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python || 99.43% Faster || Sliding Window + Sorting | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | ```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n m,n=100001,len(nums)\n i,j=0,k-1\n while j<n:\n m=min(m,nums[j]-nums[i])\n i+=1\n j+=1\n return m\n```\n\n**An upvote will be encouraging** | 6 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python 99.70% time solution (beginner friendly) | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the input array first so it is easier to work with, then implement sliding window approach\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the input array so we can know what the lowest and highest number in the sliding window is easily; then use a loop to go through the array with a sliding window of length k, then the result will be the minimum of what it is currently and nums[right] - nums[left]\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(NlogN)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) from sorting\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n result = float(\'inf\')\n left = 0\n for right in range(k - 1, len(nums)):\n result = min(result, nums[right] - nums[left])\n left += 1\n return result\n``` | 1 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python Solution | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | # Intuition\nThe hardest issue was trying to figure out how to calculate the difference, based on the number of k students, no matter the size of the list. And then check each difference and compare it to the minimum difference, and then return the lowest possible difference. \n\n# Approach\nSimple usage of python built in functions for sorting nums and calculating the min diff, and then return the min diff after comparing it to each possible difference calcultion\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums = sorted(nums)\n return_diff = float(\'inf\')\n for num in range(len(nums)-k + 1):\n current_diff = nums[num+k-1] - nums[num]\n if current_diff < return_diff:\n return_diff = current_diff\n\n return return_diff\n\n\n``` | 2 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Simple and short Python solution O(n) | minimum-difference-between-highest-and-lowest-of-k-scores | 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 minimumDifference(self, nums: List[int], k: int) -> int:\n \n #CODE\n # - Initiall we want to sort the list\n # - We compare the k sized window with the l and r numbers difference\n # - Update min global variable if less than it\n\n l, r = 0, k\n minDiff = float(\'inf\')\n nums.sort()\n \n while r <= len(nums):\n minDiff = min(minDiff, abs(nums[r-1] - nums[l]))\n r += 1\n l += 1\n \n return minDiff\n``` | 0 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
nlogn | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort() # we sort the element\n l,r = 0,k-1\n res = float("inf")\n\n while r < len(nums):\n res = min(res,nums[r]-nums[l])\n l,r = l+1,r+1\n return res\n\n# time complexity -- O(Nlogn)\n``` | 1 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Python-3- sliding window | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | Slide the window and update the min. each time we increase the window, if needed!\n\n```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n l, r = 0, k-1\n \n minDiff = float(\'inf\')\n \n while r < len(nums):\n minDiff = min(minDiff, nums[r] - nums[l])\n l, r = l+1, r+1\n \n return minDiff \n``` | 10 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Best Easy approach || 96.84% Beat || Python | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | # Intuition\nSorting\n\n# Approach\nSliding Window\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(K)\n\n# Code\n```\nimport math\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n lst=[]\n res=math.inf\n nums.sort()\n for i in range(len(nums)-k+1):\n lst=nums[i:i+k]\n res=min(res,lst[-1]-lst[0])\n return res\n``` | 1 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
Minimum Difference Between Highest and Lowest of K Scores | minimum-difference-between-highest-and-lowest-of-k-scores | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing list append method and two pointer algorithm\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ntwo pointer algorithm\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nn\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n a=[]\n i=0\n j=k-1\n nums=sorted(nums)\n if(len(nums)!=1):\n while(j<=len(nums)-1):\n a.append(nums[j]-nums[i])\n i=i+1\n j=j+1\n else:\n return(0)\n return min(a)\n``` | 1 | You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`.
Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**.
Return _the **minimum** possible difference_.
**Example 1:**
**Input:** nums = \[90\], k = 1
**Output:** 0
**Explanation:** There is one way to pick score(s) of one student:
- \[**90**\]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
**Example 2:**
**Input:** nums = \[9,4,1,7\], k = 2
**Output:** 2
**Explanation:** There are six ways to pick score(s) of two students:
- \[**9**,**4**,1,7\]. The difference between the highest and lowest score is 9 - 4 = 5.
- \[**9**,4,**1**,7\]. The difference between the highest and lowest score is 9 - 1 = 8.
- \[**9**,4,1,**7**\]. The difference between the highest and lowest score is 9 - 7 = 2.
- \[9,**4**,**1**,7\]. The difference between the highest and lowest score is 4 - 1 = 3.
- \[9,**4**,1,**7**\]. The difference between the highest and lowest score is 7 - 4 = 3.
- \[9,4,**1**,**7**\]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.
**Constraints:**
* `1 <= k <= nums.length <= 1000`
* `0 <= nums[i] <= 105` | Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at least as far as the farthest j such that nums2[j] ≥ nums1[i-1] |
beats 99.5% | find-the-kth-largest-integer-in-the-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n # time complexity -- O(klogn)\n\n maxHeap = [-int(n) for n in nums]\n heapq.heapify(maxHeap)\n\n while k > 1:\n heapq.heappop(maxHeap)\n k-=1\n return str(-maxHeap[0])\n \n``` | 1 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
2 line code in python | find-the-kth-largest-integer-in-the-array | 0 | 1 | \nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n l=list(map(int,nums))\n l.sort()\n return str(l[-k])\n``` | 1 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
Best python 3 solution , beats 92% ms | find-the-kth-largest-integer-in-the-array | 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 kthLargestNumber(self, nums: List[str], k: int) -> str:\n ls = []\n for i in nums:\n ls.append(int(i))\n sorted_ = sorted(ls)\n return str(sorted_[-1*k])\n``` | 2 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
Python || 1 Liner || 94.90% Faster || Sorting | find-the-kth-largest-integer-in-the-array | 0 | 1 | ```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n return sorted(nums, key= lambda i : int(i))[-k]\n```\n\n**An upvote will be encouaging** | 4 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
Python | The Right Way during Interview | Comparators | find-the-kth-largest-integer-in-the-array | 0 | 1 | Although, this ways works, ie by directly converting all string to integer. Then sort and reverse.\n\n```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n nums = sorted(map(int, nums), reverse=True)\n return str(nums[k-1])\n```\n\nThis works because there is no limit to size of int in Python, here 100 digits. So it works, but it only works in Python, not in any other. And it may not work if the length of string is much larger or even if work ,can take large memory. So you can\'t risk using this method in actual interview. This is the correct way.\n\nBy sorting based on customize sort function, which sorts x and y like\n1. when left is smaller, then -1, to keep left on left, \n2. when left is larger, then +1, to put on right\n\n\'4\', \'33\' - len of 4 is smaller, so left smaller, -1\n\'555\', \'66\' - len of 555 is larger, so right larger, +1\n\'342\', \'312\' - left if larger, so +1\n\'11\', \'11\', - both same, so 0\n\ncmp_to_key - is an comparator in python, used to create customized sort based on compare conditions (x, y for eg, in default sort, if x < y then x stays on left, else x goes on right of y).\n\n```\nfrom functools import cmp_to_key\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n def sorter(x, y):\n n, m = len(x), len(y)\n if n < m: # if you want to keep x in left of y, return -1, here if len(x) is shorter, so it is smaller, so left # [\'33\', \'4\'], 4 to left\n return -1\n elif n > m: # +1, if to keep in right of y\n return 1\n else:\n for i in range(n):\n if x[i] < y[i]: # if x[i] smaller, then left\n return -1\n elif x[i] > y[i]: # else in right \n return 1\n else:\n continue\n return 0 # if both same, x==y\n \n key = cmp_to_key(sorter)\n nums.sort(key=key, reverse=True)\n # print(nums)\n return nums[k-1]\n```\n\nUpper Code in more concise form -\n\n```\nfrom functools import cmp_to_key\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n def sorter(x, y):\n n, m = len(x), len(y)\n if n != m:\n return -1 if n < m else 1 # when n > m\n else:\n return -1 if x < y else 1 if x > y else 0\n \n key = cmp_to_key(sorter)\n nums.sort(key=key, reverse=True)\n return nums[k-1]\n```\n\n**Please give this a Upvote if you liked my effort.** | 40 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
Best python 3 solution , beats 92% ms | find-the-kth-largest-integer-in-the-array | 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 kthLargestNumber(self, nums: List[str], k: int) -> str:\n ls = []\n for i in nums:\n ls.append(int(i))\n sorted_ = sorted(ls)\n return str(sorted_[-1*k])\n``` | 1 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
Classic quick select algorithm in Python | find-the-kth-largest-integer-in-the-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n), with the worst case O(n^2)\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 kthLargestNumber(self, nums: List[str], k: int) -> str:\n \n def _quick_select_(nums, k):\n left, mid, right = [],[], []\n pivot = random.choice(nums)\n\n for num in nums:\n if int(num) > int(pivot):\n left.append(num)\n elif int(num) < int(pivot):\n right.append(num)\n else:\n mid.append(num)\n \n if k <= len(left):\n return _quick_select_(left, k)\n\n if k > len(left) + len(mid):\n return _quick_select_(right, k - len(left) - len(mid))\n\n return pivot\n \n return _quick_select_(nums, k)\n``` | 1 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
2 GENEROUS lines of code, 70% TC and 57% SC | find-the-kth-largest-integer-in-the-array | 0 | 1 | ```\ndef kthLargestNumber(self, nums: List[str], k: int) -> str:\n\tnums.sort(key = lambda x:int(x), reverse = True)\n\treturn nums[k-1]\n``` | 1 | You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros.
Return _the string that represents the_ `kth` _**largest integer** in_ `nums`.
**Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 "` is the first largest integer, `"2 "` is the second-largest integer, and `"1 "` is the third-largest integer.
**Example 1:**
**Input:** nums = \[ "3 ", "6 ", "7 ", "10 "\], k = 4
**Output:** "3 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "3 ", "6 ", "7 ", "10 "\].
The 4th largest integer in nums is "3 ".
**Example 2:**
**Input:** nums = \[ "2 ", "21 ", "12 ", "1 "\], k = 3
**Output:** "2 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "1 ", "2 ", "12 ", "21 "\].
The 3rd largest integer in nums is "2 ".
**Example 3:**
**Input:** nums = \[ "0 ", "0 "\], k = 2
**Output:** "0 "
**Explanation:**
The numbers in nums sorted in non-decreasing order are \[ "0 ", "0 "\].
The 2nd largest integer in nums is "0 ".
**Constraints:**
* `1 <= k <= nums.length <= 104`
* `1 <= nums[i].length <= 100`
* `nums[i]` consists of only digits.
* `nums[i]` will not have any leading zeros. | Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array? |
1987. Number of Unique Good Subsequences [Python] | number-of-unique-good-subsequences | 0 | 1 | \n\n```python\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n mod = 10**9 + 7\n dp = [[0, 0] for _ in range(2)] # dp[i][j] represents count of subsequences ending at index i with last element j (0 or 1)\n n = len(binary)\n \n for ch in binary:\n if ch == \'0\':\n # For a \'0\', we have two cases:\n # 1. Extend the subsequences ending with \'0\' by one more \'0\'.\n # 2. Extend the subsequences ending with \'1\' by appending this \'0\' to form new subsequences.\n dp[0][0] = 1\n dp[1][0] = (dp[1][0] + dp[1][1]) % mod\n else:\n # For a \'1\', we have one case:\n # Extend the subsequences ending with \'0\' or \'1\' by appending this \'1\' to form new subsequences.\n dp[1][1] = (dp[1][0] + dp[1][1] + 1) % mod\n \n # The answer is the sum of counts of subsequences ending with \'0\' and \'1\',\n # considering all the possibilities.\n result = (dp[0][0] + dp[0][1] + dp[1][0] + dp[1][1]) % mod\n return result\n\n# Create an instance of the Solution class\nsol = Solution()\n\n# Test cases\nprint(sol.numberOfUniqueGoodSubsequences("001")) # Output: 2\nprint(sol.numberOfUniqueGoodSubsequences("11")) # Output: 2\nprint(sol.numberOfUniqueGoodSubsequences("101")) # Output: 5\n```\n\n**Intuition:**\n\nThe algorithm works by maintaining two sets of counts for each index: `dp[i][0]` represents the count of subsequences ending at index `i` with the last element being \'0\', and `dp[i][1]` represents the count of subsequences ending at index `i` with the last element being \'1\'. \n\nWhen a \'0\' is encountered, two possibilities arise:\n1. We can extend the subsequences ending with \'0\' by one more \'0\', and this count is updated in `dp[0][0]`.\n2. We can append this \'0\' to subsequences ending with \'1\', creating new subsequences, and this count is updated in `dp[1][0]`.\n\nWhen a \'1\' is encountered, we can extend the subsequences ending with \'0\' or \'1\' by appending this \'1\' to form new subsequences. This count is updated in `dp[1][1]`.\n\nFinally, the answer is the sum of counts of subsequences ending with \'0\' and \'1\', considering all the possibilities.\n\n**Time Complexity:**\n\nThe algorithm iterates through the binary string once, performing constant time operations for each character. Hence, the time complexity is O(N), where N is the length of the binary string. The space complexity is O(1) since we are using a fixed-size array for dynamic programming.\n\n# Code\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n mod = 10**9 + 7\n dp = [[0, 0] for _ in range(2)]\n n = len(binary)\n \n for ch in binary:\n if ch == \'0\':\n dp[0][0] = 1\n dp[1][0] = (dp[1][0] + dp[1][1]) % mod\n else:\n dp[1][1] = (dp[1][0] + dp[1][1] + 1) % mod\n \n return (dp[0][0] + dp[0][1] + dp[1][0] + dp[1][1]) % mod\n``` | 2 | You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`).
Find the number of **unique good subsequences** of `binary`.
* For example, if `binary = "001 "`, then all the **good** subsequences are `[ "0 ", "0 ", "1 "]`, so the **unique** good subsequences are `"0 "` and `"1 "`. Note that subsequences `"00 "`, `"01 "`, and `"001 "` are not good because they have leading zeros.
Return _the number of **unique good subsequences** of_ `binary`. Since the answer may be very large, return it **modulo** `109 + 7`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** binary = "001 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "0 ", "0 ", "1 "\].
The unique good subsequences are "0 " and "1 ".
**Example 2:**
**Input:** binary = "11 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "1 ", "1 ", "11 "\].
The unique good subsequences are "1 " and "11 ".
**Example 3:**
**Input:** binary = "101 "
**Output:** 5
**Explanation:** The good subsequences of binary are \[ "1 ", "0 ", "1 ", "10 ", "11 ", "101 "\].
The unique good subsequences are "0 ", "1 ", "10 ", "11 ", and "101 ".
**Constraints:**
* `1 <= binary.length <= 105`
* `binary` consists of only `'0'`s and `'1'`s. | Try using a set to find out the number of distinct characters in a substring. |
Python (Simple Maths) | number-of-unique-good-subsequences | 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 numberOfUniqueGoodSubsequences(self, binary):\n ans = [0]*2\n\n for i in binary:\n ans[int(i)] = sum(ans) + int(i)\n\n return (sum(ans) + ("0" in binary))%(10**9+7)\n\n\n\n\n\n\n``` | 2 | You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`).
Find the number of **unique good subsequences** of `binary`.
* For example, if `binary = "001 "`, then all the **good** subsequences are `[ "0 ", "0 ", "1 "]`, so the **unique** good subsequences are `"0 "` and `"1 "`. Note that subsequences `"00 "`, `"01 "`, and `"001 "` are not good because they have leading zeros.
Return _the number of **unique good subsequences** of_ `binary`. Since the answer may be very large, return it **modulo** `109 + 7`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** binary = "001 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "0 ", "0 ", "1 "\].
The unique good subsequences are "0 " and "1 ".
**Example 2:**
**Input:** binary = "11 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "1 ", "1 ", "11 "\].
The unique good subsequences are "1 " and "11 ".
**Example 3:**
**Input:** binary = "101 "
**Output:** 5
**Explanation:** The good subsequences of binary are \[ "1 ", "0 ", "1 ", "10 ", "11 ", "101 "\].
The unique good subsequences are "0 ", "1 ", "10 ", "11 ", and "101 ".
**Constraints:**
* `1 <= binary.length <= 105`
* `binary` consists of only `'0'`s and `'1'`s. | Try using a set to find out the number of distinct characters in a substring. |
Python, runtime O(n), memory O(1) | number-of-unique-good-subsequences | 0 | 1 | Got idea here: https://leetcode.com/problems/number-of-unique-good-subsequences/solutions/1431802/c-clean-dp-solution-with-explanation-time-o-n-space-o-1/\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n end0 = end1 = hasZero = 0\n mod = 10**9+7\n for e in binary:\n if e == \'0\':\n hasZero = 1\n end0 = end0 + end1\n else:\n end1 = end0 + end1 + 1\n return (hasZero + end0 + end1)%mod\n``` | 0 | You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`).
Find the number of **unique good subsequences** of `binary`.
* For example, if `binary = "001 "`, then all the **good** subsequences are `[ "0 ", "0 ", "1 "]`, so the **unique** good subsequences are `"0 "` and `"1 "`. Note that subsequences `"00 "`, `"01 "`, and `"001 "` are not good because they have leading zeros.
Return _the number of **unique good subsequences** of_ `binary`. Since the answer may be very large, return it **modulo** `109 + 7`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** binary = "001 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "0 ", "0 ", "1 "\].
The unique good subsequences are "0 " and "1 ".
**Example 2:**
**Input:** binary = "11 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "1 ", "1 ", "11 "\].
The unique good subsequences are "1 " and "11 ".
**Example 3:**
**Input:** binary = "101 "
**Output:** 5
**Explanation:** The good subsequences of binary are \[ "1 ", "0 ", "1 ", "10 ", "11 ", "101 "\].
The unique good subsequences are "0 ", "1 ", "10 ", "11 ", and "101 ".
**Constraints:**
* `1 <= binary.length <= 105`
* `binary` consists of only `'0'`s and `'1'`s. | Try using a set to find out the number of distinct characters in a substring. |
The Easier Way | DP O(n) | Backward Iteration | number-of-unique-good-subsequences | 0 | 1 | # Intuition\nSuppose ```dp[i][bit]``` shows number of subsequences with all of it\'s bit indices greater or equal to ```i``` and starts with bit ```bit```(0, 1). So, the recursive relation would be:\n```dp[i][bit] = dp[i + 1][0] + dp[i + 1][1] + 1```(+1 for single 1 or single zero). Therefore the optimized space solution would be like below:\n# Code\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n dp = [0, 0]\n mod = int(1e9 + 7)\n for bit in [int(b) for b in binary][::-1]:\n dp[bit] = (1 + sum(dp)) % mod\n return (dp[1] + int(\'0\' in binary)) % mod\n\n``` | 0 | You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`).
Find the number of **unique good subsequences** of `binary`.
* For example, if `binary = "001 "`, then all the **good** subsequences are `[ "0 ", "0 ", "1 "]`, so the **unique** good subsequences are `"0 "` and `"1 "`. Note that subsequences `"00 "`, `"01 "`, and `"001 "` are not good because they have leading zeros.
Return _the number of **unique good subsequences** of_ `binary`. Since the answer may be very large, return it **modulo** `109 + 7`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** binary = "001 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "0 ", "0 ", "1 "\].
The unique good subsequences are "0 " and "1 ".
**Example 2:**
**Input:** binary = "11 "
**Output:** 2
**Explanation:** The good subsequences of binary are \[ "1 ", "1 ", "11 "\].
The unique good subsequences are "1 " and "11 ".
**Example 3:**
**Input:** binary = "101 "
**Output:** 5
**Explanation:** The good subsequences of binary are \[ "1 ", "0 ", "1 ", "10 ", "11 ", "101 "\].
The unique good subsequences are "0 ", "1 ", "10 ", "11 ", and "101 ".
**Constraints:**
* `1 <= binary.length <= 105`
* `binary` consists of only `'0'`s and `'1'`s. | Try using a set to find out the number of distinct characters in a substring. |
O(n log n) using divide and conquer | find-the-middle-index-in-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo we notice that for index `i` and index `i + 1`, most of the sum on the left and right side are shared. In particular, the left side of index `i` is `sum(nums[0..i-1])` and the left side of `i + 1` is `sum(nums[0..i-1]) + nums[i]`, so they both share `sum(nums[0..i-1]`. This is similar for the right side.\n\nSo we can split the problem in half, calculate the sum of the left half and calculate the sum of the right half and keep that in a cumulative sum so we don\'t have to repeat work.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst find the sum of the left and right half of some subsection of the array (originally the entire array). Then find the middle index of the left half of the array recursively, but make sure to add on the sum of the right half you have calculated so far. Similar for the left side.\n\n# Complexity\n- Time complexity: $O(n \\log n)$\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $O(n)$ (proof as an exercise to the reader)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n def dnc(l, r, lo, hi):\n if l == r - 1:\n return l if lo == hi else -1\n \n mid = (l + r) // 2\n right = sum(nums[mid:r])\n left = sum(nums[l:mid])\n\n left_ind = dnc(l, mid, lo, hi + right)\n return left_ind if left_ind != -1 else dnc(mid, r, lo + left, hi)\n return dnc(0, len(nums), 0, 0)\n``` | 7 | Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).
A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.
If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.
Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.
**Example 1:**
**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
**Example 2:**
**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
**Example 3:**
**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.
**Constraints:**
* `1 <= nums.length <= 100`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/) | null |
Python simple O(n) solution | find-the-middle-index-in-array | 0 | 1 | **Python :**\n\n```\ndef findMiddleIndex(self, nums: List[int]) -> int: \n\tleftSum = 0\n\trightSum = sum(nums)\n\n\tfor i in range(len(nums)):\n\t\tif leftSum == rightSum - nums[i]:\n\t\t\treturn i\n\n\t\tleftSum += nums[i]\n\t\trightSum -= nums[i]\n\n\treturn -1\n```\n\n**Like it ? please upvote !** | 60 | Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).
A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.
If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.
Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.
**Example 1:**
**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
**Example 2:**
**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
**Example 3:**
**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.
**Constraints:**
* `1 <= nums.length <= 100`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/) | null |
Python | Easy Solution✅ | find-the-middle-index-in-array | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n left = 0\n right = sum(nums)\n for index, num in enumerate(nums):\n right -= num\n if left == right:\n return index\n left += num\n \n return -1\n``` | 4 | Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).
A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.
If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.
Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.
**Example 1:**
**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
**Example 2:**
**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
**Example 3:**
**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.
**Constraints:**
* `1 <= nums.length <= 100`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/) | null |
[python3] Simple and easy Beats 97% runtime | find-the-middle-index-in-array | 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 findMiddleIndex(self, nums: List[int]) -> int:\n for i in range(len(nums)):\n if sum(nums[:i])==sum(nums[i+1:]):\n return i\n return -1\n``` | 2 | Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).
A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.
If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.
Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.
**Example 1:**
**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
**Example 2:**
**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
**Example 3:**
**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.
**Constraints:**
* `1 <= nums.length <= 100`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/) | null |
[Python] - Commented Rolling Window | find-the-middle-index-in-array | 0 | 1 | The exercise could be solved with prefix sum, but also with a rolling window.\n\nWe can compute the whole sum in one pass. This is our initial sum to the right, our sum to the left is zero. Then for every index, we first subtract current index from right sum, compare the sums and after that add the index to the left sum. Like this we keep track of both sums using only two addition.\n\n```\nclass Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n \n # find the sum\n right_sum = sum(nums)\n left_sum = 0\n \n for idx in range(len(nums)):\n \n # subtract current num from right sum\n right_sum -= nums[idx]\n \n # compare the sums\n if right_sum == left_sum:\n return idx\n \n # add current value to left sum\n left_sum += nums[idx]\n return -1\n``` | 1 | Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones).
A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`.
If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`.
Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_.
**Example 1:**
**Input:** nums = \[2,3,-1,8,4\]
**Output:** 3
**Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
**Example 2:**
**Input:** nums = \[1,-1,4\]
**Output:** 2
**Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
**Example 3:**
**Input:** nums = \[2,5\]
**Output:** -1
**Explanation:** There is no valid middleIndex.
**Constraints:**
* `1 <= nums.length <= 100`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/) | null |
python3 solution using queue only,(bfs) used simple to implement with detailed solution | find-all-groups-of-farmland | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe can have dimensions stored in m,n of the land\nif we find an index storing 1 we will start with it by adding it to an array b which will store the topleft and bottomright indices\nwe have a queue with index `(i,j)` in it and we pop the first element check if it is 1 or not.`if not land[ni][nj]:continue` `this might seem unnecessary but without this an infinite loop will happen ,figure out how` then make it 0 to not visit it again the next time when main for loops comes to land within outer boundaries\n then we store the most recent popped nodes `(ni,nj)` into `li,lj` and we check if land extends to the left or bottom and according add it to queue \nwhen q is empty the values will be there in li,lj and these can be added to array b which will now contain all 4 indices appending to ans and returning does it\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**__________O(M*N)**\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**__________O(M*N)**\n\n# Code\n```\nclass Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n ans=[]\n m,n=len(land),len(land[0])\n for i in range(m):\n for j in range(n):\n if land[i][j]:\n b=[]\n b.append(i)\n b.append(j)\n q=[(i,j)]\n while q:\n ni,nj=q.pop(0)\n if not land[ni][nj]:continue\n land[ni][nj]=0\n li,lj=ni,nj\n if nj<n-1 and land[ni][nj+1]:q.append((ni,nj+1))\n if ni<m-1 and land[ni+1][nj]:q.append((ni+1,nj))\n b.append(ni)\n b.append(nj)\n ans.append(b)\n return ans\n``` | 1 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
[Python3] DFS (easy to understand) | find-all-groups-of-farmland | 0 | 1 | ### Idea\n- first we need to iterative through all the positions in the square from the left to the right, top to the bottom.\n- If the land[i][j] == 1, the current coordinate (i, j) will be the top left position and then we will dfs from that coordinate to find to bottom right coordinate.\n- The dfs function will stop if the value is not `1` and the current coordinate are not on the given board.\n- then it turns the current coordinate of the board into `1` to ensure that we visited it.\n- then it try to recursively search for the right and below square of this.\n- the bottom right coordinate will be the maximum value of column and row of alls the block that contains `1` we visited from `dfs`\n\n\n### Analysis\n- Time Complexity O(m X n + k) ~ O(n^2). Where m, n are size of the board, k is number of farm area (k <= m X n).\n- \n\n### Code\n\n```\ndef findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n group = []\n m, n = len(land), len(land[0])\n \n def dfs(row: int, col: int) -> (int, int):\n if row < 0 or row >= m or col < 0 or col >= n or land[row][col] == 0:\n return (0, 0)\n \n land[row][col] = 0\n \n h_r1, h_c1 = dfs(row + 1, col)\n h_r2, h_c2 = dfs(row, col + 1)\n \n h_r = max(h_r1, h_r2, row)\n h_c = max(h_c1, h_c2, col)\n \n return (h_r, h_c)\n \n for i in range(m):\n for j in range(n):\n if land[i][j] == 1:\n x, y = dfs(i, j)\n group.append([i, j, x, y])\n \n return group\n``` | 18 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
✅[Python] Simple and Clean, beats 99.09%✅ | find-all-groups-of-farmland | 0 | 1 | ### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking us to find groups of farmland in a binary matrix where each group is a rectangular area of farmland consisting entirely of 1\'s. Two farmland areas are not considered adjacent if they are not four-directionally adjacent. We can use a simple nested for loop to iterate over each cell of the matrix and find the top left and bottom right coordinates of each group of farmland.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an empty list `groups` to store the groups of farmland.\n1. Iterate over each cell of the matrix using two nested loops.\n1. Check if the current cell represents farmland (i.e., 1) and if it is not four-directionally adjacent to any other farmland in a different group.\n1. If it is not adjacent to any other group of farmland, it means we have found a new group. In this case, we can find the boundaries of the group by traversing right and down to find the bottom right coordinate (i.e., the last cell in the group) and then adding this group to the `groups` list.\n\n1. Return the `groups` list containing the coordinates of the top left and bottom right corners of each group of farmland.\n\n# Complexity\n- Time complexity: $O(m*n)$, where `m` and `n` are the dimensions of the matrix. We are iterating over each cell of the matrix once and performing constant time operations within the loop.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(k)$, where `k` is the number of groups of farmland in the matrix. We are storing the coordinates of the top left and bottom right corners of each group of farmland in the `groups` list, which has space complexity proportional to the number of groups.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n m, n = len(land), len(land[0])\n groups = []\n for i in range(m):\n for j in range(n):\n if land[i][j] == 1 and (i == 0 or land[i-1][j] == 0) and (j == 0 or land[i][j-1] == 0):\n # found a new group, find its boundaries\n r1, c1 = i, j\n r2, c2 = i, j\n while r2 < m-1 and land[r2+1][j] == 1:\n r2 += 1\n while c2 < n-1 and land[i][c2+1] == 1:\n c2 += 1\n groups.append([r1, c1, r2, c2])\n \n return groups\n\n``` | 2 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
python3 easy to understand | find-all-groups-of-farmland | 0 | 1 | ```\ndef findFarmland(self, grid):\n self.ans=[]\n row=len(grid)\n col=len(grid[0])\n \n def helper(i,j,grid):\n if i<0 or j<0 or j>=len(grid[0]) or i>=len(grid) or grid[i][j]==0:return (0,0)\n (nx,ny)=(i,j)\n grid[i][j]=0\n for x,y in [(1,0),(0,1)]:\n (nx,ny)=max((nx,ny),helper(i+x,j+y,grid))\n return (nx,ny)\n \n for i in range(row):\n for j in range(col):\n if grid[i][j]==1:\n (x,y)=helper(i,j,grid)\n self.ans.append([i,j,x,y])\n return self.ans | 13 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
Easy Python Solution : 🚀 | find-all-groups-of-farmland | 1 | 1 | > ### Wherever you find an island compare all the coordinates of the island and store the minimum and maximum in an array.\n# Java Code\n---\n```\nclass Solution:\n def DFS(self,grid,i,j,visited,arr):\n if i<0 or i>=len(grid) or j<0 or j>=len(grid[0]) or visited[i][j] == True or grid[i][j] != 1:\n return\n if i<arr[0] or j<arr[1]:\n arr[0] = i\n arr[1] = j\n if i>arr[2] or j>arr[3]:\n arr[2] = i\n arr[3] = j\n visited[i][j] = True\n self.DFS(grid,i-1,j,visited,arr)\n self.DFS(grid,i+1,j,visited,arr)\n self.DFS(grid,i,j-1,visited,arr)\n self.DFS(grid,i,j+1,visited,arr)\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n result = []\n visited = [[False for i in range(len(land[0]))] for j in range(len(land))]\n for i in range(len(land)):\n for j in range(len(land[0])):\n if land[i][j] == 1 and visited[i][j] == False:\n arr = [float(\'inf\'),float(\'inf\'),float(\'-inf\'),float(\'-inf\')]\n self.DFS(land,i,j,visited,arr)\n result.append(arr)\n return result\n \n```\n---\n#### *Please don\'t forget to upvote if you\'ve liked my solution.*\n--- | 3 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
[Python3] dfs | find-all-groups-of-farmland | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/471dd5133055b331710ed3828849586ce1796b1a) for solutions of biweekly 60.\n```\nclass Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n m, n = len(land), len(land[0])\n ans = []\n for i in range(m):\n for j in range(n): \n if land[i][j]: # found farmland\n mini, minj = i, j \n maxi, maxj = i, j \n stack = [(i, j)]\n land[i][j] = 0 # mark as visited \n while stack: \n i, j = stack.pop()\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and land[ii][jj]: \n stack.append((ii, jj))\n land[ii][jj] = 0 \n maxi = max(maxi, ii)\n maxj = max(maxj, jj)\n ans.append([mini, minj, maxi, maxj])\n return ans \n``` | 5 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
Python3 simple flood fill dfs | find-all-groups-of-farmland | 0 | 1 | Mark cells as 0 as we find them and return the maximum coords we see (these are our bottom right coords). There are more efficient approaches but this template can be applied to a wider variety of problems with little modification.\n\n```python\ndef findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n m,n = len(land), len(land[0])\n dirs = [[1,0],[0,1]]\n res = []\n \n def isInBounds(i,j):\n return 0 <= i < m and 0 <= j < n\n \n def isGroup(i,j):\n return land[i][j] == 1\n \n def isValid(i,j):\n return isInBounds(i,j) and isGroup(i,j)\n \n def getMaxBounds(i,j):\n return max([dfs(i+x,j+y) for x,y in dirs if isValid(i+x,j+y)], default=(i,j))\n \n def dfs(i,j):\n land[i][j] = 0\n return getMaxBounds(i,j)\n \n for i,j in product(range(m), range(n)):\n if isValid(i,j): \n res.append([i,j,*dfs(i,j)])\n \n return res\n``` | 1 | You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. No two groups are adjacent, meaning farmland in one group is **not** four-directionally adjacent to another farmland in a different group.
`land` can be represented by a coordinate system where the top left corner of `land` is `(0, 0)` and the bottom right corner of `land` is `(m-1, n-1)`. Find the coordinates of the top left and bottom right corner of each **group** of farmland. A **group** of farmland with a top left corner at `(r1, c1)` and a bottom right corner at `(r2, c2)` is represented by the 4-length array `[r1, c1, r2, c2].`
Return _a 2D array containing the 4-length arrays described above for each **group** of farmland in_ `land`_. If there are no groups of farmland, return an empty array. You may return the answer in **any order**_.
**Example 1:**
**Input:** land = \[\[1,0,0\],\[0,1,1\],\[0,1,1\]\]
**Output:** \[\[0,0,0,0\],\[1,1,2,2\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[0\]\[0\].
The second group has a top left corner at land\[1\]\[1\] and a bottom right corner at land\[2\]\[2\].
**Example 2:**
**Input:** land = \[\[1,1\],\[1,1\]\]
**Output:** \[\[0,0,1,1\]\]
**Explanation:**
The first group has a top left corner at land\[0\]\[0\] and a bottom right corner at land\[1\]\[1\].
**Example 3:**
**Input:** land = \[\[0\]\]
**Output:** \[\]
**Explanation:**
There are no groups of farmland.
**Constraints:**
* `m == land.length`
* `n == land[i].length`
* `1 <= m, n <= 300`
* `land` consists of only `0`'s and `1`'s.
* Groups of farmland are **rectangular** in shape. | The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order. |
[Python3] tree traversal | operations-on-tree | 0 | 1 | Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/471dd5133055b331710ed3828849586ce1796b1a) for solutions of biweekly 60.\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.parent = parent\n self.tree = [[] for _ in parent]\n for i, x in enumerate(parent): \n if x != -1: self.tree[x].append(i)\n self.locked = {}\n\n def lock(self, num: int, user: int) -> bool:\n if num in self.locked: return False \n self.locked[num] = user\n return True \n\n def unlock(self, num: int, user: int) -> bool:\n if self.locked.get(num) != user: return False \n self.locked.pop(num)\n return True \n\n def upgrade(self, num: int, user: int) -> bool:\n if num in self.locked: return False # check for unlocked\n \n node = num\n while node != -1: \n if node in self.locked: break # locked ancestor\n node = self.parent[node]\n else: \n stack = [num]\n descendant = []\n while stack: \n node = stack.pop()\n if node in self.locked: descendant.append(node)\n for child in self.tree[node]: stack.append(child)\n if descendant: \n self.locked[num] = user # lock given node \n for node in descendant: self.locked.pop(node) # unlock all descendants\n return True \n return False # locked ancestor \n``` | 15 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
Intuitive Python with Comments | operations-on-tree | 0 | 1 | \n```\nclass LockingTree:\n \n def __init__(self, parent: List[int]):\n self.locked = {}\n self.parent = parent\n # Store immediate children of every node so we can DFS\n self.children = defaultdict(list)\n for i in range(len(parent)):\n par = parent[i]\n self.children[par].append(i)\n\n def lock(self, num: int, user: int) -> bool:\n if num in self.locked:\n return False\n self.locked[num] = user\n return True\n\n def unlock(self, num: int, user: int) -> bool:\n if num in self.locked and self.locked[num] == user:\n del self.locked[num]\n return True\n return False\n \n def hasLockedAncestor(self, num):\n # Check for locked ancestor, repeatedly get parent\n while self.parent[num] != -1:\n num = self.parent[num]\n if num in self.locked:\n return True\n return False\n \n def getLockedDescendants(self, num):\n # DFS through children of num, if locked, add to result\n stack = [num]\n res = []\n while stack:\n cur = stack.pop()\n if cur in self.locked:\n res.append(cur)\n for child in self.children[cur]:\n stack.append(child)\n return res\n \n def upgrade(self, num: int, user: int) -> bool:\n # Follow criteria for upgrade in problem description\n if num in self.locked:\n return False\n if self.hasLockedAncestor(num):\n return False\n lockedDescendants = self.getLockedDescendants(num)\n if not lockedDescendants:\n return False\n for node in lockedDescendants:\n del self.locked[node]\n self.locked[num] = user\n return True\n``` | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
Python 3: using dictionary and queue | operations-on-tree | 0 | 1 | Lock, Unlock -- Time: O(1)\nUpgrade -- Worst case Time: O(n)\n\n# Code\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.parent = parent\n self.children = defaultdict(list)\n self.locked = {}\n for i, node in enumerate(parent):\n if i != -1:\n self.children[node].append(i)\n\n def lock(self, num: int, user: int) -> bool:\n if num in self.locked:\n return False\n self.locked[num] = user\n return True\n \n def unlock(self, num: int, user: int) -> bool:\n if self.locked.get(num) != user:\n return False\n self.locked.pop(num)\n return True\n \n def upgrade(self, num: int, user: int) -> bool:\n ## check if num or its ancestors are locked or not\n node = num\n while node != -1:\n if node in self.locked:\n return False\n node = self.parent[node]\n\n ## check descendants of num and unlock them if locked\n locked_count = 0\n queue = deque([num])\n while queue:\n node = queue.popleft()\n if node in self.locked:\n locked_count += 1\n self.locked.pop(node)\n queue.extend(self.children[node])\n ## if any descendants of num are found to be locked, only then lock the given num with given user\n if locked_count:\n self.locked[num] = user\n\n return locked_count > 0\n\n# Your LockingTree object will be instantiated and called as such:\n# obj = LockingTree(parent)\n# param_1 = obj.lock(num,user)\n# param_2 = obj.unlock(num,user)\n# param_3 = obj.upgrade(num,user)\n``` | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
BFS Solution | operations-on-tree | 0 | 1 | # Code\n```python []\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.tree = parent\n self.vis = [0] * len(parent)\n self.child = defaultdict(list)\n for Child, Parent in enumerate(parent):\n if Child > 0: self.child[Parent].append(Child)\n\n def lock(self, num: int, user: int) -> bool:\n if self.vis[num]: return False\n self.vis[num] = user\n return True\n\n def unlock(self, num: int, user: int) -> bool:\n if self.vis[num] != user: return False\n self.vis[num] = 0\n return True\n\n def upgrade(self, num: int, user: int) -> bool:\n # The node is unlocked.\n if self.vis[num]: return False\n # It does not have any locked ancestors.\n ancestor = self.tree[num]\n while ancestor != -1:\n if self.vis[ancestor]: return False\n ancestor = self.tree[ancestor]\n # It has at least one locked descendant.\n has_locked_descendant = False\n q = deque()\n q.append(num)\n while q: # BFS.\n for Child in self.child[q.popleft()]:\n if self.vis[Child]:\n has_locked_descendant = True\n self.vis[Child] = 0\n q.append(Child)\n if has_locked_descendant: self.vis[num] = user # Fulfilled the 3 conditions below.\n return has_locked_descendant\n```\n```C++ []\nclass LockingTree {\nprivate:\n vector<int> tree, vis;\n vector<vector<int>> child;\npublic:\n LockingTree(vector<int>& parent) {\n int n = parent.size();\n this->tree = parent;\n this->vis.resize(n, 0);\n this->child.resize(n, vector<int>());\n for (int node = 1; node < n; node++) {\n this->child[parent[node]].push_back(node);\n }\n }\n \n bool lock(int num, int user) {\n if (this->vis[num]) return false;\n return this->vis[num] = user;\n }\n \n bool unlock(int num, int user) {\n if (this->vis[num] != user) return false;\n this->vis[num] = 0;\n return true; \n }\n \n bool upgrade(int num, int user) {\n // The node is unlocked.\n if (this->vis[num]) return false;\n // It does not have any locked ancestors.\n int ancestor = this->tree[num];\n while (ancestor != -1) {\n if (this->vis[ancestor]) return false;\n ancestor = this->tree[ancestor];\n }\n // It has at least one locked descendant.\n bool has_locked_descendant = false;\n queue<int> q;\n q.push(num);\n while (!q.empty()) {\n int node = q.front(); q.pop();\n for (int Child : this->child[node]) {\n if (this->vis[Child]) has_locked_descendant = true;\n this->vis[Child] = 0;\n q.push(Child);\n }\n }\n if (has_locked_descendant) this->vis[num] = user;\n return has_locked_descendant;\n }\n};\n\n/**\n * Your LockingTree object will be instantiated and called as such:\n * LockingTree* obj = new LockingTree(parent);\n * bool param_1 = obj->lock(num,user);\n * bool param_2 = obj->unlock(num,user);\n * bool param_3 = obj->upgrade(num,user);\n */\n``` | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
O(n) time | O(n) space | solution explained | operations-on-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse hashmap because its access and search time is O(1).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**init()**\n- declare an instance variable to store the parent array\n- set locked = a hashmap to store the locked nodes\n - key = node, value = user\n - here we have used a hashmap with a default value of null for the key. This is to handle missing keys and avoid the check for keys i.e to check if a key exists\n- set child = a hashmap to store child nodes\nkey = node, value = list of child nodes\n- fill the child hashmap i.e traverse the parent list and map the parent value as the key (nodes) and its index as the child node \n\n**lock()**\n- if the node is already locked i.e the value in hashmap is not null, \n- else, lock the node by setting the value of the node to the user and return true\n\n**unlock()**\n- return false if the node (num) is not locked by the user\n- else, unlock the node by making its value null and return true\n\n**upgrade()**\n- if the node is not locked, its ancestor is also not locked and at least one child is locked\n - unlock the children\n - lock the node\n - return true because the upgrade operation is successful\n- else return false\n\nNote: We have defined separate internal functions to check for locked ancestors, and locked children and to unlock children. You can put the code directly here in this function\n\n**_is_locked_parent()**\n- find the parent of the node\n- loop to check all ancestors\n - if parent is locked\n return true\n - else update the parent\n- if the loop completes without returning true, there is no locked parent (ancestor) for this node, return false \n\n**_is_lock_child()**\n- do DFS to find the child nodes\n - create a stack and push the current node to the stack\n - loop until the stack is empty \n - pop stack to get a node\n - if the node is locked, return true\n - else add the child nodes of this node to the stack to check if they are locked or not\n - if the loop completes without returning true, no child node is locked, return false\n\n**_unlock_children()**\n- do DFS to find the child nodes\n - create a stack and push the current node to the stack\n - loop until the stack is empty \n - pop stack to get a node\n - if the node is locked, unlock it\n - add the child nodes of this node to the stack to unlock them\n\n\n# Complexity\n- Time complexity:\n - init() O(filling hashmap) \u2192 O(parent array) \u2192 O(n) \n - only once i.e during object creation\n - lock() O(1)\n - unlock() O(1)\n - upgrade() O(_is_locked_parent() + _is_locked_child() + _unlock_children()) \u2192 O(n + DFS + DFS) \u2192 O(n + n + n) \u2192 O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n - init() O(hashmap) \u2192 O(parent array) \u2192 O(n)\n - lock() O(1)\n - unlock() O(1)\n - upgrade() O(_is_locked_parent() + _is_locked_child() + _unlock_children()) \u2192 O(stack + stack) \u2192 O(h + h) \u2192 O(n + n) \u2192 O(n)\n - height (h) depends on the tree structure. Balanced tree height is logn and skewed tree height is n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.parent = parent\n self.locked = defaultdict(lambda: None)\n self.child = defaultdict(list)\n for i, v in enumerate(parent):\n self.child[v].append(i)\n \n def lock(self, num: int, user: int) -> bool:\n if self.locked[num]:\n return False\n self.locked[num] = user\n return True\n \n def unlock(self, num: int, user: int) -> bool:\n if self.locked[num] != user:\n return False\n self.locked[num] = None\n return True\n \n def upgrade(self, num: int, user: int) -> bool:\n if not self.locked[num] and not self._is_locked_parent(num) and self._is_locked_child(num):\n self._unlock_children(num)\n self.locked[num] = user\n return True\n return False\n \n def _is_locked_parent(self, num: int) -> bool:\n parent = self.parent[num]\n while parent != -1:\n if self.locked[parent]:\n return True\n parent = self.parent[parent]\n return False\n \n def _is_locked_child(self, num: int) -> bool:\n stack = [num]\n while stack:\n node = stack.pop()\n if self.locked[node]:\n return True\n stack.extend(self.child[node])\n return False\n\n def _unlock_children(self, num: int):\n stack = [num]\n while stack:\n node = stack.pop()\n if self.locked[node]:\n self.locked[node] = None\n stack.extend(self.child[node])\n \n\n\n# Your LockingTree object will be instantiated and called as such:\n# obj = LockingTree(parent)\n# param_1 = obj.lock(num,user)\n# param_2 = obj.unlock(num,user)\n# param_3 = obj.upgrade(num,user)\n``` | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
Beats 100% TC || Python code | operations-on-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass LockingTree:\n def __init__(self, parent: List[int]):\n self.tree=defaultdict(list)\n for i in range(1,len(parent)):\n self.tree[parent[i]].append(i) \n self.locks=[0]*len(parent)\n\n def dfs(i):\n for j in self.tree[i]:\n ances.append(i)\n dfs(j)\n ances.pop()\n self.ances[i]=ances.copy()\n self.ances=[0]*len(parent)\n ances=[]\n dfs(0)\n\n def bfs(i):\n child=[]\n for j in self.tree[i]:\n child.extend(bfs(j).copy())\n\n self.child[i]=child.copy()\n child.append(i)\n return child\n \n self.child=[0]*len(parent)\n bfs(0)\n \n \n\n\n \n def lock(self, num: int, user: int) -> bool:\n if self.locks[num]:return False\n self.locks[num]=user\n return True\n\n def unlock(self, num: int, user: int) -> bool:\n if self.locks[num]!=user:return False\n self.locks[num]=0\n return True\n \n \n def upgrade(self, num: int, user: int) -> bool:\n if self.locks[num]:return False\n for i in self.ances[num]:\n if self.locks[i]:return False\n got =False\n for j in self.child[num]:\n if self.locks[j]:\n got=True\n self.locks[j]=0\n if not got:return False\n self.locks[num]=user\n return True\n``` | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
Python solution, laid out clearly | operations-on-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.locked = {}\n self.parent = parent\n self.descendants = defaultdict(list)\n for i, v in enumerate(parent):\n self.descendants[v].append(i)\n \n\n def lock(self, num: int, user: int) -> bool:\n if num in self.locked:\n return False\n self.locked[num] = user\n return True \n \n\n def unlock(self, num: int, user: int) -> bool:\n if num in self.locked and self.locked[num] == user:\n del self.locked[num]\n return True\n return False \n \n\n def upgrade(self, num: int, user: int) -> bool:\n\n # if locked, return false\n if num in self.locked:\n return False\n\n # function to check at least one locked descendant\n def hasLockedChild(num):\n if num not in self.descendants:\n return False\n \n for child in self.descendants[num]:\n if child in self.locked:\n return True\n if hasLockedChild(child):\n return True\n\n return False \n\n # function to unlock all descendants\n def unlockDescendants(num):\n if num not in self.descendants:\n return\n\n for child in self.descendants[num]:\n if child in self.locked:\n del self.locked[child]\n unlockDescendants(child) \n\n # does it have locked ancestors\n def unlockedParents(num):\n unlocked = True\n curr = num\n while curr != -1:\n if self.parent[curr] in self.locked:\n unlocked = False\n curr = self.parent[curr]\n return unlocked \n\n \n\n # now can see if it meets the requirements\n if hasLockedChild(num) and unlockedParents(num):\n # lock for this user\n self.locked[num] = user\n\n # unlock all descendants\n unlockDescendants(num)\n\n return True\n else:\n return False \n\n\n\n\n \n\n\n# Your LockingTree object will be instantiated and called as such:\n# obj = LockingTree(parent)\n# param_1 = obj.lock(num,user)\n# param_2 = obj.unlock(num,user)\n# param_3 = obj.upgrade(num,user)\n``` | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
* **Lock:** **Locks** the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.
* **Unlock: Unlocks** the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.
* **Upgrade****: Locks** the given node for the given user and **unlocks** all of its descendants **regardless** of who locked it. You may only upgrade a node if **all** 3 conditions are true:
* The node is unlocked,
* It has at least one locked descendant (by **any** user), and
* It does not have any locked ancestors.
Implement the `LockingTree` class:
* `LockingTree(int[] parent)` initializes the data structure with the parent array.
* `lock(int num, int user)` returns `true` if it is possible for the user with id `user` to lock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **locked** by the user with id `user`.
* `unlock(int num, int user)` returns `true` if it is possible for the user with id `user` to unlock the node `num`, or `false` otherwise. If it is possible, the node `num` will become **unlocked**.
* `upgrade(int num, int user)` returns `true` if it is possible for the user with id `user` to upgrade the node `num`, or `false` otherwise. If it is possible, the node `num` will be **upgraded**.
**Example 1:**
**Input**
\[ "LockingTree ", "lock ", "unlock ", "unlock ", "lock ", "upgrade ", "lock "\]
\[\[\[-1, 0, 0, 1, 1, 2, 2\]\], \[2, 2\], \[2, 3\], \[2, 2\], \[4, 5\], \[0, 1\], \[0, 1\]\]
**Output**
\[null, true, false, true, true, true, false\]
**Explanation**
LockingTree lockingTree = new LockingTree(\[-1, 0, 0, 1, 1, 2, 2\]);
lockingTree.lock(2, 2); // return true because node 2 is unlocked.
// Node 2 will now be locked by user 2.
lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.
lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.
// Node 2 will now be unlocked.
lockingTree.lock(4, 5); // return true because node 4 is unlocked.
// Node 4 will now be locked by user 5.
lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).
// Node 0 will now be locked by user 1 and node 4 will now be unlocked.
lockingTree.lock(0, 1); // return false because node 0 is already locked.
**Constraints:**
* `n == parent.length`
* `2 <= n <= 2000`
* `0 <= parent[i] <= n - 1` for `i != 0`
* `parent[0] == -1`
* `0 <= num <= n - 1`
* `1 <= user <= 104`
* `parent` represents a valid tree.
* At most `2000` calls **in total** will be made to `lock`, `unlock`, and `upgrade`. | Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets? |
[Python 3] Short, Neat | the-number-of-good-subsets | 0 | 1 | # Complexity\n- Time complexity: $O(N + 2^{30}) \\ \\ \\Big( = O(N + 2^{max(N) - min(N)}) \\Big)$\n * $N$ \u2014 gather frequences\n * $2^{30}$ \u2014 calculate all valid combinations\n\n- Space complexity: $O(N)$\n\n# Code\n```\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n @cache\n def get_mask(x):\n mask = 0\n for i, k in enumerate([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]):\n if x % (k * k) == 0: return None\n if x % k == 0:\n mask |= (1 << i)\n return mask\n\n def valid_combinations(x, cur_mask, cur_combination):\n if x > 30:\n if len(cur_combination) > 0:\n yield cur_combination\n return\n yield from valid_combinations(x+1, cur_mask, cur_combination)\n x_mask = get_mask(x)\n if x_mask and cur_mask & x_mask == 0:\n cur_combination.append(x)\n yield from valid_combinations(x+1, cur_mask | x_mask, cur_combination)\n cur_combination.pop()\n\n ans = 0\n cnt = Counter(nums)\n for combination in valid_combinations(2, 0, []):\n possibilities = 1\n for x in combination:\n possibilities *= cnt[x]\n ans += possibilities\n ans %= MOD\n ans *= (2 ** cnt[1]) % MOD\n ans %= MOD\n return ans\n``` | 0 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
Python | easy Solution | Faster than 99% | Bitmask | | the-number-of-good-subsets | 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 numberOfGoodSubsets(self, nums: List[int]) -> int:\n arr = [2,3,5,7,11,13,17,19,23,29]\n def solve(num):\n curr = 0\n for idx,i in enumerate(arr):\n cnt = 0\n while num%i == 0:\n num = num//i\n cnt +=1\n if cnt > 1:\n return -1\n if cnt:\n curr = curr|(1<<idx)\n return curr if curr != 0 else -1\n go = lambda x,y:bin(x).count("1")+bin(y).count("1") == bin(x|y).count("1")\n freq = {}\n for i in nums:\n freq[i] = 1+freq.get(i,0)\n temp = [(solve(i),i) for i in range(2,31) if solve(i) != -1]\n h = defaultdict(list)\n ans = -1\n mod = 10**9 + 7\n def helper(i,curr, res):\n nonlocal ans\n if i == len(temp):\n goto = 1\n for j in res:\n goto *= freq.get(j,0)\n goto %= mod\n ans += goto\n ans %= mod\n return\n if go(curr, temp[i][0]):\n res.append(temp[i][1])\n helper(i+1, curr|temp[i][0], res)\n res.pop()\n helper(i+1, curr, res) \n helper(0,0,[])\n return (ans*(pow(2, freq.get(1, 0), mod)))%mod\n\n\n``` | 0 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
DFS with prime factors without bitmasking | the-number-of-good-subsets | 0 | 1 | # Intuition\nThis can be solved by checking the common prime factors of the number from 2 to 30 since the upper bound is given upto 30\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI started with approach like this\nfor num 2 to 30 and not including bad numbers\nI collect their prime factors \n```\n{2: {2}, 3:{3}, 5:{5}, 6:{2,3}}\n```\nI created a list like this which includes the child \n```\n{2: [3,5], 3:[5], 5:[]} ...\n```\nI created a count of elements\n```\n{2: 2, 3: 2, 5:1}\n\n```\nNow for each key starting from 2 to 31 \nwe will apply the following formula\nLet\'s say for 2 ->\n\nnumber of times 2 in the counter dictionary * (\nsum(check for child of 2 and count their counts like count(3) + count(5))\n+\n(check for child of 2 and check if their inside count are also there)\nin this when doing recursively we need to maintain the factors we have already encountered so that chain like this should not be counted\n2->5->29->30\n)\n\nNow we got the total sum excluding one\nNow multipy the result by (2^count(one)) since one can repeat itself \n\n# Code\n```\nfrom collections import Counter\n\nclass Solution:\n def count_dp(self, dp, m, root_primes, cnt_, root):\n tot_count = 0\n for i in dp[root]:\n if not m[i].intersection(root_primes):\n # print(dp)\n tot_count += (cnt_[i] * (sum(cnt_[j] for j in dp[i] if not root_primes.union(m[i]).intersection(m[j])) + self.count_dp(dp,m,root_primes.union(m[i]), cnt_, i))) % (10**9 + 7)\n return tot_count % (10**9 + 7)\n\n def count_primes(self, nums, primes, m):\n bad = {4,8,9,12,16,18,20,24,25,27,28}\n tot_count = 0\n cnt_ = Counter(nums)\n # ones = cnt_.pop(1, 0)\n for i in bad:\n cnt_.pop(i, None)\n dp = {}\n for i in range(2,31):\n if i in cnt_ and i not in bad :\n dp[i] = sorted([\n key for key in cnt_ if ((key not in (i,1)) and (key not in dp) and (key not in bad) and (not m[i].intersection(m[key])))\n ])\n # print(cnt_, dp)\n count = 0\n for i in range(2,31):\n if i in cnt_ and i not in bad :\n c = (cnt_[i] * (sum(cnt_[j] for j in dp[i]) + self.count_dp(dp, m, m[i], cnt_, i)) % (10**9 + 7))\n count += c\n # print(i, c, count)\n ones = cnt_.pop(1, 0)\n count += sum(cnt_.values())\n\n return (count * pow(2,ones,10**9 + 7)) % (10**9 + 7)\n\n\n \n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n primes = {2,3,5,7,11,13,17,19,23,29}\n m = {\n i: set(j for j in primes if i%j==0) for i in range(1, 31)\n }\n return self.count_primes(nums, primes, m)\n\n``` | 0 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
Python simple solution that beats 90% | the-number-of-good-subsets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom itertools import combinations\nfrom collections import Counter, defaultdict\nimport math\n\ndef dfs(frequencies, number, good_numbers, result):\n if number > 30:\n return\n frequency = frequencies[number]\n if frequency:\n for other_number in list(result.keys()):\n product = number * other_number\n if product in good_numbers:\n result[product] += result[other_number] * frequency\n dfs(frequencies, number + 1, good_numbers, result)\n\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n primes = set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]) # 10\n good_numbers = set() # 1024\n for i in range(1, len(primes) + 1):\n for combo in combinations(primes, i):\n good_numbers.add(math.prod(combo))\n frequencies = Counter(nums)\n good_subsets = Counter({1 : 1})\n dfs(frequencies, 2, good_numbers, good_subsets)\n special_case = 2 ** frequencies[1] # number of 1s if a special case\n del good_subsets[1]\n return sum(value * special_case for value in good_subsets.values()) % (10 ** 9 + 7) \n``` | 0 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
100% Speee | the-number-of-good-subsets | 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 numberOfGoodSubsets(self, nums: List[int]) -> int:\n d = Counter(nums)\n print(d)\n output = 0\n output += (d[2] + 1) * (d[3] + 1) * (d[5] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[6] * (d[5] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[10] * (d[3] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[14] * (d[3] + 1) * (d[5] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[15] * (d[2] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[21] * (d[2] + 1) * (d[5] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[22] * (d[3] + 1) * (d[5] + 1) * (d[7] + 1) * (d[13] + 1)\n output += d[26] * (d[3] + 1) * (d[5] + 1) * (d[7] + 1) * (d[11] + 1)\n output += d[30] * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[10] * d[21] * (d[11] + 1) * (d[13] + 1)\n output += d[14] * d[15] * (d[11] + 1) * (d[13] + 1)\n output += d[15] * d[22] * (d[7] + 1) * (d[13] + 1)\n output += d[15] * d[26] * (d[7] + 1) * (d[11] + 1)\n output += d[21] * d[22] * (d[5] + 1) * (d[13] + 1)\n output += d[21] * d[26] * (d[5] + 1) * (d[11] + 1)\n output *= (d[17] + 1) * (d[19] + 1) * (d[23] + 1) * (d[29] + 1)\n output -= 1\n output *= 2 ** (d[1]) % (10**9 + 7)\n return output % (10**9 + 7)\n``` | 0 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
Solution | the-number-of-good-subsets | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n long modulo = 1e9 + 7, result = 0;\n int primes[10] = {2,3,5,7,11,13,17,19,23,29};\n int nonprimes[8] = {6,10,14,15,21,22,26,30};\n int count[31];\n vector<int> bit_rep;\n long powerOfTwo(int x) {\n long result = 1;\n while(x--)result = (result * 2) % modulo;\n return result;\n }\n void dfs(int index, int cur_set_bits, long countSoFar,long debug){\n if(index == 8) {\n for(int prime : primes) {\n if((cur_set_bits & bit_rep[prime]) == 0) {\n countSoFar = (countSoFar * (1 + count[prime])) % modulo;\n }\n }\n result = (result + countSoFar) % modulo;\n return ;\n }\n dfs(index+1,cur_set_bits, countSoFar, debug);\n if((cur_set_bits & bit_rep[nonprimes[index]]) == 0 && count[nonprimes[index]]!=0) {\n countSoFar = (countSoFar * count[nonprimes[index]]) % modulo;\n dfs(index+1, cur_set_bits|bit_rep[nonprimes[index]], countSoFar, debug * nonprimes[index]);\n }\n }\n int numberOfGoodSubsets(vector<int>& nums) {\n bit_rep.clear(); bit_rep.resize(31, 0);\n for(int i : nums) count[i]++;\n for(int i : primes)bit_rep[i] = 1<<i;\n for(int i : nonprimes){\n for(int prime:primes)if(i % prime == 0)bit_rep[i] |= (1<<prime);\n }\n dfs(0,0,1,1);\n result = (result + modulo - 1) % modulo;\n result = (result * powerOfTwo(count[1])) % modulo;\n return result;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n d = Counter(nums)\n print(d)\n output = 0\n output += (d[2] + 1) * (d[3] + 1) * (d[5] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[6] * (d[5] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[10] * (d[3] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[14] * (d[3] + 1) * (d[5] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[15] * (d[2] + 1) * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[21] * (d[2] + 1) * (d[5] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[22] * (d[3] + 1) * (d[5] + 1) * (d[7] + 1) * (d[13] + 1)\n output += d[26] * (d[3] + 1) * (d[5] + 1) * (d[7] + 1) * (d[11] + 1)\n output += d[30] * (d[7] + 1) * (d[11] + 1) * (d[13] + 1)\n output += d[10] * d[21] * (d[11] + 1) * (d[13] + 1)\n output += d[14] * d[15] * (d[11] + 1) * (d[13] + 1)\n output += d[15] * d[22] * (d[7] + 1) * (d[13] + 1)\n output += d[15] * d[26] * (d[7] + 1) * (d[11] + 1)\n output += d[21] * d[22] * (d[5] + 1) * (d[13] + 1)\n output += d[21] * d[26] * (d[5] + 1) * (d[11] + 1)\n output *= (d[17] + 1) * (d[19] + 1) * (d[23] + 1) * (d[29] + 1)\n output -= 1\n output *= 2 ** (d[1]) % (10**9 + 7)\n return output % (10**9 + 7)\n```\n\n```Java []\npublic class Solution {\n private static final long MOD = (long) (1e9 + 7);\n\n private long add(long a, long b) {\n a += b;\n return a < MOD ? a : a - MOD;\n }\n\n private long mul(long a, long b) {\n a *= b;\n return a < MOD ? a : a % MOD;\n }\n\n private long pow(long a, long b) {\n long res = 1;\n while (b > 0) {\n if ((b & 1) == 1) {\n res = mul(res, a);\n }\n a = mul(a, a);\n b >>= 1;\n }\n return add(res, 0);\n }\n\n public int numberOfGoodSubsets(int[] nums) {\n int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};\n int[] mask = new int[31];\n int[] freq = new int[31];\n for (int x : nums) {\n freq[x]++;\n }\n for (int i = 1; i <= 30; i++) {\n for (int j = 0; j < primes.length; j++) {\n if (i % primes[j] == 0) {\n if ((i / primes[j]) % primes[j] == 0) {\n mask[i] = 0;\n break;\n }\n mask[i] |= (int) pow(2, j);\n }\n }\n }\n long[] dp = new long[1024];\n dp[0] = 1;\n for (int i = 1; i <= 30; i++) {\n if (mask[i] != 0) {\n for (int j = 0; j < 1024; j++) {\n if ((mask[i] & j) == 0 && dp[j] > 0) {\n dp[(mask[i] | j)] = add(dp[(mask[i] | j)], mul(dp[j], freq[i]));\n }\n }\n }\n }\n long ans = 0;\n for (int i = 1; i < 1024; i++) {\n ans = add(ans, dp[i]);\n }\n ans = mul(ans, pow(2, freq[1]));\n ans = add(ans, 0);\n return (int) ans;\n }\n}\n```\n | 0 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
[Python3] dp | the-number-of-good-subsets | 0 | 1 | \nPlease check out this [commit](https://github.com/gaosanyong/leetcode/commit/471dd5133055b331710ed3828849586ce1796b1a) for solutions of biweekly 60.\n```\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n freq = [0] * 31\n for x in nums: freq[x] += 1\n \n masks = [0] * 31\n for x in range(1, 31): \n if x == 1: masks[x] = 0b10\n else: \n bits = 0\n xx = x\n for k in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29): \n while xx % k == 0: \n if (bits >> k) & 1: break # repeated factors \n bits ^= 1 << k\n xx //= k\n else: continue \n break \n else: masks[x] = bits\n \n @cache\n def fn(x, m): \n """Return number of good subsets."""\n if x == 31: return int(m > 2)\n ans = fn(x+1, m)\n if freq[x] and masks[x]: \n if x == 1: ans *= 2**freq[x]\n elif not m & masks[x]: ans += freq[x] * fn(x+1, m | masks[x])\n return ans % 1_000_000_007\n \n return fn(1, 0)\n``` | 3 | You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers.
* For example, if `nums = [1, 2, 3, 4]`:
* `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively.
* `[1, 4]` and `[4]` are not **good** subsets with products `4 = 2*2` and `4 = 2*2` respectively.
Return _the number of different **good** subsets in_ `nums` _**modulo**_ `109 + 7`.
A **subset** of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 6
**Explanation:** The good subsets are:
- \[1,2\]: product is 2, which is the product of distinct prime 2.
- \[1,2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[1,3\]: product is 3, which is the product of distinct prime 3.
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[3\]: product is 3, which is the product of distinct prime 3.
**Example 2:**
**Input:** nums = \[4,2,3,15\]
**Output:** 5
**Explanation:** The good subsets are:
- \[2\]: product is 2, which is the product of distinct prime 2.
- \[2,3\]: product is 6, which is the product of distinct primes 2 and 3.
- \[2,15\]: product is 30, which is the product of distinct primes 2, 3, and 5.
- \[3\]: product is 3, which is the product of distinct prime 3.
- \[15\]: product is 15, which is the product of distinct primes 3 and 5.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 30` | Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n. |
One line solution with using itertools.combinations | count-special-quadruplets | 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 countQuadruplets(self, nums: List[int]) -> int:\n\n return sum(1 for a,b,c,d in itertools.combinations(nums, 4) if a+b+c == d)\n \n``` | 1 | You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class: | The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1 |
Heavy Brute Force---->Python | count-special-quadruplets | 0 | 1 | \n\n# 1. Brute Force\n```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n count=0\n for a in range(len(nums)):\n for b in range(a+1,len(nums)):\n for c in range(b+1,len(nums)):\n for d in range(c+1,len(nums)):\n if nums[a]+nums[b]+nums[c]==nums[d]:\n count+=1\n return count\n\n //please upvote me it would encourage me alot\n\n```\n# please upvote me it would encourage me alot\n | 4 | You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class: | The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1 |
✅ PYTHON || Simple 1-Liner 🔥 | count-special-quadruplets | 0 | 1 | # Code\n```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n return sum([1 for a, b, c, d in combinations(nums, 4) if a + b + c == d])\n``` | 2 | You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class: | The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1 |
Python, non-brute force. Time: O(N^2), Space: O(N^2) | count-special-quadruplets | 0 | 1 | ```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n idx = defaultdict(list)\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n idx[nums[j]-nums[i]].append(i)\n \n count = 0 \n for i in range(len(nums)-3):\n for j in range(i+1, len(nums)-2):\n count += sum(k > j for k in idx[nums[i]+nums[j]])\n \n return count\n``` | 7 | You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class: | The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1 |
Python Solution Using SortedList Explained | the-number-of-weak-characters-in-the-game | 0 | 1 | # Intuition\nBasically we want to check for two properties for all possible pairs. This leads to O(N^2) which wont work. The idea is to sort the properties as per their attacks. This way we can eliminate the need to atleast check one of the properties due to its increasing order. Now we want to order out their defence. \n\nFor `i\'th character with attack A and defence D`, we only check the `defence` of players with `attack <= A-1`. If we can maintain a sorted list of defence for players with `attack <= A-1`, then we can just binary search for D in that list, all characters behind the index found are weaker than `i\'th character`. \n\nIn JAVA there is [TreeSet](https://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html) for maintaining sorted order for arrays with logN time for basic operations like add, remove, contains. In Python there is nothing inbuilt for this, however [SortedContainers](https://grantjenks.com/docs/sortedcontainers/) are provided in Python\'s development environment by Leetcode for same functionality.\n\n# Approach\n1. Sort the properties of characters as per their attacks.\n2. Then we loop through n. Arr acts as a list of defence for characters with same attack. For eg: `[[2,2],[2,3],[2,8],[3,1],[3,4]]` we will have `[2,3,8]` in arr after first 3 iterations.\n3. If we are at the first index, or current attack equals previous attack, then append current defence to arr.\n4. If previous condition is not true then dump the defence in arr into sortedlist. \n***NOTE: This way we make sure that we dont compare defence of characters with same attack. We only want to compare defence of character with attack A to players with attack stricly lesser than A(not even equal to A)***. \n5. At any point sortedlist will contain defence of players with attack lesser than attack of current (`ith`) character.\n6. Check for weaker players for current character.\n7. `bisect_left` gives us the index (`idx`) in sortedlist where current defence might be placed. \n8. All players behind this index are weaker than current(`ith`) character. So we increase `ans` by `idx` and remove those weaker characters from the sortedlist. ***Removal is done to avoid counting the weaker players multiple times.***\n\n# Complexity\n- Time complexity: **O(N*logN)**, since we are doing atmost one addition and one removal of all N properties.\n- Space complexity: **O(N)**, since we only maintain a sortedlist and arr with atmost N elements.\n\n\n\n# Code\n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n properties.sort(key=lambda x: x[0]) # Step 1\n sl, ans, n, arr = SortedList(), 0, len(properties), []\n for i in range(n): # Step 2\n curr_att, curr_def = properties[i]\n if i == 0 or properties[i-1][0] == curr_att: # Step 3\n arr.append(curr_def)\n else: # Step 4\n for d in arr: \n sl.add(d)\n arr = [curr_def]\n idx = sl.bisect_left(curr_def) # Step 6 and 7\n ans += idx # Step 8\n if idx != 0:\n for _ in range(idx): sl.pop(0) # Step 8 removal part\n return ans\n\n``` | 1 | You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105` | Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick? |
Python - Sort | the-number-of-weak-characters-in-the-game | 0 | 1 | **Solution 1:**\n\n```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \n properties.sort(key=lambda x: (-x[0],x[1]))\n \n ans = 0\n curr_max = 0\n \n for _, d in properties:\n if d < curr_max:\n ans += 1\n else:\n curr_max = d\n return ans\n```\n\n**Soultion 2: Stack**\n```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \n properties.sort(key=lambda x: (x[0], -x[1]))\n \n stack = []\n ans = 0\n \n for a, d in properties:\n while stack and stack[-1] < d:\n stack.pop()\n ans += 1\n stack.append(d)\n return ans\n``` | 215 | You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105` | Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick? |
Python Easy Sorting Solution + Explanation + Runtime | the-number-of-weak-characters-in-the-game | 0 | 1 | # Explanation\n\nThis solution makes use of sorting the array with two keys. The first key, which takes priority, is the negative value of the `attack` of a given character. This causes the array to be sorted in descending value by attack. \n\nThe second key is used when the `attack` of two characters is equal (breaking ties), and it is the `defense` of a given character, which causes characters with the same `attack` to be sorted in ascending order of `defense`.\n\nIn code, this is done by assigning a tuple to the lambda:\n```python\nproperties.sort(key=lambda x: (-x[0], x[1]))\n```\n\nBecause we have sorted this array, we now have two constraints for every element we encounter as we loop through the array:\n1. Every element in the array *must have* an `attack` less than or equal to what we have already seen\n2. If the element has the same attack value as an element we have already encountered, the the defense *must be* greater than or equal to what we have already seen\n\nThis allows to arrive at the key insight in the solution to this question:\nIf the `defense` of character `i` is less than the maximum defense we have seen so far, then `i` is a weak character.\n\nThis is true because any character `k`, `k < i` has an `attack` greater than or equal to than `i`\'s `attack`. Therefore, if `i`\'s `defense` is less than the max `defense` seen so far, then `i` is a weak character. \n\nThe problem of characters potentially having the same `attack` is solved by sorting the characters with the same `attack` by `defense`.\n\n# Code\n```python\n\tdef numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n # sort properties in descending order of attack but ascending order of defense\n properties.sort(key=lambda x: (-x[0], x[1]))\n \n max_defense = 0\n weak_count = 0\n \n for _, defense in properties:\n # for any given element:\n # - every attack must be less than or equal to what we have already seen\n # - if the attack is the same, then the defense must be greater than what we have already seen for this attack value\n if defense < max_defense:\n weak_count += 1\n else:\n max_defense = defense\n \n return weak_count\n```\n# Runtime + Space Complexity\nThe time complexity is `O(n log n)` due to the sort and the single pass over the array.\nThe space complexity is `O(1)` becuase we are not using any additional data structures (other than the single variable to track the max defense)\n\n# Feedback\nFirst time posting a solution, please leave any comments if anything is not clear or incorrect, or if my solution helped you out :)\n\nHope this helps understand the problem! | 45 | You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105` | Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick? |
[Python3] Runtime: 1969 ms, faster than 99.62% | Memory: 65.7 MB, less than 98.32% | the-number-of-weak-characters-in-the-game | 0 | 1 | ```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n properties.sort(key=lambda x:(-x[0],x[1]))\n mxattack=properties[0][0]\n mxdefense=properties[0][1]\n count=0\n for i in range(1,len(properties)):\n if properties[i][0]<mxattack and properties[i][1]<mxdefense:\n count+=1\n else:\n mxattack=properties[i][0]\n mxdefense=properties[i][1]\n return count\n``` | 3 | You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game.
A character is said to be **weak** if any other character has **both** attack and defense levels **strictly greater** than this character's attack and defense levels. More formally, a character `i` is said to be **weak** if there exists another character `j` where `attackj > attacki` and `defensej > defensei`.
Return _the number of **weak** characters_.
**Example 1:**
**Input:** properties = \[\[5,5\],\[6,3\],\[3,6\]\]
**Output:** 0
**Explanation:** No character has strictly greater attack and defense than the other.
**Example 2:**
**Input:** properties = \[\[2,2\],\[3,3\]\]
**Output:** 1
**Explanation:** The first character is weak because the second character has a strictly greater attack and defense.
**Example 3:**
**Input:** properties = \[\[1,5\],\[10,4\],\[4,3\]\]
**Output:** 1
**Explanation:** The third character is weak because the second character has a strictly greater attack and defense.
**Constraints:**
* `2 <= properties.length <= 105`
* `properties[i].length == 2`
* `1 <= attacki, defensei <= 105` | Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick? |
✔ Python3 Solution | DP | first-day-where-you-have-been-in-all-the-rooms | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def firstDayBeenInAllRooms(self, A):\n n = len(A)\n mod = 10 ** 9 + 7\n dp = [0] * (n)\n for e, i in enumerate(A[:-1], 1):\n dp[e] = dp[e - 1] + 1\n dp[e] = (2 * dp[e] - dp[i]) % mod\n return dp[-1]\n``` | 1 | There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day.
Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `nextVisit` of length `n`:
* Assuming that on a day, you visit room `i`,
* if you have been in room `i` an **odd** number of times (**including** the current visit), on the **next** day you will visit a room with a **lower or equal room number** specified by `nextVisit[i]` where `0 <= nextVisit[i] <= i`;
* if you have been in room `i` an **even** number of times (**including** the current visit), on the **next** day you will visit room `(i + 1) mod n`.
Return _the label of the **first** day where you have been in **all** the rooms_. It can be shown that such a day exists. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nextVisit = \[0,0\]
**Output:** 2
**Explanation:**
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.
On the next day you will visit room nextVisit\[0\] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.
**Example 2:**
**Input:** nextVisit = \[0,0,2\]
**Output:** 6
**Explanation:**
Your room visiting order for each day is: \[0,0,1,0,0,1,2,...\].
Day 6 is the first day where you have been in all the rooms.
**Example 3:**
**Input:** nextVisit = \[0,1,2,0\]
**Output:** 6
**Explanation:**
Your room visiting order for each day is: \[0,0,1,1,2,2,3,...\].
Day 6 is the first day where you have been in all the rooms.
**Constraints:**
* `n == nextVisit.length`
* `2 <= n <= 105`
* `0 <= nextVisit[i] <= i` | Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even? |
Subsets and Splits