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
🔥🔥🔥🔥🔥Acc. 100% | js | ts | java | c | C++ | C# | python | python3 | php | kotlin | 🔥🔥🔥🔥🔥
maximal-network-rank
1
1
---\n![header_.png](https://assets.leetcode.com/users/images/ab4510d5-90e7-4616-b1e1-aac91ec90eea_1692159981.2067795.png)\n\n---\n```Python3 []\nfrom collections import defaultdict\nfrom typing import List\n\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n # Create a dictionary to store the count of roads for each city\n road_count = defaultdict(int)\n \n # Create a set to store pairs of connected cities\n connected_cities = set()\n \n # Iterate through the roads and update the road count for each city\n for road in roads:\n road_count[road[0]] += 1\n road_count[road[1]] += 1\n connected_cities.add(tuple(road))\n \n maximal_rank = 0\n \n # Calculate the maximal network rank\n for i in range(n):\n for j in range(i + 1, n):\n rank = road_count[i] + road_count[j]\n # If there is a road between cities i and j, subtract 1 from the rank\n if (i, j) in connected_cities or (j, i) in connected_cities:\n rank -= 1\n maximal_rank = max(maximal_rank, rank)\n \n return maximal_rank\n```\n```python []\nclass Solution(object):\n def maximalNetworkRank(self, n, roads):\n # Create an adjacency matrix to represent connections between cities\n adjacency_matrix = [[0] * n for _ in range(n)]\n for road in roads:\n city1, city2 = road\n adjacency_matrix[city1][city2] = 1\n adjacency_matrix[city2][city1] = 1\n \n max_rank = 0\n \n # Iterate through all pairs of cities\n for city1 in range(n):\n for city2 in range(city1 + 1, n):\n # Calculate network rank for the current pair of cities\n rank = sum(adjacency_matrix[city1]) + sum(adjacency_matrix[city2])\n if adjacency_matrix[city1][city2] == 1:\n rank -= 1 # Deduct one count for the common road\n max_rank = max(max_rank, rank)\n \n return max_rank\n```\n```Javascript []\nvar maximalNetworkRank = function(n, roads) {\n // Create an adjacency list to represent city connections\n const graph = new Array(n).fill(0).map(() => []);\n for (const [a, b] of roads) {\n graph[a].push(b);\n graph[b].push(a);\n }\n \n let maxNetworkRank = 0;\n \n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n // Calculate the network rank for the pair (i, j)\n const networkRank = graph[i].length + graph[j].length;\n if (graph[i].includes(j) || graph[j].includes(i)) {\n // If there is a direct road between the cities, subtract 1\n maxNetworkRank = Math.max(maxNetworkRank, networkRank - 1);\n } else {\n maxNetworkRank = Math.max(maxNetworkRank, networkRank);\n }\n }\n }\n \n return maxNetworkRank;\n};\n```\n```Typrscript []\nfunction maximalNetworkRank(n, roads) {\n // Create adjacency matrix\n const adj = Array.from({ length: n }, () => Array(n).fill(0));\n \n // Fill in the adjacency matrix\n for (const [a, b] of roads) {\n adj[a][b] = 1;\n adj[b][a] = 1;\n }\n \n let maxRank = 0;\n \n // Iterate through all pairs of cities\n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n const rank = countDegree(adj, i) + countDegree(adj, j) - adj[i][j];\n maxRank = Math.max(maxRank, rank);\n }\n }\n \n return maxRank;\n}\n\n// Helper function to count the degree of a city\nfunction countDegree(adj, city) {\n return adj[city].reduce((acc, val) => acc + val, 0);\n}\n```\n```Java []\nclass Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n // Create an adjacency list to represent the graph\n List<Integer>[] graph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n graph[i] = new ArrayList<>();\n }\n \n // Populate the adjacency list based on the roads\n for (int[] road : roads) {\n int city1 = road[0];\n int city2 = road[1];\n graph[city1].add(city2);\n graph[city2].add(city1);\n }\n \n int maxRank = 0;\n \n // Iterate through all pairs of cities\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int rank = graph[i].size() + graph[j].size();\n // If there is a road directly between the two cities, reduce the rank by 1\n if (graph[i].contains(j)) {\n rank--;\n }\n maxRank = Math.max(maxRank, rank);\n }\n }\n \n return maxRank;\n }\n}\n```\n```PHP []\nclass Solution {\n function maximalNetworkRank($n, $roads) {\n // Create a graph representation using an adjacency list\n $graph = array_fill(0, $n, []);\n foreach ($roads as $road) {\n $graph[$road[0]][] = $road[1];\n $graph[$road[1]][] = $road[0];\n }\n \n $maxRank = 0;\n // Iterate over all pairs of cities\n for ($i = 0; $i < $n; $i++) {\n for ($j = $i + 1; $j < $n; $j++) {\n // Calculate the network rank for this pair of cities\n $rank = count($graph[$i]) + count($graph[$j]);\n // If there is a direct road between these cities, subtract 1 from rank\n if (in_array($j, $graph[$i]) || in_array($i, $graph[$j])) {\n $rank--;\n }\n // Update the maximum network rank\n $maxRank = max($maxRank, $rank);\n }\n }\n \n return $maxRank;\n }\n}\n```\n```Kotlin []\nclass Solution {\n fun maximalNetworkRank(n: Int, roads: Array<IntArray>): Int {\n val adjMatrix = Array(n) { IntArray(n) }\n \n for (road in roads) {\n val a = road[0]\n val b = road[1]\n adjMatrix[a][b]++\n adjMatrix[b][a]++\n }\n \n var maxRank = 0\n \n for (i in 0 until n) {\n for (j in i + 1 until n) {\n val networkRank = adjMatrix[i].sum() + adjMatrix[j].sum() - adjMatrix[i][j]\n maxRank = maxOf(maxRank, networkRank)\n }\n }\n \n return maxRank\n }\n}\n```\n```C []\nint maximalNetworkRank(int n, int** roads, int roadsSize, int* roadsColSize) {\n int adjacencyMatrix[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n adjacencyMatrix[i][j] = 0;\n }\n }\n \n for (int i = 0; i < roadsSize; i++) {\n int city1 = roads[i][0];\n int city2 = roads[i][1];\n adjacencyMatrix[city1][city2] = 1;\n adjacencyMatrix[city2][city1] = 1;\n }\n \n int maxNetworkRank = 0;\n \n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int networkRank = 0;\n \n for (int k = 0; k < n; k++) {\n if (k != i && k != j) {\n networkRank += adjacencyMatrix[i][k] + adjacencyMatrix[j][k];\n }\n }\n \n // Consider the case when the cities i and j are directly connected\n networkRank += adjacencyMatrix[i][j];\n \n maxNetworkRank = networkRank > maxNetworkRank ? networkRank : maxNetworkRank;\n }\n }\n \n return maxNetworkRank;\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maximalNetworkRank(int n, vector<vector<int>>& roads) {\n // Create an adjacency list to represent the graph\n vector<vector<int>> adjList(n);\n for (const auto& road : roads) {\n adjList[road[0]].push_back(road[1]);\n adjList[road[1]].push_back(road[0]);\n }\n \n int maximalRank = 0;\n \n // Iterate through all pairs of cities\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n int rank = adjList[i].size() + adjList[j].size();\n \n // If there is a road directly connecting these two cities, reduce rank\n for (int neighbor : adjList[i]) {\n if (neighbor == j) {\n rank--;\n break;\n }\n }\n \n maximalRank = max(maximalRank, rank);\n }\n }\n \n return maximalRank;\n }\n};\n```\n```C# []\npublic class Solution {\n public int MaximalNetworkRank(int n, int[][] roads) {\n // Create and initialize the adjacency matrix\n int[][] adjacencyMatrix = new int[n][];\n for (int i = 0; i < n; i++) {\n adjacencyMatrix[i] = new int[n];\n }\n \n // Populate the adjacency matrix based on the roads\n foreach (var road in roads) {\n int city1 = road[0];\n int city2 = road[1];\n adjacencyMatrix[city1][city2]++;\n adjacencyMatrix[city2][city1]++;\n }\n \n int maxNetworkRank = 0;\n \n // Calculate and update the maximum network rank\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int networkRank = SumRow(adjacencyMatrix, i) + SumRow(adjacencyMatrix, j) - adjacencyMatrix[i][j];\n maxNetworkRank = Math.Max(maxNetworkRank, networkRank);\n }\n }\n \n return maxNetworkRank;\n }\n \n // Helper method to calculate the sum of a row in the adjacency matrix\n private int SumRow(int[][] matrix, int row) {\n int sum = 0;\n for (int col = 0; col < matrix.Length; col++) {\n sum += matrix[row][col];\n }\n return sum;\n }\n}\n```\n\n---\n![download.jpg](https://assets.leetcode.com/users/images/5196fec2-1dd4-4b82-9700-36c5a0e72623_1692159956.9446952.jpeg)\n\n---
1
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**. The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities. Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_. **Example 1:** **Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 4 **Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. **Example 2:** **Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\] **Output:** 5 **Explanation:** There are 5 roads that are connected to cities 1 or 2. **Example 3:** **Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\] **Output:** 5 **Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. **Constraints:** * `2 <= n <= 100` * `0 <= roads.length <= n * (n - 1) / 2` * `roads[i].length == 2` * `0 <= ai, bi <= n-1` * `ai != bi` * Each pair of cities has **at most one** road connecting them.
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
🔥🔥🔥🔥🔥Acc. 100% | js | ts | java | c | C++ | C# | python | python3 | php | kotlin | 🔥🔥🔥🔥🔥
maximal-network-rank
1
1
---\n![header_.png](https://assets.leetcode.com/users/images/ab4510d5-90e7-4616-b1e1-aac91ec90eea_1692159981.2067795.png)\n\n---\n```Python3 []\nfrom collections import defaultdict\nfrom typing import List\n\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n # Create a dictionary to store the count of roads for each city\n road_count = defaultdict(int)\n \n # Create a set to store pairs of connected cities\n connected_cities = set()\n \n # Iterate through the roads and update the road count for each city\n for road in roads:\n road_count[road[0]] += 1\n road_count[road[1]] += 1\n connected_cities.add(tuple(road))\n \n maximal_rank = 0\n \n # Calculate the maximal network rank\n for i in range(n):\n for j in range(i + 1, n):\n rank = road_count[i] + road_count[j]\n # If there is a road between cities i and j, subtract 1 from the rank\n if (i, j) in connected_cities or (j, i) in connected_cities:\n rank -= 1\n maximal_rank = max(maximal_rank, rank)\n \n return maximal_rank\n```\n```python []\nclass Solution(object):\n def maximalNetworkRank(self, n, roads):\n # Create an adjacency matrix to represent connections between cities\n adjacency_matrix = [[0] * n for _ in range(n)]\n for road in roads:\n city1, city2 = road\n adjacency_matrix[city1][city2] = 1\n adjacency_matrix[city2][city1] = 1\n \n max_rank = 0\n \n # Iterate through all pairs of cities\n for city1 in range(n):\n for city2 in range(city1 + 1, n):\n # Calculate network rank for the current pair of cities\n rank = sum(adjacency_matrix[city1]) + sum(adjacency_matrix[city2])\n if adjacency_matrix[city1][city2] == 1:\n rank -= 1 # Deduct one count for the common road\n max_rank = max(max_rank, rank)\n \n return max_rank\n```\n```Javascript []\nvar maximalNetworkRank = function(n, roads) {\n // Create an adjacency list to represent city connections\n const graph = new Array(n).fill(0).map(() => []);\n for (const [a, b] of roads) {\n graph[a].push(b);\n graph[b].push(a);\n }\n \n let maxNetworkRank = 0;\n \n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n // Calculate the network rank for the pair (i, j)\n const networkRank = graph[i].length + graph[j].length;\n if (graph[i].includes(j) || graph[j].includes(i)) {\n // If there is a direct road between the cities, subtract 1\n maxNetworkRank = Math.max(maxNetworkRank, networkRank - 1);\n } else {\n maxNetworkRank = Math.max(maxNetworkRank, networkRank);\n }\n }\n }\n \n return maxNetworkRank;\n};\n```\n```Typrscript []\nfunction maximalNetworkRank(n, roads) {\n // Create adjacency matrix\n const adj = Array.from({ length: n }, () => Array(n).fill(0));\n \n // Fill in the adjacency matrix\n for (const [a, b] of roads) {\n adj[a][b] = 1;\n adj[b][a] = 1;\n }\n \n let maxRank = 0;\n \n // Iterate through all pairs of cities\n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n const rank = countDegree(adj, i) + countDegree(adj, j) - adj[i][j];\n maxRank = Math.max(maxRank, rank);\n }\n }\n \n return maxRank;\n}\n\n// Helper function to count the degree of a city\nfunction countDegree(adj, city) {\n return adj[city].reduce((acc, val) => acc + val, 0);\n}\n```\n```Java []\nclass Solution {\n public int maximalNetworkRank(int n, int[][] roads) {\n // Create an adjacency list to represent the graph\n List<Integer>[] graph = new ArrayList[n];\n for (int i = 0; i < n; i++) {\n graph[i] = new ArrayList<>();\n }\n \n // Populate the adjacency list based on the roads\n for (int[] road : roads) {\n int city1 = road[0];\n int city2 = road[1];\n graph[city1].add(city2);\n graph[city2].add(city1);\n }\n \n int maxRank = 0;\n \n // Iterate through all pairs of cities\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int rank = graph[i].size() + graph[j].size();\n // If there is a road directly between the two cities, reduce the rank by 1\n if (graph[i].contains(j)) {\n rank--;\n }\n maxRank = Math.max(maxRank, rank);\n }\n }\n \n return maxRank;\n }\n}\n```\n```PHP []\nclass Solution {\n function maximalNetworkRank($n, $roads) {\n // Create a graph representation using an adjacency list\n $graph = array_fill(0, $n, []);\n foreach ($roads as $road) {\n $graph[$road[0]][] = $road[1];\n $graph[$road[1]][] = $road[0];\n }\n \n $maxRank = 0;\n // Iterate over all pairs of cities\n for ($i = 0; $i < $n; $i++) {\n for ($j = $i + 1; $j < $n; $j++) {\n // Calculate the network rank for this pair of cities\n $rank = count($graph[$i]) + count($graph[$j]);\n // If there is a direct road between these cities, subtract 1 from rank\n if (in_array($j, $graph[$i]) || in_array($i, $graph[$j])) {\n $rank--;\n }\n // Update the maximum network rank\n $maxRank = max($maxRank, $rank);\n }\n }\n \n return $maxRank;\n }\n}\n```\n```Kotlin []\nclass Solution {\n fun maximalNetworkRank(n: Int, roads: Array<IntArray>): Int {\n val adjMatrix = Array(n) { IntArray(n) }\n \n for (road in roads) {\n val a = road[0]\n val b = road[1]\n adjMatrix[a][b]++\n adjMatrix[b][a]++\n }\n \n var maxRank = 0\n \n for (i in 0 until n) {\n for (j in i + 1 until n) {\n val networkRank = adjMatrix[i].sum() + adjMatrix[j].sum() - adjMatrix[i][j]\n maxRank = maxOf(maxRank, networkRank)\n }\n }\n \n return maxRank\n }\n}\n```\n```C []\nint maximalNetworkRank(int n, int** roads, int roadsSize, int* roadsColSize) {\n int adjacencyMatrix[n][n];\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n adjacencyMatrix[i][j] = 0;\n }\n }\n \n for (int i = 0; i < roadsSize; i++) {\n int city1 = roads[i][0];\n int city2 = roads[i][1];\n adjacencyMatrix[city1][city2] = 1;\n adjacencyMatrix[city2][city1] = 1;\n }\n \n int maxNetworkRank = 0;\n \n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int networkRank = 0;\n \n for (int k = 0; k < n; k++) {\n if (k != i && k != j) {\n networkRank += adjacencyMatrix[i][k] + adjacencyMatrix[j][k];\n }\n }\n \n // Consider the case when the cities i and j are directly connected\n networkRank += adjacencyMatrix[i][j];\n \n maxNetworkRank = networkRank > maxNetworkRank ? networkRank : maxNetworkRank;\n }\n }\n \n return maxNetworkRank;\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maximalNetworkRank(int n, vector<vector<int>>& roads) {\n // Create an adjacency list to represent the graph\n vector<vector<int>> adjList(n);\n for (const auto& road : roads) {\n adjList[road[0]].push_back(road[1]);\n adjList[road[1]].push_back(road[0]);\n }\n \n int maximalRank = 0;\n \n // Iterate through all pairs of cities\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n int rank = adjList[i].size() + adjList[j].size();\n \n // If there is a road directly connecting these two cities, reduce rank\n for (int neighbor : adjList[i]) {\n if (neighbor == j) {\n rank--;\n break;\n }\n }\n \n maximalRank = max(maximalRank, rank);\n }\n }\n \n return maximalRank;\n }\n};\n```\n```C# []\npublic class Solution {\n public int MaximalNetworkRank(int n, int[][] roads) {\n // Create and initialize the adjacency matrix\n int[][] adjacencyMatrix = new int[n][];\n for (int i = 0; i < n; i++) {\n adjacencyMatrix[i] = new int[n];\n }\n \n // Populate the adjacency matrix based on the roads\n foreach (var road in roads) {\n int city1 = road[0];\n int city2 = road[1];\n adjacencyMatrix[city1][city2]++;\n adjacencyMatrix[city2][city1]++;\n }\n \n int maxNetworkRank = 0;\n \n // Calculate and update the maximum network rank\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n int networkRank = SumRow(adjacencyMatrix, i) + SumRow(adjacencyMatrix, j) - adjacencyMatrix[i][j];\n maxNetworkRank = Math.Max(maxNetworkRank, networkRank);\n }\n }\n \n return maxNetworkRank;\n }\n \n // Helper method to calculate the sum of a row in the adjacency matrix\n private int SumRow(int[][] matrix, int row) {\n int sum = 0;\n for (int col = 0; col < matrix.Length; col++) {\n sum += matrix[row][col];\n }\n return sum;\n }\n}\n```\n\n---\n![download.jpg](https://assets.leetcode.com/users/images/5196fec2-1dd4-4b82-9700-36c5a0e72623_1692159956.9446952.jpeg)\n\n---
1
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all the coordinates of `matrix`. **Example 1:** **Input:** matrix = \[\[5,2\],\[1,6\]\], k = 1 **Output:** 7 **Explanation:** The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. **Example 2:** **Input:** matrix = \[\[5,2\],\[1,6\]\], k = 2 **Output:** 5 **Explanation:** The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. **Example 3:** **Input:** matrix = \[\[5,2\],\[1,6\]\], k = 3 **Output:** 4 **Explanation:** The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `0 <= matrix[i][j] <= 106` * `1 <= k <= m * n`
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
Python maintainable with O(n) time/space complexity
split-two-strings-to-make-palindrome
0
1
# Intuition\n\nBounds:\n- we don\'t need to return the idx or the palindrome, just bool\n- we can split before and after a/b, but not by more than 1 idx. That\'s not a concern because a.length == b.length\n- input a/b length can be = 10^5, so likely need O(n) time complexity or better\n\nCritical hints/properties (potentially):\n- palindrome is a a word reflected about the center\n- if either palindrome, true\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nSince we\'re only looking at suffix and prefix (can\'t omit characters), can we use a 2-ptr method? the combinations we have to evaluate are:\n\n1. a prefix + b suffix\n2. b prefix + a suffix\n3. a entire (sort of an edge case of 1 where len(b suffix) == 0)\n4. b entire (sort of an edge case of 2 where len(a prefix) == 0)\n\nAlso t\'s an or condition, we don\'t care about the leftover combination\n\nThis seems feasible; we just need to run 2 pointer on 2 combinations. That said, it\'s not an easy 2-ptr as the meeting idx won\'t always be the center.\nWhat\'s the meeting idx? maybe when we encounter an inequality, we let either pointer continue until we have the length if it then becomes a palinxdrome, then we have a true. This checks out.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) as all the operations in makes_palindrome have O(n) time complexity (is_palindrome, prefix + suffix), and none of them multiply\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) as we have to make prefix combinations in memory\n\n# Code\n```\nclass Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n def is_palindrome(s: str) -> bool:\n return s == s[::-1]\n \n def makes_palindrome(prefix: str, suffix: str) -> bool:\n """Determine if prefix or suffix\n # when do we know if we used the full length? len(prefix[:l] + suffix[r:]) == len(res)\n # an l==0 means we did not include prefix. an r == len(suffix) - 1 means we did not include suffix.\n """\n l, r = 0, len(suffix) - 1\n # keep going until inequality or intersection\n # r >= l intersection: we want l and r to be at first idx of inequality for next steps\n while r >= l and prefix[l] == suffix[r]:\n l += 1\n r -= 1\n # try proceed suffix until length and return true if palindrome\n if is_palindrome(prefix[:l] + suffix[l:]):\n return True\n # try proceed prefix until length and return true if palindrome\n if is_palindrome(prefix[:r+1] + suffix[r+1:]):\n return True\n return False\n\n return makes_palindrome(a,b) or makes_palindrome(b,a)\n```
0
You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bsuffix` or `bprefix + asuffix` forms a palindrome. When you split a string `s` into `sprefix` and `ssuffix`, either `ssuffix` or `sprefix` is allowed to be empty. For example, if `s = "abc "`, then `" " + "abc "`, `"a " + "bc "`, `"ab " + "c "` , and `"abc " + " "` are valid splits. Return `true` _if it is possible to form_ _a palindrome string, otherwise return_ `false`. **Notice** that `x + y` denotes the concatenation of strings `x` and `y`. **Example 1:** **Input:** a = "x ", b = "y " **Output:** true **Explaination:** If either a or b are palindromes the answer is true since you can split in the following way: aprefix = " ", asuffix = "x " bprefix = " ", bsuffix = "y " Then, aprefix + bsuffix = " " + "y " = "y ", which is a palindrome. **Example 2:** **Input:** a = "xbdef ", b = "xecab " **Output:** false **Example 3:** **Input:** a = "ulacfd ", b = "jizalu " **Output:** true **Explaination:** Split them at index 3: aprefix = "ula ", asuffix = "cfd " bprefix = "jiz ", bsuffix = "alu " Then, aprefix + bsuffix = "ula " + "alu " = "ulaalu ", which is a palindrome. **Constraints:** * `1 <= a.length, b.length <= 105` * `a.length == b.length` * `a` and `b` consist of lowercase English letters
The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array.
Python maintainable with O(n) time/space complexity
split-two-strings-to-make-palindrome
0
1
# Intuition\n\nBounds:\n- we don\'t need to return the idx or the palindrome, just bool\n- we can split before and after a/b, but not by more than 1 idx. That\'s not a concern because a.length == b.length\n- input a/b length can be = 10^5, so likely need O(n) time complexity or better\n\nCritical hints/properties (potentially):\n- palindrome is a a word reflected about the center\n- if either palindrome, true\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nSince we\'re only looking at suffix and prefix (can\'t omit characters), can we use a 2-ptr method? the combinations we have to evaluate are:\n\n1. a prefix + b suffix\n2. b prefix + a suffix\n3. a entire (sort of an edge case of 1 where len(b suffix) == 0)\n4. b entire (sort of an edge case of 2 where len(a prefix) == 0)\n\nAlso t\'s an or condition, we don\'t care about the leftover combination\n\nThis seems feasible; we just need to run 2 pointer on 2 combinations. That said, it\'s not an easy 2-ptr as the meeting idx won\'t always be the center.\nWhat\'s the meeting idx? maybe when we encounter an inequality, we let either pointer continue until we have the length if it then becomes a palinxdrome, then we have a true. This checks out.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n) as all the operations in makes_palindrome have O(n) time complexity (is_palindrome, prefix + suffix), and none of them multiply\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) as we have to make prefix combinations in memory\n\n# Code\n```\nclass Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n def is_palindrome(s: str) -> bool:\n return s == s[::-1]\n \n def makes_palindrome(prefix: str, suffix: str) -> bool:\n """Determine if prefix or suffix\n # when do we know if we used the full length? len(prefix[:l] + suffix[r:]) == len(res)\n # an l==0 means we did not include prefix. an r == len(suffix) - 1 means we did not include suffix.\n """\n l, r = 0, len(suffix) - 1\n # keep going until inequality or intersection\n # r >= l intersection: we want l and r to be at first idx of inequality for next steps\n while r >= l and prefix[l] == suffix[r]:\n l += 1\n r -= 1\n # try proceed suffix until length and return true if palindrome\n if is_palindrome(prefix[:l] + suffix[l:]):\n return True\n # try proceed prefix until length and return true if palindrome\n if is_palindrome(prefix[:r+1] + suffix[r+1:]):\n return True\n return False\n\n return makes_palindrome(a,b) or makes_palindrome(b,a)\n```
0
You have a cubic storeroom where the width, length, and height of the room are all equal to `n` units. You are asked to place `n` boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes: * You can place the boxes anywhere on the floor. * If box `x` is placed on top of the box `y`, then each side of the four vertical sides of the box `y` **must** either be adjacent to another box or to a wall. Given an integer `n`, return _the **minimum** possible number of boxes touching the floor._ **Example 1:** **Input:** n = 3 **Output:** 3 **Explanation:** The figure above is for the placement of the three boxes. These boxes are placed in the corner of the room, where the corner is on the left side. **Example 2:** **Input:** n = 4 **Output:** 3 **Explanation:** The figure above is for the placement of the four boxes. These boxes are placed in the corner of the room, where the corner is on the left side. **Example 3:** **Input:** n = 10 **Output:** 6 **Explanation:** The figure above is for the placement of the ten boxes. These boxes are placed in the corner of the room, where the corner is on the back side. **Constraints:** * `1 <= n <= 109`
Try finding the largest prefix form a that matches a suffix in b Try string matching
O(n^3) algorithm
count-subtrees-with-max-distance-between-cities
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA (sub)tree may have many diameters, but there is exactly one or two centers. To simplfying the implementation, we divide into two cases: diameter is even or odd. For the case of even diameter, we count the subtrees by enumerating each vertex as the center. For the case of odd diameter, we enumerate each edge as the center. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each node $v$ as the center, we root the tree at $v$ and do a DFS. When visiting a vertex $u$, we recursively compute the number of subtrees rooted at $u$ and with depth $i$, for each possible $i$.\nWhen combining the results from the children of $u$, a naive implementation takes $O(deg(u)\\times n^2)$ time. By using prefix sum, it can be reduced to $O(deg(u)\\times n)$ time. Thus a DFS takes $O(n^2)$ since the total degree of a tree is $O(n)$.\nAt root $v$, we combine the results from its children. Since we care about only even diameter and centered at $v$, two branches of same depth $i$ form a subtree of diamter $2i$. When combining the branches one by one, we need to count the way that a current subtree is merged with a small incoming subtree which does not change its diameter.\nThe case of odd diameter is similar and simpler since there are only two branches for each center edge.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n^3)$ since each center vertex takes $O(n^2)$.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nLinear.\n\n# Code\n```\nclass Solution:\n # odd/even diameter couned individually\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n adj = [[] for i in range(n)]\n for u,v in edges:\n adj[u-1].append(v-1)\n adj[v-1].append(u-1)\n def comb(p,q): # merge p and q, res[max(i,j)]+=p[i]*q[j]\n if len(q)<len(p): p,q = q,p\n res = [0]*len(q)\n res[0] = p[0]*q[0]\n for i in range(1,len(p)): p[i] += p[i-1]\n for i in range(1,len(q)): q[i] += q[i-1]\n for i in range(1,len(p)):\n res[i] = p[i]*q[i]-p[i-1]*q[i-1]\n for i in range(len(p),len(q)):\n res[i] = (q[i]-q[i-1])*p[-1]\n return res\n \n def dfs(r,p): # num of subtree rooted at r with given depth\n d = [1]\n for v in adj[r]:\n if v==p: continue\n t = [1]+dfs(v,r)\n d = comb(t,d)\n return d\n #end dfs\n ans = [0]*n\n # odd diameter with (u,v) as center edge\n for u,v in edges:\n u -= 1; v-=1\n p = dfs(u,v)\n q = dfs(v,u)\n for i in range(min(len(p),len(q))):\n ans[i+i+1] += p[i]*q[i]\n #even diamter with v as center vertex\n for v in range(n): \n if len(adj[v])==1: continue \n tree = [1]+dfs(adj[v][0],v) #tree with depth\n curr = [0]*n\n for u in adj[v][1:]:\n q = [1]+dfs(u,v)\n # curr tree + new small\n j = 1; t = q[1]+1 # prefix sum of q\n for i in range(4,n,2):\n while j+1<min(i//2,len(q)):\n j += 1; t += q[j]\n curr[i] *= t\n # curr tree + same height\n for i in range(min(len(tree),len(q))):\n curr[i+i] += tree[i]*q[i]\n tree = comb(tree,q)\n for i in range(2,n,2):\n ans[i] += curr[i]\n #end\n return ans[1:]\n\n\n```\n
0
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. Return _an array of size_ `n-1` _where the_ `dth` _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. **Notice** that the **distance** between the two cities is the number of edges in the path between them. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,3\],\[2,4\]\] **Output:** \[3,4,0\] **Explanation:** The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. **Example 2:** **Input:** n = 2, edges = \[\[1,2\]\] **Output:** \[1\] **Example 3:** **Input:** n = 3, edges = \[\[1,2\],\[2,3\]\] **Output:** \[2,1\] **Constraints:** * `2 <= n <= 15` * `edges.length == n-1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * All pairs `(ui, vi)` are distinct.
Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.
O(n^3) algorithm
count-subtrees-with-max-distance-between-cities
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA (sub)tree may have many diameters, but there is exactly one or two centers. To simplfying the implementation, we divide into two cases: diameter is even or odd. For the case of even diameter, we count the subtrees by enumerating each vertex as the center. For the case of odd diameter, we enumerate each edge as the center. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each node $v$ as the center, we root the tree at $v$ and do a DFS. When visiting a vertex $u$, we recursively compute the number of subtrees rooted at $u$ and with depth $i$, for each possible $i$.\nWhen combining the results from the children of $u$, a naive implementation takes $O(deg(u)\\times n^2)$ time. By using prefix sum, it can be reduced to $O(deg(u)\\times n)$ time. Thus a DFS takes $O(n^2)$ since the total degree of a tree is $O(n)$.\nAt root $v$, we combine the results from its children. Since we care about only even diameter and centered at $v$, two branches of same depth $i$ form a subtree of diamter $2i$. When combining the branches one by one, we need to count the way that a current subtree is merged with a small incoming subtree which does not change its diameter.\nThe case of odd diameter is similar and simpler since there are only two branches for each center edge.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n^3)$ since each center vertex takes $O(n^2)$.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nLinear.\n\n# Code\n```\nclass Solution:\n # odd/even diameter couned individually\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n adj = [[] for i in range(n)]\n for u,v in edges:\n adj[u-1].append(v-1)\n adj[v-1].append(u-1)\n def comb(p,q): # merge p and q, res[max(i,j)]+=p[i]*q[j]\n if len(q)<len(p): p,q = q,p\n res = [0]*len(q)\n res[0] = p[0]*q[0]\n for i in range(1,len(p)): p[i] += p[i-1]\n for i in range(1,len(q)): q[i] += q[i-1]\n for i in range(1,len(p)):\n res[i] = p[i]*q[i]-p[i-1]*q[i-1]\n for i in range(len(p),len(q)):\n res[i] = (q[i]-q[i-1])*p[-1]\n return res\n \n def dfs(r,p): # num of subtree rooted at r with given depth\n d = [1]\n for v in adj[r]:\n if v==p: continue\n t = [1]+dfs(v,r)\n d = comb(t,d)\n return d\n #end dfs\n ans = [0]*n\n # odd diameter with (u,v) as center edge\n for u,v in edges:\n u -= 1; v-=1\n p = dfs(u,v)\n q = dfs(v,u)\n for i in range(min(len(p),len(q))):\n ans[i+i+1] += p[i]*q[i]\n #even diamter with v as center vertex\n for v in range(n): \n if len(adj[v])==1: continue \n tree = [1]+dfs(adj[v][0],v) #tree with depth\n curr = [0]*n\n for u in adj[v][1:]:\n q = [1]+dfs(u,v)\n # curr tree + new small\n j = 1; t = q[1]+1 # prefix sum of q\n for i in range(4,n,2):\n while j+1<min(i//2,len(q)):\n j += 1; t += q[j]\n curr[i] *= t\n # curr tree + same height\n for i in range(min(len(tree),len(q))):\n curr[i+i] += tree[i]*q[i]\n tree = comb(tree,q)\n for i in range(2,n,2):\n ans[i] += curr[i]\n #end\n return ans[1:]\n\n\n```\n
0
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Python (Simple BFS + DP + BitMasking)
count-subtrees-with-max-distance-between-cities
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 countSubgraphsForEachDiameter(self, n, edges):\n def bfs(src,cities):\n stack, visited, max_dist = [(src,0)], {src}, 0\n\n while stack:\n node, dist = stack.pop(0)\n max_dist = dist\n\n for neighbor in dict1[node]:\n if neighbor not in visited and neighbor in cities:\n visited.add(neighbor)\n stack.append((neighbor,dist+1))\n\n return max_dist, visited\n\n\n def max_distance_two_nodes(state):\n cities = set()\n\n for i in range(n):\n if (state>>i)&1 == 1:\n cities.add(i)\n\n result = 0\n\n for i in cities:\n max_dist, visited = bfs(i,cities)\n if len(visited) < len(cities): return 0\n result = max(result,max_dist)\n\n return result \n\n\n dict1 = defaultdict(list)\n\n for i,j in edges:\n dict1[i-1].append(j-1)\n dict1[j-1].append(i-1)\n\n ans = [0]*(n-1)\n\n for j in range(1,2**n):\n d = max_distance_two_nodes(j)\n if d > 0: ans[d-1] += 1 \n\n return ans\n\n \n\n\n\n\n\n \n\n \n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n```
0
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. Return _an array of size_ `n-1` _where the_ `dth` _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. **Notice** that the **distance** between the two cities is the number of edges in the path between them. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,3\],\[2,4\]\] **Output:** \[3,4,0\] **Explanation:** The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. **Example 2:** **Input:** n = 2, edges = \[\[1,2\]\] **Output:** \[1\] **Example 3:** **Input:** n = 3, edges = \[\[1,2\],\[2,3\]\] **Output:** \[2,1\] **Constraints:** * `2 <= n <= 15` * `edges.length == n-1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * All pairs `(ui, vi)` are distinct.
Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.
Python (Simple BFS + DP + BitMasking)
count-subtrees-with-max-distance-between-cities
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 countSubgraphsForEachDiameter(self, n, edges):\n def bfs(src,cities):\n stack, visited, max_dist = [(src,0)], {src}, 0\n\n while stack:\n node, dist = stack.pop(0)\n max_dist = dist\n\n for neighbor in dict1[node]:\n if neighbor not in visited and neighbor in cities:\n visited.add(neighbor)\n stack.append((neighbor,dist+1))\n\n return max_dist, visited\n\n\n def max_distance_two_nodes(state):\n cities = set()\n\n for i in range(n):\n if (state>>i)&1 == 1:\n cities.add(i)\n\n result = 0\n\n for i in cities:\n max_dist, visited = bfs(i,cities)\n if len(visited) < len(cities): return 0\n result = max(result,max_dist)\n\n return result \n\n\n dict1 = defaultdict(list)\n\n for i,j in edges:\n dict1[i-1].append(j-1)\n dict1[j-1].append(i-1)\n\n ans = [0]*(n-1)\n\n for j in range(1,2**n):\n d = max_distance_two_nodes(j)\n if d > 0: ans[d-1] += 1 \n\n return ans\n\n \n\n\n\n\n\n \n\n \n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n \n \n```
0
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Python3 easiest solution
count-subtrees-with-max-distance-between-cities
0
1
# Code\n```\nclass Solution(object):\n def countSubgraphsForEachDiameter(self, n, edges):\n def bfs(src, cities):\n visited = {src}\n q = deque([(src, 0)]) # Pair of (vertex, distance)\n farthestDist = 0 # Farthest distance from src to other nodes\n while len(q) > 0:\n u, d = q.popleft()\n farthestDist = d\n for v in graph[u]:\n if v not in visited and v in cities:\n visited.add(v)\n q.append((v, d+1))\n return farthestDist, visited\n\n def maxDistance(state): # return: maximum distance between any two cities in our subset. O(n^2)\n cities = set()\n for i in range(n):\n if (state >> i) & 1 == 1:\n cities.add(i)\n ans = 0\n for i in cities:\n farthestDist, visited = bfs(i, cities)\n if len(visited) < len(cities): return 0 # Can\'t visit all nodes of the tree -> Invalid tree\n ans = max(ans, farthestDist)\n return ans\n\n graph = defaultdict(list)\n for u, v in edges:\n graph[u-1].append(v-1)\n graph[v-1].append(u-1)\n \n ans = [0] * (n - 1)\n for state in range(1, 2 ** n):\n d = maxDistance(state)\n if d > 0: ans[d - 1] += 1\n return ans\n```
0
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. Return _an array of size_ `n-1` _where the_ `dth` _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. **Notice** that the **distance** between the two cities is the number of edges in the path between them. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,3\],\[2,4\]\] **Output:** \[3,4,0\] **Explanation:** The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. **Example 2:** **Input:** n = 2, edges = \[\[1,2\]\] **Output:** \[1\] **Example 3:** **Input:** n = 3, edges = \[\[1,2\],\[2,3\]\] **Output:** \[2,1\] **Constraints:** * `2 <= n <= 15` * `edges.length == n-1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * All pairs `(ui, vi)` are distinct.
Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.
Python3 easiest solution
count-subtrees-with-max-distance-between-cities
0
1
# Code\n```\nclass Solution(object):\n def countSubgraphsForEachDiameter(self, n, edges):\n def bfs(src, cities):\n visited = {src}\n q = deque([(src, 0)]) # Pair of (vertex, distance)\n farthestDist = 0 # Farthest distance from src to other nodes\n while len(q) > 0:\n u, d = q.popleft()\n farthestDist = d\n for v in graph[u]:\n if v not in visited and v in cities:\n visited.add(v)\n q.append((v, d+1))\n return farthestDist, visited\n\n def maxDistance(state): # return: maximum distance between any two cities in our subset. O(n^2)\n cities = set()\n for i in range(n):\n if (state >> i) & 1 == 1:\n cities.add(i)\n ans = 0\n for i in cities:\n farthestDist, visited = bfs(i, cities)\n if len(visited) < len(cities): return 0 # Can\'t visit all nodes of the tree -> Invalid tree\n ans = max(ans, farthestDist)\n return ans\n\n graph = defaultdict(list)\n for u, v in edges:\n graph[u-1].append(v-1)\n graph[v-1].append(u-1)\n \n ans = [0] * (n - 1)\n for state in range(1, 2 ** n):\n d = maxDistance(state)\n if d > 0: ans[d - 1] += 1\n return ans\n```
0
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
[Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained
count-subtrees-with-max-distance-between-cities
0
1
**Idea**\n\nI didn\'t see any posted DP solutions with a full writeup (or decent comments), so I wrote out each step in detail. The idea here is to choose any vertex `x` with neighbors `v1,v2...,vk`, and pretend that we have removed each edge `x--vi`. Suppose we only remove the first edge, `x--v1`, to split our tree T into two smaller trees Tx and Tv1 rooted at x and v1. **If we compute diameters and counts for subtrees in `Tx` and `Tv1`, we can \'merge\' these** (i.e. add back the edge `v1`) to find diameters and counts for a combined tree rooted at `x`. We do this merging once for each neighbor, adding back the edge to `v1`, then to `v2` and so on.\n\n**Complexity**\n\nTime: `O(n^5)` We call merge exactly once for each edge; merge is called only from compute_subtree_counts, and compute_subtree_counts is called exactly once for each vertex. There are, worst case, `O(n^4)` operations in merge. Our outer loop in merge is over all (diameter, height) pairs of each subtree of `parent_vertex`, which can be at most `O(n^2)`; the inner loop is also at most `O(n^2)`. In practice, the time complexity is much better than `O(n^5)`, so perhaps it\'s possible to prove a smaller upper bound.\n\nThere may be a way to get `O(n^2)` or `O(n^3)` by using bottom-up DP and precomputing sums in the merge function [as discussed in this post](https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/896313/O(n2)-using-DP). If you find an implementation (or even detailed pseudocode) of that idea, please let me know. Space complexity is `O(n^3)` worst case, but I suspect this can be brought down to `O(n^2)` (and I suspect the true value of the current code to already be `O((n^2) log n)`) .\n\n\n**Python**\n\n\n```python\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n # Create Tree as adjacency list\n neigh: List[List[int]] = [[] for _ in range(n)]\n for u, v in edges:\n neigh[u - 1].append(v - 1)\n neigh[v - 1].append(u - 1)\n\n distance_array: List[int] = [0] * n\n\n def find_tree_center(vertices: List[int], adj_list: List[List[int]]) -> int:\n """Given a tree, return a central vertex (minimum radius vertex) with BFS"""\n\n num_neighbors: List[int] = list(map(len, adj_list))\n leaf_nodes: Deque[int] = collections.deque((x for x in range(len(vertices)) if num_neighbors[x] == 1))\n while len(leaf_nodes) > 1:\n leaf = leaf_nodes.popleft()\n for neighbor in adj_list[leaf]:\n num_neighbors[neighbor] -= 1\n if num_neighbors[neighbor] == 1:\n leaf_nodes.append(neighbor)\n return leaf_nodes[0]\n\n def merge_into_parent(parent_subtrees: Dict[Tuple[int, int], int],\n child_subtrees: Dict[Tuple[int, int], int]) -> None:\n\n """ Helper function to merge two disjoint rooted trees T_parent and T_child rooted at \'parent\' and \'child\',\n into one tree rooted at \'parent\', by adding an edge from \'parent\' to \'child\'.\n Called once for each edge in our tree. parent_subtrees[i, j] is the count of rooted subtrees\n of T_parent that contain \'parent\', have diameter i, and height j.\n Worst case complexity: O(n^4) per call\n """\n\n for (diam_for_parent, height_for_parent), count_from_parent in list(parent_subtrees.items()):\n\n for (diam_for_child, height_for_child), count_from_child in child_subtrees.items():\n\n new_diameter = max(diam_for_parent, diam_for_child, height_for_parent + height_for_child + 1)\n new_height = max(height_for_parent, height_for_child + 1)\n parent_subtrees[new_diameter, new_height] = parent_subtrees.get((new_diameter, new_height), 0) + count_from_child * count_from_parent\n\n return None\n\n def compute_subtree_counts(current_vertex: int,\n last_vertex: int = -1) -> Dict[Tuple[int, int], int]:\n """Recursively counts subtrees rooted at current_vertex using DFS,\n with edge from current_vertex to \'last_vertex\' (parent node) cut off"""\n subtree_counts: Dict[Tuple[int, int], int] = {(0, 0): 1}\n\n for child_vertex in neigh[current_vertex]:\n if child_vertex == last_vertex:\n continue\n\n merge_into_parent(parent_subtrees=subtree_counts,\n child_subtrees=compute_subtree_counts(current_vertex=child_vertex,\n last_vertex=current_vertex))\n\n for (diameter, height), subtree_count in subtree_counts.items():\n distance_array[diameter] += subtree_count\n\n return subtree_counts\n\n # Optimization: Use a max-degree vertex as our root to minimize recursion depth\n max_degree_vertex: int = find_tree_center(vertices=list(range(n)),\n adj_list=neigh)\n\n compute_subtree_counts(current_vertex=max_degree_vertex)\n\n return distance_array[1:]\n```
2
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. Return _an array of size_ `n-1` _where the_ `dth` _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. **Notice** that the **distance** between the two cities is the number of edges in the path between them. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,3\],\[2,4\]\] **Output:** \[3,4,0\] **Explanation:** The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. **Example 2:** **Input:** n = 2, edges = \[\[1,2\]\] **Output:** \[1\] **Example 3:** **Input:** n = 3, edges = \[\[1,2\],\[2,3\]\] **Output:** \[2,1\] **Constraints:** * `2 <= n <= 15` * `edges.length == n-1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * All pairs `(ui, vi)` are distinct.
Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.
[Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained
count-subtrees-with-max-distance-between-cities
0
1
**Idea**\n\nI didn\'t see any posted DP solutions with a full writeup (or decent comments), so I wrote out each step in detail. The idea here is to choose any vertex `x` with neighbors `v1,v2...,vk`, and pretend that we have removed each edge `x--vi`. Suppose we only remove the first edge, `x--v1`, to split our tree T into two smaller trees Tx and Tv1 rooted at x and v1. **If we compute diameters and counts for subtrees in `Tx` and `Tv1`, we can \'merge\' these** (i.e. add back the edge `v1`) to find diameters and counts for a combined tree rooted at `x`. We do this merging once for each neighbor, adding back the edge to `v1`, then to `v2` and so on.\n\n**Complexity**\n\nTime: `O(n^5)` We call merge exactly once for each edge; merge is called only from compute_subtree_counts, and compute_subtree_counts is called exactly once for each vertex. There are, worst case, `O(n^4)` operations in merge. Our outer loop in merge is over all (diameter, height) pairs of each subtree of `parent_vertex`, which can be at most `O(n^2)`; the inner loop is also at most `O(n^2)`. In practice, the time complexity is much better than `O(n^5)`, so perhaps it\'s possible to prove a smaller upper bound.\n\nThere may be a way to get `O(n^2)` or `O(n^3)` by using bottom-up DP and precomputing sums in the merge function [as discussed in this post](https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/896313/O(n2)-using-DP). If you find an implementation (or even detailed pseudocode) of that idea, please let me know. Space complexity is `O(n^3)` worst case, but I suspect this can be brought down to `O(n^2)` (and I suspect the true value of the current code to already be `O((n^2) log n)`) .\n\n\n**Python**\n\n\n```python\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n # Create Tree as adjacency list\n neigh: List[List[int]] = [[] for _ in range(n)]\n for u, v in edges:\n neigh[u - 1].append(v - 1)\n neigh[v - 1].append(u - 1)\n\n distance_array: List[int] = [0] * n\n\n def find_tree_center(vertices: List[int], adj_list: List[List[int]]) -> int:\n """Given a tree, return a central vertex (minimum radius vertex) with BFS"""\n\n num_neighbors: List[int] = list(map(len, adj_list))\n leaf_nodes: Deque[int] = collections.deque((x for x in range(len(vertices)) if num_neighbors[x] == 1))\n while len(leaf_nodes) > 1:\n leaf = leaf_nodes.popleft()\n for neighbor in adj_list[leaf]:\n num_neighbors[neighbor] -= 1\n if num_neighbors[neighbor] == 1:\n leaf_nodes.append(neighbor)\n return leaf_nodes[0]\n\n def merge_into_parent(parent_subtrees: Dict[Tuple[int, int], int],\n child_subtrees: Dict[Tuple[int, int], int]) -> None:\n\n """ Helper function to merge two disjoint rooted trees T_parent and T_child rooted at \'parent\' and \'child\',\n into one tree rooted at \'parent\', by adding an edge from \'parent\' to \'child\'.\n Called once for each edge in our tree. parent_subtrees[i, j] is the count of rooted subtrees\n of T_parent that contain \'parent\', have diameter i, and height j.\n Worst case complexity: O(n^4) per call\n """\n\n for (diam_for_parent, height_for_parent), count_from_parent in list(parent_subtrees.items()):\n\n for (diam_for_child, height_for_child), count_from_child in child_subtrees.items():\n\n new_diameter = max(diam_for_parent, diam_for_child, height_for_parent + height_for_child + 1)\n new_height = max(height_for_parent, height_for_child + 1)\n parent_subtrees[new_diameter, new_height] = parent_subtrees.get((new_diameter, new_height), 0) + count_from_child * count_from_parent\n\n return None\n\n def compute_subtree_counts(current_vertex: int,\n last_vertex: int = -1) -> Dict[Tuple[int, int], int]:\n """Recursively counts subtrees rooted at current_vertex using DFS,\n with edge from current_vertex to \'last_vertex\' (parent node) cut off"""\n subtree_counts: Dict[Tuple[int, int], int] = {(0, 0): 1}\n\n for child_vertex in neigh[current_vertex]:\n if child_vertex == last_vertex:\n continue\n\n merge_into_parent(parent_subtrees=subtree_counts,\n child_subtrees=compute_subtree_counts(current_vertex=child_vertex,\n last_vertex=current_vertex))\n\n for (diameter, height), subtree_count in subtree_counts.items():\n distance_array[diameter] += subtree_count\n\n return subtree_counts\n\n # Optimization: Use a max-degree vertex as our root to minimize recursion depth\n max_degree_vertex: int = find_tree_center(vertices=list(range(n)),\n adj_list=neigh)\n\n compute_subtree_counts(current_vertex=max_degree_vertex)\n\n return distance_array[1:]\n```
2
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
[python] Dynamic Programming, O(2^N*N)
count-subtrees-with-max-distance-between-cities
0
1
First calculate all node pairs\' distances, and then iterate all possible states sequentially while each state only require one update, therefore time complexity is only O(2^N*N)\n```python\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n res = [0]*(n-1)\n g = defaultdict(list)\n gs = [0]*n\n dp = [0]*(1<<n)\n for a, b in edges:\n a -= 1\n b -= 1\n g[a].append(b)\n g[b].append(a)\n gs[a] |= (1<<b)\n gs[b] |= (1<<a)\n dp[(1<<a)|(1<<b)] = 1\n dis = [[0]*n for _ in range(n)]\n def dfs(root, cur, depth, parent):\n dis[root][cur] = depth\n for nxt in g[cur]:\n if nxt == parent:\n continue\n dfs(root, nxt, depth+1, cur)\n return\n\n for i in range(n):\n dfs(i,i,0,-1)\n \n# print(dis)\n# print(ees)\n \n for state in range(1<<n):\n # print(state, dp[state])\n if dp[state] > 0:\n res[dp[state]-1] += 1\n for i in range(n):\n if dp[state | (1<<i)] == 0 and (state & gs[i]):\n dp[state | (1<<i)] = max(dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n # if dp[state | (1<<i)] == 0 and any((i,j) in ees for j in range(n) if state&(1<<j)):\n # dp[state | (1<<i)] = max(dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n # if state & (1<<i) == 0 and any((i,j) in ees for j in range(n) if state&(1<<j)):\n # dp[state ^ (1<<i)] = max(dp[state ^ (1<<i)], dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n return res\n\n```
4
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**. A **subtree** is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the **maximum distance** between any two cities in the subtree is equal to `d`. Return _an array of size_ `n-1` _where the_ `dth` _element **(1-indexed)** is the number of subtrees in which the **maximum distance** between any two cities is equal to_ `d`. **Notice** that the **distance** between the two cities is the number of edges in the path between them. **Example 1:** **Input:** n = 4, edges = \[\[1,2\],\[2,3\],\[2,4\]\] **Output:** \[3,4,0\] **Explanation:** The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. **Example 2:** **Input:** n = 2, edges = \[\[1,2\]\] **Output:** \[1\] **Example 3:** **Input:** n = 3, edges = \[\[1,2\],\[2,3\]\] **Output:** \[2,1\] **Constraints:** * `2 <= n <= 15` * `edges.length == n-1` * `edges[i].length == 2` * `1 <= ui, vi <= n` * All pairs `(ui, vi)` are distinct.
Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state.
[python] Dynamic Programming, O(2^N*N)
count-subtrees-with-max-distance-between-cities
0
1
First calculate all node pairs\' distances, and then iterate all possible states sequentially while each state only require one update, therefore time complexity is only O(2^N*N)\n```python\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n res = [0]*(n-1)\n g = defaultdict(list)\n gs = [0]*n\n dp = [0]*(1<<n)\n for a, b in edges:\n a -= 1\n b -= 1\n g[a].append(b)\n g[b].append(a)\n gs[a] |= (1<<b)\n gs[b] |= (1<<a)\n dp[(1<<a)|(1<<b)] = 1\n dis = [[0]*n for _ in range(n)]\n def dfs(root, cur, depth, parent):\n dis[root][cur] = depth\n for nxt in g[cur]:\n if nxt == parent:\n continue\n dfs(root, nxt, depth+1, cur)\n return\n\n for i in range(n):\n dfs(i,i,0,-1)\n \n# print(dis)\n# print(ees)\n \n for state in range(1<<n):\n # print(state, dp[state])\n if dp[state] > 0:\n res[dp[state]-1] += 1\n for i in range(n):\n if dp[state | (1<<i)] == 0 and (state & gs[i]):\n dp[state | (1<<i)] = max(dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n # if dp[state | (1<<i)] == 0 and any((i,j) in ees for j in range(n) if state&(1<<j)):\n # dp[state | (1<<i)] = max(dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n # if state & (1<<i) == 0 and any((i,j) in ees for j in range(n) if state&(1<<j)):\n # dp[state ^ (1<<i)] = max(dp[state ^ (1<<i)], dp[state], max(dis[i][j] for j in range(n) if state&(1<<j)))\n return res\n\n```
4
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Awesome Logic with shocking Code
mean-of-array-after-removing-some-elements
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 trimMean(self, arr: List[int]) -> float:\n n=int(0.05*len(arr))\n for i in range(n):\n arr.remove(min(arr))\n arr.remove(max(arr))\n return sum(arr)/len(arr)\n#please upvote me it would encourage me alot\n```
7
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
PYTHON | Without sorting | Easy solution
mean-of-array-after-removing-some-elements
0
1
```\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n counter = 0.05*len(arr)\n \n while counter != 0:\n arr.remove(min(arr))\n arr.remove(max(arr))\n counter -= 1\n \n return sum(arr) / len(arr)\n```
3
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Simple and easiest solution Beginner Friendly.
mean-of-array-after-removing-some-elements
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 trimMean(self, arr: List[int]) -> float:\n x=arr.sort()\n len1=len(arr)\n y=len1//20\n sum1=sum(arr[y:len1-y])\n return sum1/(len1-2*y)\n #please do upvote it will encourage me alot\n```
4
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Python 2 lines simple solution
mean-of-array-after-removing-some-elements
0
1
**Python :**\n\n```\ndef trimMean(self, arr: List[int]) -> float:\n\tarr = sorted(arr)\n\treturn statistics.mean(arr[int(0.05 * len(arr)):(len(arr) - int(0.05 * len(arr)))]) \n```\n\n**Like it ? please upvote !**
6
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Python - Short & Simple
mean-of-array-after-removing-some-elements
0
1
```\ndef trimMean(self, arr: List[int]) -> float:\n\t# first will sort the array then we will return the mean of those elements\n\t# which are not in least 5% and max 5% of the elements\n\t# try to divide the following return statement and get the intuition\n\t\n fivePercent = (5*len(arr))//100\n arr.sort()\n return sum(arr[fivePercent:len(arr)-fivePercent]) / (len(arr)-(fivePercent*2))\n```
1
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
2 easy Python Solutions
mean-of-array-after-removing-some-elements
0
1
```\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n\n return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])\n \n```\n\n**Solution two:**\n```\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n \n n = len(arr)\n per = int(n*5/100)\n l2 = arr[per:len(arr)-per]\n\t\t\n x = sum(l2)/len(l2)\n\n return x\n \n```
10
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Python solution
mean-of-array-after-removing-some-elements
0
1
```\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n amount_to_remove = int(len(arr) * 0.05)\n new_one = arr[amount_to_remove:-amount_to_remove]\n\n return sum(new_one) / len(new_one)\n \n```
0
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Python Simple Solution!!
mean-of-array-after-removing-some-elements
0
1
# Code\n```\nclass Solution:\n def trimMean(self, arr: List[int]) -> float:\n \n arr.sort()\n amount: int = int(len(arr) * 0.05)\n return sum(arr[amount: len(arr) - amount]) / len(arr[amount: len(arr) - amount])\n```
0
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
python beats 93%
mean-of-array-after-removing-some-elements
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 trimMean(self, arr: List[int]) -> float:\n arr.sort()\n n = len(arr)\n arr = arr[int(0+n*0.05):int(n-n*0.05)]\n return sum(arr)/len(arr)\n \n```
0
Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._ Answers within `10-5` of the **actual answer** will be considered accepted. **Example 1:** **Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\] **Output:** 2.00000 **Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2. **Example 2:** **Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\] **Output:** 4.00000 **Example 3:** **Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\] **Output:** 4.77778 **Constraints:** * `20 <= arr.length <= 1000` * `arr.length` **is a multiple** of `20`. * `0 <= arr[i] <= 105`
Simulate the process while keeping track of visited points. Use a set to store previously visited points.
Bounding Box and Defaults
coordinate-with-maximum-network-quality
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne of the key ideas from computer graphics is that of a bounding box, or area that something fits into. In this case we have a bounding box around each tower, and around each point in the array. As such, we have a bounding box that can then reflect the current points of interest to loop over. This leads to the idea that we loop over the integral coordinates (pixels) in our bounding box of the network, and can then find within there the strongest signal quality summation. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet up a few helper functions first; I used a euclid and a reachable function. The euclid calculates euclidean distance. The reachable calculates an array of reachability status and distance from a tower given a coordinate. These together form the backbone of our search process. \n\nThen, set up your min and max x and y. We know these are possible as the signal at each tower is maximal at the tower location. This means that we can find a bounding box as min x and y as either 0 or minimal x and y values - 1 if the minimals are greater than or equal to 1 and a maximal as 51 or any value less than 51. \n\nThen we set up a lexicographical coordinate checker, c1_lt_c2, which does the lexicographic comparison as described in the problem. \n\nDefine a default for the result of [0, 0] in case of 0 signal everywhere. \nDefine a default signal of 0. \n\nThen, loop your bounding area (double loop necessitates) \n- get your coordinate and calculate your quality here by looping towers \n- if quality is gt 0 \n - if quality is gt default signal \n - update default signal and default coordinate \n - elif quality is equal to default signal \n - check lexicographical nature, and update as needed \n - otherwise continue \n- otherwise continue \n\nAt end return your default coordinate \n\n# Complexity\n- Time complexity : O(A * T)\n - Takes O(A) where A is the boudning box area to loop over area \n - During which in each step do O(T) to loop towers \n - total complexity is O(A * T) \n\n- Space complexity : O(1) \n - Takes up no extra space beyond specified \n\n# Code\n```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n\n # to get distance \n def euclid(x1, y1, x2, y2) : \n return math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)))\n\n # to calculate reachable tower ids vs coordinates \n def reachable(tower_a, x2, y2) : \n x1, y1, q1 = tower_a\n distance = euclid(x1, y1, x2, y2)\n return [distance <= radius, distance]\n\n # find max x and y in towers \n max_x = 0 \n max_y = 0 \n min_x = 51\n min_y = 51 \n for tower in towers : \n x, y, q = tower \n max_x = max(max_x, x)\n min_x = min(min_x, x)\n max_y = max(max_y, y)\n min_y = min(min_y, y)\n # off by 1 in each direction to achieve bounding box maximally \n max_x += 1 \n min_x = min_x - 1 if min_x >= 1 else min_x\n max_y += 1 \n min_y = min_y - 1 if min_y >= 1 else min_y \n \n # to lexicographically compare coordinates \n def c1_lt_c2(c1, c2) : \n if c1[0] < c2[0] : \n return True \n elif c1[0] == c2[0] and c1[1] < c2[1] : \n return True \n else : \n return False \n\n # set defaults and signal \n default_coordinate = [0, 0]\n default_signal = 0 \n\n # loop over coordinates of network bounding box \n for x in range(min_x, max_x, 1) : \n for y in range(min_y, max_y, 1) : \n # get current coordinate and quality \n c = [x, y]\n quality = 0 \n # by looping tower in towers \n for tower in towers : \n # and checking validity \n validity = reachable(tower, x, y) \n # update based on validity calculation \n if validity[0] : \n quality += int(tower[2] / (1 + validity[1])) \n else : \n quality += 0 \n # if quality is gt 0 \n if quality > 0 : \n # if it is greater than default current \n if quality > default_signal : \n # update both \n default_signal = quality \n default_coordinate = c \n # elif it is a match \n elif quality == default_signal : \n # only update on lexicographic improvement\n if c1_lt_c2(c, default_coordinate) : \n default_signal = quality \n default_coordinate = c \n else : \n continue \n else : \n continue \n else : \n continue \n # default return is [0, 0] if no signal, otherwise best coordinate in bounding box \n return default_coordinate \n```
0
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**. You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**. The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers. Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._ **Note:** * A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either: * `x1 < x2`, or * `x1 == x2` and `y1 < y2`. * `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function). **Example 1:** **Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2 **Output:** \[2,1\] **Explanation:** At coordinate (2, 1) the total quality is 13. - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 No other coordinate has a higher network quality. **Example 2:** **Input:** towers = \[\[23,11,21\]\], radius = 9 **Output:** \[23,11\] **Explanation:** Since there is only one tower, the network quality is highest right at the tower's location. **Example 3:** **Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2 **Output:** \[1,2\] **Explanation:** Coordinate (1, 2) has the highest network quality. **Constraints:** * `1 <= towers.length <= 50` * `towers[i].length == 3` * `0 <= xi, yi, qi <= 50` * `1 <= radius <= 50`
Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0
Bounding Box and Defaults
coordinate-with-maximum-network-quality
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne of the key ideas from computer graphics is that of a bounding box, or area that something fits into. In this case we have a bounding box around each tower, and around each point in the array. As such, we have a bounding box that can then reflect the current points of interest to loop over. This leads to the idea that we loop over the integral coordinates (pixels) in our bounding box of the network, and can then find within there the strongest signal quality summation. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSet up a few helper functions first; I used a euclid and a reachable function. The euclid calculates euclidean distance. The reachable calculates an array of reachability status and distance from a tower given a coordinate. These together form the backbone of our search process. \n\nThen, set up your min and max x and y. We know these are possible as the signal at each tower is maximal at the tower location. This means that we can find a bounding box as min x and y as either 0 or minimal x and y values - 1 if the minimals are greater than or equal to 1 and a maximal as 51 or any value less than 51. \n\nThen we set up a lexicographical coordinate checker, c1_lt_c2, which does the lexicographic comparison as described in the problem. \n\nDefine a default for the result of [0, 0] in case of 0 signal everywhere. \nDefine a default signal of 0. \n\nThen, loop your bounding area (double loop necessitates) \n- get your coordinate and calculate your quality here by looping towers \n- if quality is gt 0 \n - if quality is gt default signal \n - update default signal and default coordinate \n - elif quality is equal to default signal \n - check lexicographical nature, and update as needed \n - otherwise continue \n- otherwise continue \n\nAt end return your default coordinate \n\n# Complexity\n- Time complexity : O(A * T)\n - Takes O(A) where A is the boudning box area to loop over area \n - During which in each step do O(T) to loop towers \n - total complexity is O(A * T) \n\n- Space complexity : O(1) \n - Takes up no extra space beyond specified \n\n# Code\n```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n\n # to get distance \n def euclid(x1, y1, x2, y2) : \n return math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)))\n\n # to calculate reachable tower ids vs coordinates \n def reachable(tower_a, x2, y2) : \n x1, y1, q1 = tower_a\n distance = euclid(x1, y1, x2, y2)\n return [distance <= radius, distance]\n\n # find max x and y in towers \n max_x = 0 \n max_y = 0 \n min_x = 51\n min_y = 51 \n for tower in towers : \n x, y, q = tower \n max_x = max(max_x, x)\n min_x = min(min_x, x)\n max_y = max(max_y, y)\n min_y = min(min_y, y)\n # off by 1 in each direction to achieve bounding box maximally \n max_x += 1 \n min_x = min_x - 1 if min_x >= 1 else min_x\n max_y += 1 \n min_y = min_y - 1 if min_y >= 1 else min_y \n \n # to lexicographically compare coordinates \n def c1_lt_c2(c1, c2) : \n if c1[0] < c2[0] : \n return True \n elif c1[0] == c2[0] and c1[1] < c2[1] : \n return True \n else : \n return False \n\n # set defaults and signal \n default_coordinate = [0, 0]\n default_signal = 0 \n\n # loop over coordinates of network bounding box \n for x in range(min_x, max_x, 1) : \n for y in range(min_y, max_y, 1) : \n # get current coordinate and quality \n c = [x, y]\n quality = 0 \n # by looping tower in towers \n for tower in towers : \n # and checking validity \n validity = reachable(tower, x, y) \n # update based on validity calculation \n if validity[0] : \n quality += int(tower[2] / (1 + validity[1])) \n else : \n quality += 0 \n # if quality is gt 0 \n if quality > 0 : \n # if it is greater than default current \n if quality > default_signal : \n # update both \n default_signal = quality \n default_coordinate = c \n # elif it is a match \n elif quality == default_signal : \n # only update on lexicographic improvement\n if c1_lt_c2(c, default_coordinate) : \n default_signal = quality \n default_coordinate = c \n else : \n continue \n else : \n continue \n else : \n continue \n # default return is [0, 0] if no signal, otherwise best coordinate in bounding box \n return default_coordinate \n```
0
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Example 1:** **Input:** nums = \[2,3,4,6\] **Output:** 8 **Explanation:** There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) **Example 2:** **Input:** nums = \[1,2,4,5,10\] **Output:** 16 **Explanation:** There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * All elements in `nums` are **distinct**.
The constraints are small enough to consider every possible coordinate and calculate its quality.
Python - brute force
coordinate-with-maximum-network-quality
0
1
# Intuition\nBrute force search on complete space 50x50\n\n\n# Complexity\n- Time complexity:\n$$O(50^2T)$$\n\n\n\n# Code\n```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n edist = lambda a, b: ((a[0]-b[0])**2 + (a[1]-b[1])**2)**.5\n quality = lambda q, d: floor(abs(q / (1 + d)))\n max_quality, result = 0, [(0, 0)]\n for coors in product(range(51), range(51)):\n curr = 0\n for xx, yy, qq in towers:\n dd = edist(coors, (xx,yy))\n if dd <= radius: curr += quality(qq, dd)\n if curr == max_quality: result.append(coors)\n elif curr > max_quality: max_quality, result = curr, [coors]\n return sorted(result)[0]\n```
0
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**. You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**. The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers. Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._ **Note:** * A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either: * `x1 < x2`, or * `x1 == x2` and `y1 < y2`. * `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function). **Example 1:** **Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2 **Output:** \[2,1\] **Explanation:** At coordinate (2, 1) the total quality is 13. - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 No other coordinate has a higher network quality. **Example 2:** **Input:** towers = \[\[23,11,21\]\], radius = 9 **Output:** \[23,11\] **Explanation:** Since there is only one tower, the network quality is highest right at the tower's location. **Example 3:** **Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2 **Output:** \[1,2\] **Explanation:** Coordinate (1, 2) has the highest network quality. **Constraints:** * `1 <= towers.length <= 50` * `towers[i].length == 3` * `0 <= xi, yi, qi <= 50` * `1 <= radius <= 50`
Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0
Python - brute force
coordinate-with-maximum-network-quality
0
1
# Intuition\nBrute force search on complete space 50x50\n\n\n# Complexity\n- Time complexity:\n$$O(50^2T)$$\n\n\n\n# Code\n```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n edist = lambda a, b: ((a[0]-b[0])**2 + (a[1]-b[1])**2)**.5\n quality = lambda q, d: floor(abs(q / (1 + d)))\n max_quality, result = 0, [(0, 0)]\n for coors in product(range(51), range(51)):\n curr = 0\n for xx, yy, qq in towers:\n dd = edist(coors, (xx,yy))\n if dd <= radius: curr += quality(qq, dd)\n if curr == max_quality: result.append(coors)\n elif curr > max_quality: max_quality, result = curr, [coors]\n return sorted(result)[0]\n```
0
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Example 1:** **Input:** nums = \[2,3,4,6\] **Output:** 8 **Explanation:** There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) **Example 2:** **Input:** nums = \[1,2,4,5,10\] **Output:** 16 **Explanation:** There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * All elements in `nums` are **distinct**.
The constraints are small enough to consider every possible coordinate and calculate its quality.
Python3 solution beats 98%. exPlained
coordinate-with-maximum-network-quality
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought was to iterate through all the towers and calculate the quality of signal for each tower and then compare them to find the best coordinate.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI decided to iterate through all the coordinates from 0 to 50 and calculate the quality of signal at each coordinate by taking into account the signal strength of the towers and the distance from each tower. Then I compared the quality at each coordinate and stored the highest quality and the corresponding coordinate in two variables. Lastly, I returned the coordinate with the highest quality.\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 bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n ans = [0, 0]\n max_quality = 0\n for x in range(51):\n for y in range(51):\n quality = 0\n for tower in towers:\n distance = (x - tower[0]) * (x - tower[0]) + (y - tower[1]) * (y - tower[1])\n if distance <= radius * radius:\n quality += int(tower[2] / (1 + math.sqrt(distance)))\n if quality > max_quality:\n max_quality = quality\n ans = [x, y]\n return ans\n```
0
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**. You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**. The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers. Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._ **Note:** * A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either: * `x1 < x2`, or * `x1 == x2` and `y1 < y2`. * `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function). **Example 1:** **Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2 **Output:** \[2,1\] **Explanation:** At coordinate (2, 1) the total quality is 13. - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 No other coordinate has a higher network quality. **Example 2:** **Input:** towers = \[\[23,11,21\]\], radius = 9 **Output:** \[23,11\] **Explanation:** Since there is only one tower, the network quality is highest right at the tower's location. **Example 3:** **Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2 **Output:** \[1,2\] **Explanation:** Coordinate (1, 2) has the highest network quality. **Constraints:** * `1 <= towers.length <= 50` * `towers[i].length == 3` * `0 <= xi, yi, qi <= 50` * `1 <= radius <= 50`
Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0
Python3 solution beats 98%. exPlained
coordinate-with-maximum-network-quality
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought was to iterate through all the towers and calculate the quality of signal for each tower and then compare them to find the best coordinate.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI decided to iterate through all the coordinates from 0 to 50 and calculate the quality of signal at each coordinate by taking into account the signal strength of the towers and the distance from each tower. Then I compared the quality at each coordinate and stored the highest quality and the corresponding coordinate in two variables. Lastly, I returned the coordinate with the highest quality.\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 bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n ans = [0, 0]\n max_quality = 0\n for x in range(51):\n for y in range(51):\n quality = 0\n for tower in towers:\n distance = (x - tower[0]) * (x - tower[0]) + (y - tower[1]) * (y - tower[1])\n if distance <= radius * radius:\n quality += int(tower[2] / (1 + math.sqrt(distance)))\n if quality > max_quality:\n max_quality = quality\n ans = [x, y]\n return ans\n```
0
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Example 1:** **Input:** nums = \[2,3,4,6\] **Output:** 8 **Explanation:** There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) **Example 2:** **Input:** nums = \[1,2,4,5,10\] **Output:** 16 **Explanation:** There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * All elements in `nums` are **distinct**.
The constraints are small enough to consider every possible coordinate and calculate its quality.
python 3
coordinate-with-maximum-network-quality
0
1
```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n \n def getQuality(x,y):\n ans = 0\n for i,j,q in towers:\n d = math.sqrt((x-i)**2+(y-j)**2)\n if d<=radius:\n ans+=math.floor(q/(1+d))\n return ans\n q = -math.inf\n minX = min(t[0] for t in towers)\n maxX = max(t[0] for t in towers)\n minY = min(t[1] for t in towers)\n maxY = max(t[1] for t in towers)\n for i in range(minX,maxX+1):\n for j in range(minY,maxY+1):\n q1 = getQuality(i,j)\n if q1>q:\n q = q1 \n ans = [i,j]\n return ans\n```
2
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**. You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**. The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers. Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._ **Note:** * A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either: * `x1 < x2`, or * `x1 == x2` and `y1 < y2`. * `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function). **Example 1:** **Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2 **Output:** \[2,1\] **Explanation:** At coordinate (2, 1) the total quality is 13. - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 No other coordinate has a higher network quality. **Example 2:** **Input:** towers = \[\[23,11,21\]\], radius = 9 **Output:** \[23,11\] **Explanation:** Since there is only one tower, the network quality is highest right at the tower's location. **Example 3:** **Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2 **Output:** \[1,2\] **Explanation:** Coordinate (1, 2) has the highest network quality. **Constraints:** * `1 <= towers.length <= 50` * `towers[i].length == 3` * `0 <= xi, yi, qi <= 50` * `1 <= radius <= 50`
Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0
python 3
coordinate-with-maximum-network-quality
0
1
```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n \n def getQuality(x,y):\n ans = 0\n for i,j,q in towers:\n d = math.sqrt((x-i)**2+(y-j)**2)\n if d<=radius:\n ans+=math.floor(q/(1+d))\n return ans\n q = -math.inf\n minX = min(t[0] for t in towers)\n maxX = max(t[0] for t in towers)\n minY = min(t[1] for t in towers)\n maxY = max(t[1] for t in towers)\n for i in range(minX,maxX+1):\n for j in range(minY,maxY+1):\n q1 = getQuality(i,j)\n if q1>q:\n q = q1 \n ans = [i,j]\n return ans\n```
2
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Example 1:** **Input:** nums = \[2,3,4,6\] **Output:** 8 **Explanation:** There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) **Example 2:** **Input:** nums = \[1,2,4,5,10\] **Output:** 16 **Explanation:** There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * All elements in `nums` are **distinct**.
The constraints are small enough to consider every possible coordinate and calculate its quality.
[Python3] enumerate all candidates
coordinate-with-maximum-network-quality
0
1
\n```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n mx = -inf\n for x in range(51):\n for y in range(51): \n val = 0\n for xi, yi, qi in towers: \n d = sqrt((x-xi)**2 + (y-yi)**2)\n if d <= radius: val += int(qi/(1 + d))\n if val > mx: \n ans = [x, y]\n mx = val\n return ans \n```
2
You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**. You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**. The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers. Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._ **Note:** * A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either: * `x1 < x2`, or * `x1 == x2` and `y1 < y2`. * `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function). **Example 1:** **Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2 **Output:** \[2,1\] **Explanation:** At coordinate (2, 1) the total quality is 13. - Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7 - Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2 - Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4 No other coordinate has a higher network quality. **Example 2:** **Input:** towers = \[\[23,11,21\]\], radius = 9 **Output:** \[23,11\] **Explanation:** Since there is only one tower, the network quality is highest right at the tower's location. **Example 3:** **Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2 **Output:** \[1,2\] **Explanation:** Coordinate (1, 2) has the highest network quality. **Constraints:** * `1 <= towers.length <= 50` * `towers[i].length == 3` * `0 <= xi, yi, qi <= 50` * `1 <= radius <= 50`
Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0
[Python3] enumerate all candidates
coordinate-with-maximum-network-quality
0
1
\n```\nclass Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n mx = -inf\n for x in range(51):\n for y in range(51): \n val = 0\n for xi, yi, qi in towers: \n d = sqrt((x-xi)**2 + (y-yi)**2)\n if d <= radius: val += int(qi/(1 + d))\n if val > mx: \n ans = [x, y]\n mx = val\n return ans \n```
2
Given an array `nums` of **distinct** positive integers, return _the number of tuples_ `(a, b, c, d)` _such that_ `a * b = c * d` _where_ `a`_,_ `b`_,_ `c`_, and_ `d` _are elements of_ `nums`_, and_ `a != b != c != d`_._ **Example 1:** **Input:** nums = \[2,3,4,6\] **Output:** 8 **Explanation:** There are 8 valid tuples: (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3) (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2) **Example 2:** **Input:** nums = \[1,2,4,5,10\] **Output:** 16 **Explanation:** There are 16 valid tuples: (1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2) (2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1) (2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4) (4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2) **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 104` * All elements in `nums` are **distinct**.
The constraints are small enough to consider every possible coordinate and calculate its quality.
[Java/Python] Top Down DP - Clean & Concise - O(4*n*k)
number-of-sets-of-k-non-overlapping-line-segments
1
1
**Python 3**\n```python\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @lru_cache(None)\n def dp(i, k, isStart):\n if k == 0: return 1 # Found a way to draw k valid segments\n if i == n: return 0 # Reach end of points\n ans = dp(i+1, k, isStart) # Skip ith point\n if isStart:\n ans += dp(i+1, k, False) # Take ith point as start\n else:\n ans += dp(i, k-1, True) # Take ith point as end\n return ans % MOD\n return dp(0, k, True)\n```\n\n**Java**\n```java\nclass Solution {\n Integer[][][] memo;\n int n;\n public int numberOfSets(int n, int k) {\n this.n = n;\n this.memo = new Integer[n+1][k+1][2];\n return dp(0, k, 1);\n }\n int dp(int i, int k, int isStart) {\n if (memo[i][k][isStart] != null) return memo[i][k][isStart];\n if (k == 0) return 1; // Found a way to draw k valid segments\n if (i == n) return 0; // Reach end of points\n\n int ans = dp(i+1, k, isStart); // Skip ith point\n if (isStart == 1)\n ans += dp(i+1, k, 0); // Take ith point as start\n else\n ans += dp(i, k-1, 1); // Take ith point as end\n\n return memo[i][k][isStart] = ans % 1_000_000_007;\n }\n}\n```\n\n**Complexity:**\n- Time: `O(4*n*k)`, there are total `2*n*k` state in `dp(i, k, isStart)` functions, inside function there are at most twice call of `dp` function.\n- Space: `O(2*n*k)`\n\nFeel free to ask your quetions. If this post is helpful, please help to give it a **vote**!.\nHappy coding!
77
Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints. Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 4, k = 2 **Output:** 5 **Explanation:** The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. **Example 2:** **Input:** n = 3, k = 1 **Output:** 3 **Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. **Example 3:** **Input:** n = 30, k = 7 **Output:** 796297179 **Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. **Constraints:** * `2 <= n <= 1000` * `1 <= k <= n-1`
Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences.
[Java/Python] Top Down DP - Clean & Concise - O(4*n*k)
number-of-sets-of-k-non-overlapping-line-segments
1
1
**Python 3**\n```python\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @lru_cache(None)\n def dp(i, k, isStart):\n if k == 0: return 1 # Found a way to draw k valid segments\n if i == n: return 0 # Reach end of points\n ans = dp(i+1, k, isStart) # Skip ith point\n if isStart:\n ans += dp(i+1, k, False) # Take ith point as start\n else:\n ans += dp(i, k-1, True) # Take ith point as end\n return ans % MOD\n return dp(0, k, True)\n```\n\n**Java**\n```java\nclass Solution {\n Integer[][][] memo;\n int n;\n public int numberOfSets(int n, int k) {\n this.n = n;\n this.memo = new Integer[n+1][k+1][2];\n return dp(0, k, 1);\n }\n int dp(int i, int k, int isStart) {\n if (memo[i][k][isStart] != null) return memo[i][k][isStart];\n if (k == 0) return 1; // Found a way to draw k valid segments\n if (i == n) return 0; // Reach end of points\n\n int ans = dp(i+1, k, isStart); // Skip ith point\n if (isStart == 1)\n ans += dp(i+1, k, 0); // Take ith point as start\n else\n ans += dp(i, k-1, 1); // Take ith point as end\n\n return memo[i][k][isStart] = ans % 1_000_000_007;\n }\n}\n```\n\n**Complexity:**\n- Time: `O(4*n*k)`, there are total `2*n*k` state in `dp(i, k, isStart)` functions, inside function there are at most twice call of `dp` function.\n- Space: `O(2*n*k)`\n\nFeel free to ask your quetions. If this post is helpful, please help to give it a **vote**!.\nHappy coding!
77
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Top Down DP | O(n*k)
number-of-sets-of-k-non-overlapping-line-segments
0
1
\n\nDp state here is-\nidx - means current index\nrem - means remaining lines we need to draw\nisInMiddle - is a boolean representing whether we have started drawing a line and currently in middle of that.\n\n\n```\nimport sys\nsys.setrecursionlimit(10**9)\n\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n M = 10**9+7\n \n @lru_cache(None)\n def helper(idx, rem, isInMiddle):\n if idx==n-1:\n if rem:\n return 0\n else:\n return 1\n ans = 0\n if isInMiddle:\n ans += helper(idx+1, rem, isInMiddle)\n ans %= M\n ans += helper(idx+1, rem, not isInMiddle)\n ans %= M\n if rem>0:\n ans += helper(idx+1, rem-1, isInMiddle)\n ans %= M\n else:\n ans += helper(idx+1, rem, isInMiddle)\n ans %= M\n if rem>0:\n ans += helper(idx+1, rem-1, not isInMiddle)\n ans %= M\n return ans\n return helper(0, k, False)\n \n
5
Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints. Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 4, k = 2 **Output:** 5 **Explanation:** The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. **Example 2:** **Input:** n = 3, k = 1 **Output:** 3 **Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. **Example 3:** **Input:** n = 30, k = 7 **Output:** 796297179 **Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. **Constraints:** * `2 <= n <= 1000` * `1 <= k <= n-1`
Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences.
Top Down DP | O(n*k)
number-of-sets-of-k-non-overlapping-line-segments
0
1
\n\nDp state here is-\nidx - means current index\nrem - means remaining lines we need to draw\nisInMiddle - is a boolean representing whether we have started drawing a line and currently in middle of that.\n\n\n```\nimport sys\nsys.setrecursionlimit(10**9)\n\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n M = 10**9+7\n \n @lru_cache(None)\n def helper(idx, rem, isInMiddle):\n if idx==n-1:\n if rem:\n return 0\n else:\n return 1\n ans = 0\n if isInMiddle:\n ans += helper(idx+1, rem, isInMiddle)\n ans %= M\n ans += helper(idx+1, rem, not isInMiddle)\n ans %= M\n if rem>0:\n ans += helper(idx+1, rem-1, isInMiddle)\n ans %= M\n else:\n ans += helper(idx+1, rem, isInMiddle)\n ans %= M\n if rem>0:\n ans += helper(idx+1, rem-1, not isInMiddle)\n ans %= M\n return ans\n return helper(0, k, False)\n \n
5
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Python DP Solution from Pattern
number-of-sets-of-k-non-overlapping-line-segments
0
1
```\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n dp = [[0 for i in range(n+1)] for j in range(k)]\n\n for i in range(1,n+1):\n dp[0][i] = dp[0][i-1] + i-1\n\n for i in range(1,k):\n cur = 0\n for j in range(i+2,n+1):\n cur += dp[i-1][j-1]\n\n dp[i][j] = cur + dp[i][j-1]\n \n return dp[-1][-1] % 1_000_000_007\n \n```
0
Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints. Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 4, k = 2 **Output:** 5 **Explanation:** The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. **Example 2:** **Input:** n = 3, k = 1 **Output:** 3 **Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. **Example 3:** **Input:** n = 30, k = 7 **Output:** 796297179 **Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. **Constraints:** * `2 <= n <= 1000` * `1 <= k <= n-1`
Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences.
Python DP Solution from Pattern
number-of-sets-of-k-non-overlapping-line-segments
0
1
```\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n dp = [[0 for i in range(n+1)] for j in range(k)]\n\n for i in range(1,n+1):\n dp[0][i] = dp[0][i-1] + i-1\n\n for i in range(1,k):\n cur = 0\n for j in range(i+2,n+1):\n cur += dp[i-1][j-1]\n\n dp[i][j] = cur + dp[i][j-1]\n \n return dp[-1][-1] % 1_000_000_007\n \n```
0
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Python | Top Down DP + Suffix Sum | Concise
number-of-sets-of-k-non-overlapping-line-segments
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nTop Down DP + Suffix Sum\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(nk)$\n\n# Code\n```\nfrom functools import cache\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @cache\n def dfs(i, k):\n if k == 0: return 1\n if i == n: return 0\n res = 0\n res = (res + suffix(i+1,k-1)) % MOD\n res = (res + dfs(i+1, k)) % MOD\n return res\n @cache\n def suffix(i, k):\n if i == n: return 0\n return (dfs(i,k) + suffix(i+1,k)) % MOD\n return dfs(0, k)\n```
0
Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints. Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 4, k = 2 **Output:** 5 **Explanation:** The two line segments are shown in red and blue. The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}. **Example 2:** **Input:** n = 3, k = 1 **Output:** 3 **Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}. **Example 3:** **Input:** n = 30, k = 7 **Output:** 796297179 **Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179. **Constraints:** * `2 <= n <= 1000` * `1 <= k <= n-1`
Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences.
Python | Top Down DP + Suffix Sum | Concise
number-of-sets-of-k-non-overlapping-line-segments
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nTop Down DP + Suffix Sum\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(nk)$\n\n# Code\n```\nfrom functools import cache\nclass Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @cache\n def dfs(i, k):\n if k == 0: return 1\n if i == n: return 0\n res = 0\n res = (res + suffix(i+1,k-1)) % MOD\n res = (res + dfs(i+1, k)) % MOD\n return res\n @cache\n def suffix(i, k):\n if i == n: return 0\n return (dfs(i,k) + suffix(i+1,k)) % MOD\n return dfs(0, k)\n```
0
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Python3 with explanation
fancy-sequence
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 Fancy:\n def __init__(self):\n self.arr = []\n self.add = [0]\n self.mul = [1]\n self.MOD = 10**9 + 7\n\n def append(self, val: int) -> None:\n self.arr.append(val)\n self.add.append(self.add[-1])\n self.mul.append(self.mul[-1])\n\n def addAll(self, inc: int) -> None:\n self.add[-1] += inc\n\n def multAll(self, m: int) -> None:\n self.add[-1] = (self.add[-1] * m) % self.MOD\n self.mul[-1] = (self.mul[-1] * m) % self.MOD\n\n def getIndex(self, idx: int) -> int:\n if idx >= len(self.arr):\n return -1\n m = self.mul[-1] * pow(self.mul[idx], -1, self.MOD)\n inc = self.add[-1] - self.add[idx] * m\n return (self.arr[idx] * m + inc) % self.MOD\n\n```
0
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `val` to the end of the sequence. * `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. * `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. * `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`. **Example 1:** **Input** \[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\] \[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\] **Output** \[null, null, null, null, null, 10, null, null, null, 26, 34, 20\] **Explanation** Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: \[2\] fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\] fancy.append(7); // fancy sequence: \[5, 7\] fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\] fancy.append(10); // fancy sequence: \[13, 17, 10\] fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20 **Constraints:** * `1 <= val, inc, m <= 100` * `0 <= idx <= 105` * At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
Python3 with explanation
fancy-sequence
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 Fancy:\n def __init__(self):\n self.arr = []\n self.add = [0]\n self.mul = [1]\n self.MOD = 10**9 + 7\n\n def append(self, val: int) -> None:\n self.arr.append(val)\n self.add.append(self.add[-1])\n self.mul.append(self.mul[-1])\n\n def addAll(self, inc: int) -> None:\n self.add[-1] += inc\n\n def multAll(self, m: int) -> None:\n self.add[-1] = (self.add[-1] * m) % self.MOD\n self.mul[-1] = (self.mul[-1] * m) % self.MOD\n\n def getIndex(self, idx: int) -> int:\n if idx >= len(self.arr):\n return -1\n m = self.mul[-1] * pow(self.mul[idx], -1, self.MOD)\n inc = self.add[-1] - self.add[idx] * m\n return (self.arr[idx] * m + inc) % self.MOD\n\n```
0
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Fast Python solution
fancy-sequence
0
1
\n# Complexity\nAppending, adding, multiplying have $$O(1)$$ time complexity,\n`getIndex` $$O(\\log(k))$$ where $k$ is the effective number of times `addAll` was called.\n\n- Space complexity: $$O(\\text{number of append+number of addAll calls})$$\n\n# Code\n```\nP = 1_000_000_007\n\ndef inv(x):\n n = P-2\n p = x\n y = 1\n while n>0:\n n, r = divmod(n, 2)\n if r:\n y = (y*p) % P\n p = (p*p) % P\n return y\n\ninverses = [0] + [inv(x) for x in range(1,101)]\n\nclass Bias:\n def __init__(self):\n self._from = [0]\n self._value = [0]\n\n def add(self, idx, inc):\n from_idx, value = self._from, self._value\n new_value = (self._value[-1]+inc) % P \n if idx==from_idx[-1]:\n value[-1] = new_value\n else:\n from_idx.append(idx)\n value.append(new_value)\n\n def __getitem__(self, idx):\n i0 = bisect.bisect(self._from, idx)-1\n if i0<len(self._value):\n return (self._value[-1] - self._value[i0])\n return 0\n\n def show(self, m):\n return f"{[(idx, (v*m)%P) for idx, v in zip(self._from, self._value)]}"\n \ndef show_changes(method):\n name = method.__name__\n def f(self, *args, **kwargs):\n print(f"before {name}(*{args},**{kwargs}): {self}")\n result = method(self, *args, **kwargs)\n print(f"after {name}: {self}")\n return result\n return f\n\nclass Fancy:\n\n def __init__(self):\n self.seq = []\n self.bias = Bias()\n self.m = 1\n self.minv = 1\n\n # @show_changes\n def append(self, val: int) -> None:\n self.seq.append((self.minv * val) % P)\n\n # @show_changes\n def addAll(self, inc: int) -> None:\n self.bias.add(len(self.seq), inc*self.minv)\n \n # @show_changes\n def multAll(self, m: int) -> None:\n self.m = (self.m * m) % P\n self.minv = (self.minv * inverses[m]) % P\n \n def getIndex(self, idx: int) -> int:\n if idx>=len(self.seq):\n return -1\n return (self.m*(self.seq[idx]+self.bias[idx])) % P\n\n def __repr__(self):\n return f"{[self.getIndex(i) for i in range(len(self.seq))]}\\nBias = {self.bias.show(self.m)}"\n\n# Your Fancy object will be instantiated and called as such:\n# obj = Fancy()\n# obj.append(val)\n# obj.addAll(inc)\n# obj.multAll(m)\n# param_4 = obj.getIndex(idx)\n```
0
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `val` to the end of the sequence. * `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. * `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. * `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`. **Example 1:** **Input** \[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\] \[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\] **Output** \[null, null, null, null, null, 10, null, null, null, 26, 34, 20\] **Explanation** Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: \[2\] fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\] fancy.append(7); // fancy sequence: \[5, 7\] fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\] fancy.append(10); // fancy sequence: \[13, 17, 10\] fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20 **Constraints:** * `1 <= val, inc, m <= 100` * `0 <= idx <= 105` * At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
Fast Python solution
fancy-sequence
0
1
\n# Complexity\nAppending, adding, multiplying have $$O(1)$$ time complexity,\n`getIndex` $$O(\\log(k))$$ where $k$ is the effective number of times `addAll` was called.\n\n- Space complexity: $$O(\\text{number of append+number of addAll calls})$$\n\n# Code\n```\nP = 1_000_000_007\n\ndef inv(x):\n n = P-2\n p = x\n y = 1\n while n>0:\n n, r = divmod(n, 2)\n if r:\n y = (y*p) % P\n p = (p*p) % P\n return y\n\ninverses = [0] + [inv(x) for x in range(1,101)]\n\nclass Bias:\n def __init__(self):\n self._from = [0]\n self._value = [0]\n\n def add(self, idx, inc):\n from_idx, value = self._from, self._value\n new_value = (self._value[-1]+inc) % P \n if idx==from_idx[-1]:\n value[-1] = new_value\n else:\n from_idx.append(idx)\n value.append(new_value)\n\n def __getitem__(self, idx):\n i0 = bisect.bisect(self._from, idx)-1\n if i0<len(self._value):\n return (self._value[-1] - self._value[i0])\n return 0\n\n def show(self, m):\n return f"{[(idx, (v*m)%P) for idx, v in zip(self._from, self._value)]}"\n \ndef show_changes(method):\n name = method.__name__\n def f(self, *args, **kwargs):\n print(f"before {name}(*{args},**{kwargs}): {self}")\n result = method(self, *args, **kwargs)\n print(f"after {name}: {self}")\n return result\n return f\n\nclass Fancy:\n\n def __init__(self):\n self.seq = []\n self.bias = Bias()\n self.m = 1\n self.minv = 1\n\n # @show_changes\n def append(self, val: int) -> None:\n self.seq.append((self.minv * val) % P)\n\n # @show_changes\n def addAll(self, inc: int) -> None:\n self.bias.add(len(self.seq), inc*self.minv)\n \n # @show_changes\n def multAll(self, m: int) -> None:\n self.m = (self.m * m) % P\n self.minv = (self.minv * inverses[m]) % P\n \n def getIndex(self, idx: int) -> int:\n if idx>=len(self.seq):\n return -1\n return (self.m*(self.seq[idx]+self.bias[idx])) % P\n\n def __repr__(self):\n return f"{[self.getIndex(i) for i in range(len(self.seq))]}\\nBias = {self.bias.show(self.m)}"\n\n# Your Fancy object will be instantiated and called as such:\n# obj = Fancy()\n# obj.append(val)\n# obj.addAll(inc)\n# obj.multAll(m)\n# param_4 = obj.getIndex(idx)\n```
0
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
got 100 on speed
fancy-sequence
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```\np = 10**9 + 7\ninv = [None] + [pow(m, -1, p) for m in range(1, 101)]\n\nclass Fancy:\n\n def __init__(self):\n self.x = []\n self.a = 1\n self.ainv = 1\n self.b = 0\n\n def append(self, val):\n self.x.append((val - self.b) * self.ainv)\n\n def addAll(self, inc):\n self.b += inc\n\n def multAll(self, m):\n self.a = self.a * m % p\n self.ainv = self.ainv * inv[m] % p\n self.b = self.b * m % p\n\n def getIndex(self, idx):\n if idx >= len(self.x):\n return -1\n return (self.a * self.x[idx] + self.b) % p\n```
0
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `val` to the end of the sequence. * `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. * `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. * `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`. **Example 1:** **Input** \[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\] \[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\] **Output** \[null, null, null, null, null, 10, null, null, null, 26, 34, 20\] **Explanation** Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: \[2\] fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\] fancy.append(7); // fancy sequence: \[5, 7\] fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\] fancy.append(10); // fancy sequence: \[13, 17, 10\] fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20 **Constraints:** * `1 <= val, inc, m <= 100` * `0 <= idx <= 105` * At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
got 100 on speed
fancy-sequence
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```\np = 10**9 + 7\ninv = [None] + [pow(m, -1, p) for m in range(1, 101)]\n\nclass Fancy:\n\n def __init__(self):\n self.x = []\n self.a = 1\n self.ainv = 1\n self.b = 0\n\n def append(self, val):\n self.x.append((val - self.b) * self.ainv)\n\n def addAll(self, inc):\n self.b += inc\n\n def multAll(self, m):\n self.a = self.a * m % p\n self.ainv = self.ainv * inv[m] % p\n self.b = self.b * m % p\n\n def getIndex(self, idx):\n if idx >= len(self.x):\n return -1\n return (self.a * self.x[idx] + self.b) % p\n```
0
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Ez
fancy-sequence
0
1
# Code\n```\nclass Fancy:\n def __init__(self):\n self.sequence = []\n self.add = 0\n self.multiply = 1\n self.MOD = 10**9 + 7\n\n def append(self, val):\n val = (val - self.add) % self.MOD\n val = (val * pow(self.multiply, self.MOD-2, self.MOD)) % self.MOD\n self.sequence.append(val)\n\n def addAll(self, inc):\n self.add = (self.add + inc) % self.MOD\n\n def multAll(self, m):\n self.add = (self.add * m) % self.MOD\n self.multiply = (self.multiply * m) % self.MOD\n\n def getIndex(self, idx):\n if idx >= len(self.sequence):\n return -1\n return (self.sequence[idx] * self.multiply + self.add) % self.MOD\n\n```
0
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `val` to the end of the sequence. * `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. * `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. * `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`. **Example 1:** **Input** \[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\] \[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\] **Output** \[null, null, null, null, null, 10, null, null, null, 26, 34, 20\] **Explanation** Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: \[2\] fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\] fancy.append(7); // fancy sequence: \[5, 7\] fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\] fancy.append(10); // fancy sequence: \[13, 17, 10\] fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20 **Constraints:** * `1 <= val, inc, m <= 100` * `0 <= idx <= 105` * At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
Ez
fancy-sequence
0
1
# Code\n```\nclass Fancy:\n def __init__(self):\n self.sequence = []\n self.add = 0\n self.multiply = 1\n self.MOD = 10**9 + 7\n\n def append(self, val):\n val = (val - self.add) % self.MOD\n val = (val * pow(self.multiply, self.MOD-2, self.MOD)) % self.MOD\n self.sequence.append(val)\n\n def addAll(self, inc):\n self.add = (self.add + inc) % self.MOD\n\n def multAll(self, m):\n self.add = (self.add * m) % self.MOD\n self.multiply = (self.multiply * m) % self.MOD\n\n def getIndex(self, idx):\n if idx >= len(self.sequence):\n return -1\n return (self.sequence[idx] * self.multiply + self.add) % self.MOD\n\n```
0
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Fancy a Memory-Efficient Python Solution that Crushes 99.15% of the Competition? Check This Out!
fancy-sequence
0
1
# TL;DR\n\nSo we\'ve got a problem here. We need to make an API that does fancy things with sequences, like appending, adding and multiplying values. I mean, it\'s not rocket science, but we need to do it fast and efficiently.\n\nHere\'s what we\'re gonna do. We\'ll create a class called \'Fancy\', and use some tricks to keep the memory usage low. We\'ll keep track of the sequence and the operations using some variables, and make sure to do all the calculations modulo 10^9+7 to avoid overflow.\n\nIn the end, we\'ll have a pretty slick implementation that can handle a ton of operations without breaking a sweat. And the best part? It\'s not gonna take up too much space on your machine. So there you have it, folks - fancy sequences, made easy!\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSure, here\'s an expanded version:\n\nIntuition\nThe problem asks us to implement a class that can perform a series of operations on a sequence of integers, and return the value at a given index. The operations we can perform are append, addAll, and multAll. We can think of this sequence as a mathematical function, where each operation modifies the function in a specific way. The append operation adds a new element to the end of the sequence, the addAll operation adds a constant value to all elements in the sequence, and the multAll operation multiplies all elements in the sequence by a constant value.\n\nTo solve this problem, we need to keep track of the current state of the sequence after each operation. One way to do this is to store the sequence as a list, and update the list after each operation. However, this approach would be inefficient for large sequences, because we would need to copy the entire list each time we perform an operation. Instead, we can store the sequence as a function, where each element is computed based on the current state of the function and the index. This approach allows us to update the function in constant time, and compute the value at any index in constant time as well.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo implement the Fancy class, we can use the following approach:\n\nInitialize an empty list to store the elements of the sequence, and initialize variables to store the current state of the sequence.\nImplement the append operation by adding the new element to the list, modified by the current state of the sequence.\nImplement the addAll operation by updating the add variable with the new constant value.\nImplement the multAll operation by updating the mul and add variables with the new constant value.\nImplement the getIndex operation by computing the value of the function at the given index, based on the current state of the sequence.\nThis approach allows us to update the function in constant time for each operation, and compute the value at any index in constant time as well. Additionally, the use of modular arithmetic ensures that the values remain within a reasonable range and reduces the chance of integer overflow.\n# Complexity\n\nThe time and space complexity of the Fancy class are as follows:\n\n- Time complexity:\nappend: O(1)\naddAll: O(1)\nmultAll: O(1)\ngetIndex: O(1)\nThe time complexity of each operation is constant, since we perform a fixed number of arithmetic operations and list operations in each case. Therefore, the total time complexity of the class is also constant, assuming that the range of possible values for the input parameters is limited.\n\n- Space complexity:\nThe space required for the list to store the elements of the sequence is O(n), where n is the number of elements in the sequence. However, this is limited to a maximum of 10^5 elements in this case.\nThe space required for the other variables (add, mul, inv, mod) is O(1), since they are fixed size.\nTherefore, the overall space complexity of the Fancy class is also O(1), assuming that the range of possible values for the input parameters is limited.\n\n\n\n# Code\n```\nclass Fancy:\n def __init__(self):\n self.x = []\n self.add = 0\n self.mul = 1\n self.mod = 10**9 + 7\n self.inv = [0, 1]\n for i in range(2, 101):\n self.inv.append((self.mod - self.mod//i) * self.inv[self.mod%i] % self.mod)\n\n def append(self, val: int) -> None:\n self.x.append(((val - self.add) * pow(self.mul, self.mod-2, self.mod)) % self.mod)\n\n def addAll(self, inc: int) -> None:\n self.add = (self.add + inc) % self.mod\n\n def multAll(self, m: int) -> None:\n self.mul = (self.mul * m) % self.mod\n self.add = (self.add * m) % self.mod\n\n def getIndex(self, idx: int) -> int:\n if idx >= len(self.x):\n return -1\n return (self.x[idx] * self.mul + self.add) % self.mod\n\n# Your Fancy object will be instantiated and called as such:\n# obj = Fancy()\n# obj.append(val)\n# obj.addAll(inc)\n# obj.multAll(m)\n# param_4 = obj.getIndex(idx)\n```
0
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `val` to the end of the sequence. * `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. * `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. * `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`. **Example 1:** **Input** \[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\] \[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\] **Output** \[null, null, null, null, null, 10, null, null, null, 26, 34, 20\] **Explanation** Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: \[2\] fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\] fancy.append(7); // fancy sequence: \[5, 7\] fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\] fancy.append(10); // fancy sequence: \[13, 17, 10\] fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20 **Constraints:** * `1 <= val, inc, m <= 100` * `0 <= idx <= 105` * At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
Fancy a Memory-Efficient Python Solution that Crushes 99.15% of the Competition? Check This Out!
fancy-sequence
0
1
# TL;DR\n\nSo we\'ve got a problem here. We need to make an API that does fancy things with sequences, like appending, adding and multiplying values. I mean, it\'s not rocket science, but we need to do it fast and efficiently.\n\nHere\'s what we\'re gonna do. We\'ll create a class called \'Fancy\', and use some tricks to keep the memory usage low. We\'ll keep track of the sequence and the operations using some variables, and make sure to do all the calculations modulo 10^9+7 to avoid overflow.\n\nIn the end, we\'ll have a pretty slick implementation that can handle a ton of operations without breaking a sweat. And the best part? It\'s not gonna take up too much space on your machine. So there you have it, folks - fancy sequences, made easy!\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSure, here\'s an expanded version:\n\nIntuition\nThe problem asks us to implement a class that can perform a series of operations on a sequence of integers, and return the value at a given index. The operations we can perform are append, addAll, and multAll. We can think of this sequence as a mathematical function, where each operation modifies the function in a specific way. The append operation adds a new element to the end of the sequence, the addAll operation adds a constant value to all elements in the sequence, and the multAll operation multiplies all elements in the sequence by a constant value.\n\nTo solve this problem, we need to keep track of the current state of the sequence after each operation. One way to do this is to store the sequence as a list, and update the list after each operation. However, this approach would be inefficient for large sequences, because we would need to copy the entire list each time we perform an operation. Instead, we can store the sequence as a function, where each element is computed based on the current state of the function and the index. This approach allows us to update the function in constant time, and compute the value at any index in constant time as well.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo implement the Fancy class, we can use the following approach:\n\nInitialize an empty list to store the elements of the sequence, and initialize variables to store the current state of the sequence.\nImplement the append operation by adding the new element to the list, modified by the current state of the sequence.\nImplement the addAll operation by updating the add variable with the new constant value.\nImplement the multAll operation by updating the mul and add variables with the new constant value.\nImplement the getIndex operation by computing the value of the function at the given index, based on the current state of the sequence.\nThis approach allows us to update the function in constant time for each operation, and compute the value at any index in constant time as well. Additionally, the use of modular arithmetic ensures that the values remain within a reasonable range and reduces the chance of integer overflow.\n# Complexity\n\nThe time and space complexity of the Fancy class are as follows:\n\n- Time complexity:\nappend: O(1)\naddAll: O(1)\nmultAll: O(1)\ngetIndex: O(1)\nThe time complexity of each operation is constant, since we perform a fixed number of arithmetic operations and list operations in each case. Therefore, the total time complexity of the class is also constant, assuming that the range of possible values for the input parameters is limited.\n\n- Space complexity:\nThe space required for the list to store the elements of the sequence is O(n), where n is the number of elements in the sequence. However, this is limited to a maximum of 10^5 elements in this case.\nThe space required for the other variables (add, mul, inv, mod) is O(1), since they are fixed size.\nTherefore, the overall space complexity of the Fancy class is also O(1), assuming that the range of possible values for the input parameters is limited.\n\n\n\n# Code\n```\nclass Fancy:\n def __init__(self):\n self.x = []\n self.add = 0\n self.mul = 1\n self.mod = 10**9 + 7\n self.inv = [0, 1]\n for i in range(2, 101):\n self.inv.append((self.mod - self.mod//i) * self.inv[self.mod%i] % self.mod)\n\n def append(self, val: int) -> None:\n self.x.append(((val - self.add) * pow(self.mul, self.mod-2, self.mod)) % self.mod)\n\n def addAll(self, inc: int) -> None:\n self.add = (self.add + inc) % self.mod\n\n def multAll(self, m: int) -> None:\n self.mul = (self.mul * m) % self.mod\n self.add = (self.add * m) % self.mod\n\n def getIndex(self, idx: int) -> int:\n if idx >= len(self.x):\n return -1\n return (self.x[idx] * self.mul + self.add) % self.mod\n\n# Your Fancy object will be instantiated and called as such:\n# obj = Fancy()\n# obj.append(val)\n# obj.addAll(inc)\n# obj.multAll(m)\n# param_4 = obj.getIndex(idx)\n```
0
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Simple Python solution
fancy-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWithout the modulus calculation, each sequence of operations results in a linear operation, x * m + b. Now we only need to manage the modulus calculation.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe calculate cumulative multiplier, and when it\'s larger then 10 ** 9 + 7, we record the multiplier then restart from 1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nDepends on modulus, faster than O(n^2).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Fancy:\n\n def __init__(self):\n self.deno = 10 ** 9 + 7\n self.data = []\n self.notes = []\n self.muls = []\n self.mul_ids = []\n self.mul_tots = []\n self.note = 1\n self.mul = 1\n\n def append(self, val: int) -> None:\n self.data.append(val)\n self.notes.append(self.note)\n self.muls.append(self.mul)\n self.mul_ids.append(len(self.mul_tots))\n\n def addAll(self, inc: int) -> None:\n if len(self.data) == 0:\n return\n self.note += inc\n self.note %= self.deno\n\n def multAll(self, m: int) -> None:\n if len(self.data) == 0:\n return\n self.note *= m\n self.note %= self.deno \n self.mul *= m\n if self.mul > self.deno:\n self.mul_tots.append(self.mul)\n if len(self.mul_tots) > self.mul_ids[-1] + 2:\n comb = self.mul_tots.pop()\n self.mul_tots[-1] = (self.mul_tots[-1] * comb) % self.deno\n self.mul = 1\n\n def getIndex(self, idx: int) -> int:\n if idx >= len(self.data):\n return -1\n mul_id = self.mul_ids[idx]\n if mul_id < len(self.mul_tots):\n mul = self.mul_tots[mul_id] // self.muls[idx]\n for mul_tot in self.mul_tots[mul_id+1:]:\n mul *= mul_tot\n mul %= self.deno\n mul *= self.mul\n else:\n mul = self.mul // self.muls[idx]\n \n b = self.note - (self.notes[idx] * mul)\n rst = (self.data[idx] * mul + b) % self.deno\n return rst\n\n```
0
Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations. Implement the `Fancy` class: * `Fancy()` Initializes the object with an empty sequence. * `void append(val)` Appends an integer `val` to the end of the sequence. * `void addAll(inc)` Increments all existing values in the sequence by an integer `inc`. * `void multAll(m)` Multiplies all existing values in the sequence by an integer `m`. * `int getIndex(idx)` Gets the current value at index `idx` (0-indexed) of the sequence **modulo** `109 + 7`. If the index is greater or equal than the length of the sequence, return `-1`. **Example 1:** **Input** \[ "Fancy ", "append ", "addAll ", "append ", "multAll ", "getIndex ", "addAll ", "append ", "multAll ", "getIndex ", "getIndex ", "getIndex "\] \[\[\], \[2\], \[3\], \[7\], \[2\], \[0\], \[3\], \[10\], \[2\], \[0\], \[1\], \[2\]\] **Output** \[null, null, null, null, null, 10, null, null, null, 26, 34, 20\] **Explanation** Fancy fancy = new Fancy(); fancy.append(2); // fancy sequence: \[2\] fancy.addAll(3); // fancy sequence: \[2+3\] -> \[5\] fancy.append(7); // fancy sequence: \[5, 7\] fancy.multAll(2); // fancy sequence: \[5\*2, 7\*2\] -> \[10, 14\] fancy.getIndex(0); // return 10 fancy.addAll(3); // fancy sequence: \[10+3, 14+3\] -> \[13, 17\] fancy.append(10); // fancy sequence: \[13, 17, 10\] fancy.multAll(2); // fancy sequence: \[13\*2, 17\*2, 10\*2\] -> \[26, 34, 20\] fancy.getIndex(0); // return 26 fancy.getIndex(1); // return 34 fancy.getIndex(2); // return 20 **Constraints:** * `1 <= val, inc, m <= 100` * `0 <= idx <= 105` * At most `105` calls total will be made to `append`, `addAll`, `multAll`, and `getIndex`.
Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the current point and the point on top of the queue and maximize the answer.
Simple Python solution
fancy-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWithout the modulus calculation, each sequence of operations results in a linear operation, x * m + b. Now we only need to manage the modulus calculation.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe calculate cumulative multiplier, and when it\'s larger then 10 ** 9 + 7, we record the multiplier then restart from 1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nDepends on modulus, faster than O(n^2).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Fancy:\n\n def __init__(self):\n self.deno = 10 ** 9 + 7\n self.data = []\n self.notes = []\n self.muls = []\n self.mul_ids = []\n self.mul_tots = []\n self.note = 1\n self.mul = 1\n\n def append(self, val: int) -> None:\n self.data.append(val)\n self.notes.append(self.note)\n self.muls.append(self.mul)\n self.mul_ids.append(len(self.mul_tots))\n\n def addAll(self, inc: int) -> None:\n if len(self.data) == 0:\n return\n self.note += inc\n self.note %= self.deno\n\n def multAll(self, m: int) -> None:\n if len(self.data) == 0:\n return\n self.note *= m\n self.note %= self.deno \n self.mul *= m\n if self.mul > self.deno:\n self.mul_tots.append(self.mul)\n if len(self.mul_tots) > self.mul_ids[-1] + 2:\n comb = self.mul_tots.pop()\n self.mul_tots[-1] = (self.mul_tots[-1] * comb) % self.deno\n self.mul = 1\n\n def getIndex(self, idx: int) -> int:\n if idx >= len(self.data):\n return -1\n mul_id = self.mul_ids[idx]\n if mul_id < len(self.mul_tots):\n mul = self.mul_tots[mul_id] // self.muls[idx]\n for mul_tot in self.mul_tots[mul_id+1:]:\n mul *= mul_tot\n mul %= self.deno\n mul *= self.mul\n else:\n mul = self.mul // self.muls[idx]\n \n b = self.note - (self.notes[idx] * mul)\n rst = (self.data[idx] * mul + b) % self.deno\n return rst\n\n```
0
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Solution for beginners
largest-substring-between-two-equal-characters
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 maxLengthBetweenEqualCharacters(self, s: str) -> int:\n a=[]\n for i in range(0,len(s)-1) :\n b=0\n for j in range(i+1,len(s)) :\n if s[j]==s[i] :\n b=j-i-1\n a.append(b)\n return max(a) if len(a)>0 else -1\n```
1
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Solution for beginners
largest-substring-between-two-equal-characters
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 maxLengthBetweenEqualCharacters(self, s: str) -> int:\n a=[]\n for i in range(0,len(s)-1) :\n b=0\n for j in range(i+1,len(s)) :\n if s[j]==s[i] :\n b=j-i-1\n a.append(b)\n return max(a) if len(a)>0 else -1\n```
1
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
[Python3] via dictionary
largest-substring-between-two-equal-characters
0
1
Memoize the first occurrence of a character. \n```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = -1\n seen = {}\n for i, c in enumerate(s): \n if c in seen: ans = max(ans, i - seen[c] - 1)\n seen.setdefault(c, i)\n return ans \n```
13
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
[Python3] via dictionary
largest-substring-between-two-equal-characters
0
1
Memoize the first occurrence of a character. \n```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = -1\n seen = {}\n for i, c in enumerate(s): \n if c in seen: ans = max(ans, i - seen[c] - 1)\n seen.setdefault(c, i)\n return ans \n```
13
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
#1624 Python 3 fast functional one-liner, explained
largest-substring-between-two-equal-characters
0
1
For each character `ch` that occurs in `s` one or more times the length of the longest contained substring equals to `s.rfind(ch) - s.find(ch) -1`. If a character occurs only once at position `x` this expression equals to ` x - x - 1 = -1`. The solution is largest of all longest contained substring lengths for the elements of `set(s)`:\n```\nclass SolutionI:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n return max(s.rfind(ch) - s.find(ch) - 1 for ch in set(s))\n```\n\nTime complexity: **O(n)**; Space complexity: **O(1)**
17
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
#1624 Python 3 fast functional one-liner, explained
largest-substring-between-two-equal-characters
0
1
For each character `ch` that occurs in `s` one or more times the length of the longest contained substring equals to `s.rfind(ch) - s.find(ch) -1`. If a character occurs only once at position `x` this expression equals to ` x - x - 1 = -1`. The solution is largest of all longest contained substring lengths for the elements of `set(s)`:\n```\nclass SolutionI:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n return max(s.rfind(ch) - s.find(ch) - 1 for ch in set(s))\n```\n\nTime complexity: **O(n)**; Space complexity: **O(1)**
17
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
[Python3] Simple And Readable Solution
largest-substring-between-two-equal-characters
0
1
```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = [-1]\n \n for i in set(s):\n if(s.count(i) >= 2):\n ans.append(s.rindex(i) - s.index(i) - 1 )\n \n return max(ans)\n```
8
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
[Python3] Simple And Readable Solution
largest-substring-between-two-equal-characters
0
1
```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = [-1]\n \n for i in set(s):\n if(s.count(i) >= 2):\n ans.append(s.rindex(i) - s.index(i) - 1 )\n \n return max(ans)\n```
8
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
[Python] Solution with explanation - Beats 94.49%
largest-substring-between-two-equal-characters
0
1
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n # setup to keep necessary vars in memory\n set_s, len_s = set(s), len(s)\n\n # checking if there is no such substring\n if len(set_s) == len_s:\n return -1\n\n # final check for largest substing between two equal characters\n le = 0\n for i in set_s:\n if s.count(i) > 1:\n\n # checking a lenght of a substring\n cou = len_s - s[::-1].index(i) - s.index(i) - 2\n if cou > le:\n le = cou\n \n # yay we made it\n return le\n```
1
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
[Python] Solution with explanation - Beats 94.49%
largest-substring-between-two-equal-characters
0
1
\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n # setup to keep necessary vars in memory\n set_s, len_s = set(s), len(s)\n\n # checking if there is no such substring\n if len(set_s) == len_s:\n return -1\n\n # final check for largest substing between two equal characters\n le = 0\n for i in set_s:\n if s.count(i) > 1:\n\n # checking a lenght of a substring\n cou = len_s - s[::-1].index(i) - s.index(i) - 2\n if cou > le:\n le = cou\n \n # yay we made it\n return le\n```
1
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
Python easy
largest-substring-between-two-equal-characters
0
1
```\nclass Solution(object):\n def maxLengthBetweenEqualCharacters(self, s):\n lastSeen = dict()\n maxDist = -1\n for index, char in enumerate(s):\n if char not in lastSeen:\n lastSeen[char] = index\n else:\n maxDist = max(index - lastSeen[char], maxDist)\n \n return maxDist - 1 if maxDist > -1 else -1\n \n```
6
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Python easy
largest-substring-between-two-equal-characters
0
1
```\nclass Solution(object):\n def maxLengthBetweenEqualCharacters(self, s):\n lastSeen = dict()\n maxDist = -1\n for index, char in enumerate(s):\n if char not in lastSeen:\n lastSeen[char] = index\n else:\n maxDist = max(index - lastSeen[char], maxDist)\n \n return maxDist - 1 if maxDist > -1 else -1\n \n```
6
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
Python3 one pass O(n) solution - Large Substring Between Two Equal Characters
largest-substring-between-two-equal-characters
0
1
```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n last, ans = {}, -1 \n for i, c in enumerate(s):\n if c not in last:\n last[c] = i\n else:\n ans = max(ans, i - last[c] - 1)\n return ans \n```
9
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Python3 one pass O(n) solution - Large Substring Between Two Equal Characters
largest-substring-between-two-equal-characters
0
1
```\nclass Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n last, ans = {}, -1 \n for i, c in enumerate(s):\n if c not in last:\n last[c] = i\n else:\n ans = max(ans, i - last[c] - 1)\n return ans \n```
9
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
One of the fastest solutions on Python 3
largest-substring-between-two-equal-characters
0
1
\n# Code\n```\nclass Solution:\n\tdef maxLengthBetweenEqualCharacters(self, s: str) -> int:\n\t\tcounter = -1\n\t\tchar_indices = {}\n\t\tfor i, char in enumerate(s):\n\t\t\tif char in char_indices:\n\t\t\t\tcounter = max(counter, i - char_indices[char]-1)\n\t\t\telse:\n\t\t\t\tchar_indices[char] = i\n \n\t\treturn counter\n```
0
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
One of the fastest solutions on Python 3
largest-substring-between-two-equal-characters
0
1
\n# Code\n```\nclass Solution:\n\tdef maxLengthBetweenEqualCharacters(self, s: str) -> int:\n\t\tcounter = -1\n\t\tchar_indices = {}\n\t\tfor i, char in enumerate(s):\n\t\t\tif char in char_indices:\n\t\t\t\tcounter = max(counter, i - char_indices[char]-1)\n\t\t\telse:\n\t\t\t\tchar_indices[char] = i\n \n\t\treturn counter\n```
0
You are given an integer array `nums`. You must perform **exactly one** operation where you can **replace** one element `nums[i]` with `nums[i] * nums[i]`. Return _the **maximum** possible subarray sum after **exactly one** operation_. The subarray must be non-empty. **Example 1:** **Input:** nums = \[2,-1,-4,-3\] **Output:** 17 **Explanation:** You can perform the operation on index 2 (0-indexed) to make nums = \[2,-1,**16**,-3\]. Now, the maximum subarray sum is 2 + -1 + 16 = 17. **Example 2:** **Input:** nums = \[1,-1,1,1,-1,-1,1\] **Output:** 4 **Explanation:** You can perform the operation on index 1 (0-indexed) to make nums = \[1,**1**,1,1,-1,-1,1\]. Now, the maximum subarray sum is 1 + 1 + 1 + 1 = 4. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
Try saving the first and last position of each character Try finding every pair of indexes with equal characters
Python 3 || 12 lines, recursion, dfs || T/M: 80% / 12%
lexicographically-smallest-string-after-applying-operations
0
1
\nThe plan here is to determine the set of all possible states of`s`under the two transformations, then return the lexicographic minimum of that set.\n```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n\n def dfs(s: str) -> str:\n\n if s in seen: return\n\n seen.add(s)\n res, odd =\'\', True\n\n for ch in s:\n odd^= True\n res+= d[ch] if odd else ch\n \n dfs(res)\n dfs(s[b: ] + s[ :b])\n\n\n d, seen = {ch:str((int(ch) + a) % 10\n ) for ch in digits}, set()\n\n dfs(s)\n\n return min(seen)\n```\n[https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/submissions/936536316/](http://)\n\nPython 3 || 12 lines, dfs || T/M: 80% / 12%\n\nI definitely could be wrong about this, but I think that time and space complexities are both *O*(10^*N*), where *N* = `len(s)`. Both worst-case, which is`gcd(10, a) == 1`and`gcd(len(s), b) == 1`\n
3
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
[Python3] dfs
lexicographically-smallest-string-after-applying-operations
0
1
Traverse the whole graph via the two operations, and return the minimum string. \n\n```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n op1 = lambda s: "".join(str((int(c)+a)%10) if i&1 else c for i, c in enumerate(s))\n op2 = lambda s: s[-b:] + s[:-b]\n \n seen = set()\n stack = [s]\n while stack: \n s = stack.pop()\n seen.add(s)\n if (ss := op1(s)) not in seen: stack.append(ss)\n if (ss := op2(s)) not in seen: stack.append(ss)\n return min(seen)\n```
9
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
Short Python BFS and DFS solutions
lexicographically-smallest-string-after-applying-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe brute force solution works here.\n\n# DFS Code\n```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n def dfs(s):\n if s in seen: return\n seen.add(s)\n dfs(\'\'.join(s[i] if i % 2 == 0 else str((int(s[i]) + a) % 10) for i in range(len(s))))\n dfs(s[-b:] + s[:-b])\n seen = set()\n dfs(s)\n return min(seen)\n```\n\n# BFS Code\n```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n q, seen = [s], set()\n while q:\n s = q.pop()\n if s in seen: continue\n seen.add(s)\n t = \'\'.join(s[i] if i % 2 == 0 else str((int(s[i]) + a) % 10) for i in range(len(s)))\n u = s[-b:] + s[:-b]\n q.extend([t, u])\n return min(seen)\n```
0
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
🔴🟢Python3🤔1625. Lexicographically Smallest String 🥑Recursion🍱
lexicographically-smallest-string-after-applying-operations
0
1
![image.png](https://assets.leetcode.com/users/images/bee9b3c3-9935-41ec-b4ac-bc0026d2799e_1696760405.154087.png)\n\n# Intuition\nlist stack recursion\n\n# Approach\nlist stack recursion\n\n# Complexity\n- Time complexity:\n$$O(2^n)$$\n\n- Space complexity:\n$$O(2^n)$$\n\n# Code\n```\nclass Solution:\n\tdef findLexSmallestString(self, s: str, a: int, b: int) -> str:\n\t\t\'\'\'list stack recursion\'\'\'\n\t\t# Define Two Functions\n\t\t# Add Operation\n\t\tdef add(string):\n\t\t\tret = []\n\t\t\tfor i, c in enumerate(string):\n\t\t\t\tif i % 2:\n\t\t\t\t\tret.append(str((int(c) + a) % 10))\n\t\t\t\telse:\n\t\t\t\t\tret.append(c)\n\t\t\treturn "".join(ret)\n\n\t\t# Rotate Operation using nagetive slice\n\t\trotate = lambda string: string[-b:] + string[:-b]\n\n\t\tres = set()\n\t\tstack = [s]\n\t\twhile stack: \n\t\t\tcur = stack.pop() # current string\n\t\t\tres.add(cur) # add to res set\n\t\t\t# add and rotate separately\n\t\t\tfor val in [add(cur), rotate(cur)]:\n\t\t\t\tif val not in res:\n\t\t\t\t\tstack.append(val)\n\n\t\treturn min(res)\n```
0
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
Python simple DFS
lexicographically-smallest-string-after-applying-operations
0
1
Since size of s and the variations that can happen on s are both limited, we can do a DFS on each string and keep track of the minimum\n# Code\n```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n self.vis = set()\n self.min = s\n self.a = a\n self.b = b\n self.dfs(s)\n return self.min\n\n \n def dfs(self, s):\n if not(s in self.vis):\n self.vis.add(s)\n if int(s)< int(self.min):\n self.min = s\n sa = \'\'\n for i in range(len(s)):\n if i%2==0:\n sa += s[i]\n else:\n sa += str( (int(s[i]) + self.a)%10)\n sb = s[-self.b:] + s[:-self.b]\n self.dfs(sa)\n self.dfs(sb)\n```
0
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
Python - simple brute force solution
lexicographically-smallest-string-after-applying-operations
0
1
# Intuition\nAdditions can make at most 10 different states per odd positions, this is 10 * N different states. Rotations can make at most N different states, those 2 mutiplied get 10$$N^2$$ which is asymptotically O($$N^2$$). Constraint N <= 100 allows us to brute force through all possible states and get best one as solution.\n\n\n# Approach\nGenerate all possible solutions by applying both operations on previously generated states, use hash map to avoid repeating work and getting into infinite loop.\n\n# Complexity\n- Time complexity:\nO($$N^2$$)\n\n- Space complexity:\nO($$N^2$$)\n\n# Code\n```\nfrom collections import deque\n\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str: \n seen, qu = set(), deque([s])\n while qu:\n ss = qu.popleft()\n if ss not in seen:\n seen.add(ss)\n qu.append(\'\'.join([str((int(c) + a) % 10) if i % 2 else c for i, c in enumerate(ss)]))\n qu.append(ss[-b:] + ss[:-b])\n return min(seen)\n\n```
0
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
[Python 3] BFS
lexicographically-smallest-string-after-applying-operations
0
1
```\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n q = deque( [s] )\n res = set( [s] )\n \n while q:\n cur = q.popleft()\n \n t1 = list(cur)\n for i in range(len(t1)):\n if i & 1:\n t1[i] = str( (int(t1[i]) + a) % 10 )\n \n t1 = \'\'.join(t1)\n if t1 not in res:\n q.append(t1)\n res.add(t1)\n \n t2 = cur[b : ] + cur[ : b]\n if t2 not in res:\n q.append(t2)\n res.add(t2)\n \n return min(res)\n```
0
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
Binary Indexed Tree Solution for Best Team With No Conflicts
best-team-with-no-conflicts
0
1
# Intuition\nMy first thoughts on how to solve this problem is to find a way to pick the players with the highest scores while ensuring that no younger player has a higher score than an older player. To do this, one could sort the players by their scores and ages, and then use dynamic programming to keep track of the maximum possible score of a team that includes players of all ages up to a certain age. To keep track of this information efficiently, a data structure such as a Binary Indexed Tree (BIT) can be used to retrieve and update the maximum possible score for a team of players with ages up to a certain age in logarithmic time.\n\n# Approach\n1. Create a list of tuples, where each tuple contains the age and score of a player.\n2. Sort the list of tuples based on the score of each player and their age in the case of a tie.\n3. Create a binary indexed tree (BIT) to store the maximum scores for each age.\n4. Loop through the sorted list of tuples and for each player:\n - a. Use the BIT to query the maximum score possible for players with ages less than or equal to the current player\'s age\n - b. Update the maximum score for the current player\'s age in the BIT to be the maximum of the current score and the maximum score found in step 4a plus the current player\'s score.\n5. Return the maximum score found in step 4b.\n\n# Complexity\n**Time complexity:**\nThe time complexity of the solution is $$O(nlogn)$$. This is because the first step of the solution is to sort the list of age-score pairs based on score and age, which takes $$O(nlogn)$$ time. Then for each pair, the solution performs a `query` and an `update` operation on the Binary Indexed Tree (BIT), both of which take $$O(logA)$$ time, where $$A$$ is the highest age. Since the highest age can be at most $$1000$$, the $$logA$$ term can be considered a constant. Therefore, the total time complexity of the solution is $$O(nlogn + nlogA)$$, which can be simplified to $$O(nlogn)$$.\n\n**Space complexity:**\nThe space complexity of the solution is $$O(n)$$, where `n` is the number of players in the team. This is because the space used by the Binary Indexed Tree (BIT) data structure is proportional to the size of the input, which is the number of players in the team. The BIT uses a `sums` array to store its values, and the size of the array is equal to the maximum age of a player in the team plus 1. Since the maximum age of a player is 1000, the size of the `sums` array is 1001, which is proportional to the size of the input, hence the space complexity is $$O(n)$$.\n\n# Code\n```\nfrom typing import List\n\nclass BinaryIndexedTree:\n def __init__(self, n):\n self.n = n\n self.sums = [0] * (n + 1)\n\n def update(self, i, delta):\n while i <= self.n:\n self.sums[i] = max(self.sums[i], delta)\n i += i & -i\n\n def query(self, i):\n ans = 0\n while i > 0:\n ans = max(ans, self.sums[i])\n i -= i & -i\n return ans\n\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n ageScorePair = [(a, s) for a, s in zip(ages, scores)]\n ageScorePair.sort(key=lambda x: (x[1], x[0]))\n highestAge = max(ages)\n BIT = BinaryIndexedTree(highestAge + 1)\n ans = 0\n for i in range(len(ageScorePair)):\n age, score = ageScorePair[i]\n j = BIT.query(age)\n ans = max(ans, j + score)\n BIT.update(age, j + score)\n return ans\n\n```
2
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_. **Example 1:** **Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\] **Output:** 34 **Explanation:** You can choose all the players. **Example 2:** **Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\] **Output:** 16 **Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. **Example 3:** **Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\] **Output:** 6 **Explanation:** It is best to choose the first 3 players. **Constraints:** * `1 <= scores.length, ages.length <= 1000` * `scores.length == ages.length` * `1 <= scores[i] <= 106` * `1 <= ages[i] <= 1000`
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
Binary Indexed Tree Solution for Best Team With No Conflicts
best-team-with-no-conflicts
0
1
# Intuition\nMy first thoughts on how to solve this problem is to find a way to pick the players with the highest scores while ensuring that no younger player has a higher score than an older player. To do this, one could sort the players by their scores and ages, and then use dynamic programming to keep track of the maximum possible score of a team that includes players of all ages up to a certain age. To keep track of this information efficiently, a data structure such as a Binary Indexed Tree (BIT) can be used to retrieve and update the maximum possible score for a team of players with ages up to a certain age in logarithmic time.\n\n# Approach\n1. Create a list of tuples, where each tuple contains the age and score of a player.\n2. Sort the list of tuples based on the score of each player and their age in the case of a tie.\n3. Create a binary indexed tree (BIT) to store the maximum scores for each age.\n4. Loop through the sorted list of tuples and for each player:\n - a. Use the BIT to query the maximum score possible for players with ages less than or equal to the current player\'s age\n - b. Update the maximum score for the current player\'s age in the BIT to be the maximum of the current score and the maximum score found in step 4a plus the current player\'s score.\n5. Return the maximum score found in step 4b.\n\n# Complexity\n**Time complexity:**\nThe time complexity of the solution is $$O(nlogn)$$. This is because the first step of the solution is to sort the list of age-score pairs based on score and age, which takes $$O(nlogn)$$ time. Then for each pair, the solution performs a `query` and an `update` operation on the Binary Indexed Tree (BIT), both of which take $$O(logA)$$ time, where $$A$$ is the highest age. Since the highest age can be at most $$1000$$, the $$logA$$ term can be considered a constant. Therefore, the total time complexity of the solution is $$O(nlogn + nlogA)$$, which can be simplified to $$O(nlogn)$$.\n\n**Space complexity:**\nThe space complexity of the solution is $$O(n)$$, where `n` is the number of players in the team. This is because the space used by the Binary Indexed Tree (BIT) data structure is proportional to the size of the input, which is the number of players in the team. The BIT uses a `sums` array to store its values, and the size of the array is equal to the maximum age of a player in the team plus 1. Since the maximum age of a player is 1000, the size of the `sums` array is 1001, which is proportional to the size of the input, hence the space complexity is $$O(n)$$.\n\n# Code\n```\nfrom typing import List\n\nclass BinaryIndexedTree:\n def __init__(self, n):\n self.n = n\n self.sums = [0] * (n + 1)\n\n def update(self, i, delta):\n while i <= self.n:\n self.sums[i] = max(self.sums[i], delta)\n i += i & -i\n\n def query(self, i):\n ans = 0\n while i > 0:\n ans = max(ans, self.sums[i])\n i -= i & -i\n return ans\n\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n ageScorePair = [(a, s) for a, s in zip(ages, scores)]\n ageScorePair.sort(key=lambda x: (x[1], x[0]))\n highestAge = max(ages)\n BIT = BinaryIndexedTree(highestAge + 1)\n ans = 0\n for i in range(len(ageScorePair)):\n age, score = ageScorePair[i]\n j = BIT.query(age)\n ans = max(ans, j + score)\n BIT.update(age, j + score)\n return ans\n\n```
2
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
[Python] 194ms beating 100% | O(n*logn) | Binary Indexed Tree
best-team-with-no-conflicts
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is the same as Longest Increse Sequence. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe could use similar method to maintain the sequence and search for the age (as age is smaller than score, have higher efficency). And use Binary Indexed Tree, it will be better than O(n*logn)\n\n# Complexity\n- Time complexity: Better than O(n*logn)\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 bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n n = len(scores)\n maxAge = max(ages)\n dp = [0]*(maxAge+1)\n infos = list(zip(scores, ages))\n infos.sort()\n\n for score, age in infos:\n x = age & (age-1)\n while x:\n dp[age] = max(dp[x], dp[age])\n x &= x-1\n\n dp[age] += score\n\n x = age + (age&(-age))\n while x <= maxAge:\n dp[x] = max(dp[x], dp[age])\n x += x&(-x)\n\n return max(dp)\n\n```
2
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_. **Example 1:** **Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\] **Output:** 34 **Explanation:** You can choose all the players. **Example 2:** **Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\] **Output:** 16 **Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. **Example 3:** **Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\] **Output:** 6 **Explanation:** It is best to choose the first 3 players. **Constraints:** * `1 <= scores.length, ages.length <= 1000` * `scores.length == ages.length` * `1 <= scores[i] <= 106` * `1 <= ages[i] <= 1000`
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
[Python] 194ms beating 100% | O(n*logn) | Binary Indexed Tree
best-team-with-no-conflicts
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is the same as Longest Increse Sequence. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe could use similar method to maintain the sequence and search for the age (as age is smaller than score, have higher efficency). And use Binary Indexed Tree, it will be better than O(n*logn)\n\n# Complexity\n- Time complexity: Better than O(n*logn)\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 bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n n = len(scores)\n maxAge = max(ages)\n dp = [0]*(maxAge+1)\n infos = list(zip(scores, ages))\n infos.sort()\n\n for score, age in infos:\n x = age & (age-1)\n while x:\n dp[age] = max(dp[x], dp[age])\n x &= x-1\n\n dp[age] += score\n\n x = age + (age&(-age))\n while x <= maxAge:\n dp[x] = max(dp[x], dp[age])\n x += x&(-x)\n\n return max(dp)\n\n```
2
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Python || DP Cache Solution || Beats 80 %
best-team-with-no-conflicts
0
1
# Approach\nSort the scores and age. After that start a loop and check if the age is so far maximum. If it is then initialise dp[i] as max of dp[i] or maxscore so far + dp[j].\nRefer to my [LIS solution](https://leetcode.com/problems/longest-increasing-subsequence/solutions/3122086/python-easy-dp-beats-90/) for better understanding.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n\n pairs = [[scores[i],ages[i]] for i in range(len(scores))]\n\n pairs.sort()\n\n dp = [pairs[i][0] for i in range(len(pairs))]\n\n for i in range(len(pairs)):\n mscore , mage = pairs[i]\n for j in range(0,i):\n score,age = pairs[j]\n if mage>=age:\n dp[i] = max(mscore+dp[j],dp[i])\n\n\n return max(dp) \n\n```
1
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_. **Example 1:** **Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\] **Output:** 34 **Explanation:** You can choose all the players. **Example 2:** **Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\] **Output:** 16 **Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. **Example 3:** **Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\] **Output:** 6 **Explanation:** It is best to choose the first 3 players. **Constraints:** * `1 <= scores.length, ages.length <= 1000` * `scores.length == ages.length` * `1 <= scores[i] <= 106` * `1 <= ages[i] <= 1000`
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
Python || DP Cache Solution || Beats 80 %
best-team-with-no-conflicts
0
1
# Approach\nSort the scores and age. After that start a loop and check if the age is so far maximum. If it is then initialise dp[i] as max of dp[i] or maxscore so far + dp[j].\nRefer to my [LIS solution](https://leetcode.com/problems/longest-increasing-subsequence/solutions/3122086/python-easy-dp-beats-90/) for better understanding.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n\n pairs = [[scores[i],ages[i]] for i in range(len(scores))]\n\n pairs.sort()\n\n dp = [pairs[i][0] for i in range(len(pairs))]\n\n for i in range(len(pairs)):\n mscore , mage = pairs[i]\n for j in range(0,i):\n score,age = pairs[j]\n if mage>=age:\n dp[i] = max(mscore+dp[j],dp[i])\n\n\n return max(dp) \n\n```
1
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Simple python solution
best-team-with-no-conflicts
0
1
# Intuition\nMake zip of the two lists and sort them according to age.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n team = list(zip(ages,scores))\n team.sort()\n n = len(ages)\n dp = [0]*n\n\n for i in range(n):\n curr = team[i][1]\n dp[i] = curr\n\n for j in range(i):\n if team[j][1] <= curr:\n dp[i] = max(dp[i], dp[j]+curr)\n \n return max(dp)\n\n```
1
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_. **Example 1:** **Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\] **Output:** 34 **Explanation:** You can choose all the players. **Example 2:** **Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\] **Output:** 16 **Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. **Example 3:** **Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\] **Output:** 6 **Explanation:** It is best to choose the first 3 players. **Constraints:** * `1 <= scores.length, ages.length <= 1000` * `scores.length == ages.length` * `1 <= scores[i] <= 106` * `1 <= ages[i] <= 1000`
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
Simple python solution
best-team-with-no-conflicts
0
1
# Intuition\nMake zip of the two lists and sort them according to age.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Code\n```\nclass Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n team = list(zip(ages,scores))\n team.sort()\n n = len(ages)\n dp = [0]*n\n\n for i in range(n):\n curr = team[i][1]\n dp[i] = curr\n\n for j in range(i):\n if team[j][1] <= curr:\n dp[i] = max(dp[i], dp[j]+curr)\n \n return max(dp)\n\n```
1
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. **Example 2:** **Input:** nums = \[1,1,1,1,1\] **Output:** 0 **Explanation:** There are no unique elements, and the sum is 0. **Example 3:** **Input:** nums = \[1,2,3,4,5\] **Output:** 15 **Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Simplest UNION FIND in Python with general template
graph-connectivity-with-threshold
0
1
\n\n# Template\n```\nclass DSU:\n\tdef __init__(self, n):\n\t\tself.par = list(range(n))\n\t\tself.rank = [1] * n\n\t\tself.size = 1\n\t\n\tdef find(self, u):\n\t\tif u != self.par[u]:\n\t\t\tself.par[u] = self.find(self.par[u])\n\t\treturn self.par[u]\n\t\n\tdef union(self, u, v):\n\t\tuu, vv = self.find(u), self.find(v)\n\t\tif uu == vv:\n\t\t\treturn False\n\t\tif self.rank[uu] > self.rank[vv]:\n\t\t\tself.par[vv] = uu\n\t\telif self.rank[vv] > self.rank[uu]:\n\t\t\tself.par[uu] = vv\n\t\telse:\n\t\t\tself.par[uu] = vv\n\t\t\tself.rank[vv] += 1\n\t\tself.size += 1\n\t\treturn True\n\nclass Solution:\n def solve(.....):\n # initialize your uf1, uf2 etc..\n # for the given question code for what nodes you will union\n # depending on your return type, initialize ans. list, int ...\n # \n```\n\nBased on this template for this question, code will be:\n```\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n uf = DSU(n+1)\n for z in range(threshold+1, n+1):\n for x in range(z+z, n+1, z):\n uf.union(z, x)\n ans = [False] * len(queries)\n for i, (u, v) in enumerate(queries):\n ans[i] = uf.find(u) == uf.find(v)\n return ans\n```\nFinal code with template to submit:\n\n\n# Code\n```\nclass DSU:\n\tdef __init__(self, n):\n\t\tself.par = list(range(n))\n\t\tself.rank = [1] * n\n\t\tself.size = 1\n\t\n\tdef find(self, u):\n\t\tif u != self.par[u]:\n\t\t\tself.par[u] = self.find(self.par[u])\n\t\treturn self.par[u]\n\t\n\tdef union(self, u, v):\n\t\tuu, vv = self.find(u), self.find(v)\n\t\tif uu == vv:\n\t\t\treturn False\n\t\tif self.rank[uu] > self.rank[vv]:\n\t\t\tself.par[vv] = uu\n\t\telif self.rank[vv] > self.rank[uu]:\n\t\t\tself.par[uu] = vv\n\t\telse:\n\t\t\tself.par[uu] = vv\n\t\t\tself.rank[vv] += 1\n\t\tself.size += 1\n\t\treturn True\n\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n uf = DSU(n+1)\n for z in range(threshold+1, n+1):\n for x in range(z+z, n+1, z):\n uf.union(z, x)\n ans = [False] * len(queries)\n for i, (u, v) in enumerate(queries):\n ans[i] = uf.find(u) == uf.find(v)\n return ans\n```
3
We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true: * `x % z == 0`, * `y % z == 0`, and * `z > threshold`. Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them). Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._ **Example 1:** **Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\] **Output:** \[false,false,true\] **Explanation:** The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: \[1,4\] 1 is not connected to 4 \[2,5\] 2 is not connected to 5 \[3,6\] 3 is connected to 6 through path 3--6 **Example 2:** **Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\] **Output:** \[true,true,true,true,true\] **Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. **Example 3:** **Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\] **Output:** \[false,false,false,false,false\] **Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\]. **Constraints:** * `2 <= n <= 104` * `0 <= threshold <= n` * `1 <= queries.length <= 105` * `queries[i].length == 2` * `1 <= ai, bi <= cities` * `ai != bi`
The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.
Simplest UNION FIND in Python with general template
graph-connectivity-with-threshold
0
1
\n\n# Template\n```\nclass DSU:\n\tdef __init__(self, n):\n\t\tself.par = list(range(n))\n\t\tself.rank = [1] * n\n\t\tself.size = 1\n\t\n\tdef find(self, u):\n\t\tif u != self.par[u]:\n\t\t\tself.par[u] = self.find(self.par[u])\n\t\treturn self.par[u]\n\t\n\tdef union(self, u, v):\n\t\tuu, vv = self.find(u), self.find(v)\n\t\tif uu == vv:\n\t\t\treturn False\n\t\tif self.rank[uu] > self.rank[vv]:\n\t\t\tself.par[vv] = uu\n\t\telif self.rank[vv] > self.rank[uu]:\n\t\t\tself.par[uu] = vv\n\t\telse:\n\t\t\tself.par[uu] = vv\n\t\t\tself.rank[vv] += 1\n\t\tself.size += 1\n\t\treturn True\n\nclass Solution:\n def solve(.....):\n # initialize your uf1, uf2 etc..\n # for the given question code for what nodes you will union\n # depending on your return type, initialize ans. list, int ...\n # \n```\n\nBased on this template for this question, code will be:\n```\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n uf = DSU(n+1)\n for z in range(threshold+1, n+1):\n for x in range(z+z, n+1, z):\n uf.union(z, x)\n ans = [False] * len(queries)\n for i, (u, v) in enumerate(queries):\n ans[i] = uf.find(u) == uf.find(v)\n return ans\n```\nFinal code with template to submit:\n\n\n# Code\n```\nclass DSU:\n\tdef __init__(self, n):\n\t\tself.par = list(range(n))\n\t\tself.rank = [1] * n\n\t\tself.size = 1\n\t\n\tdef find(self, u):\n\t\tif u != self.par[u]:\n\t\t\tself.par[u] = self.find(self.par[u])\n\t\treturn self.par[u]\n\t\n\tdef union(self, u, v):\n\t\tuu, vv = self.find(u), self.find(v)\n\t\tif uu == vv:\n\t\t\treturn False\n\t\tif self.rank[uu] > self.rank[vv]:\n\t\t\tself.par[vv] = uu\n\t\telif self.rank[vv] > self.rank[uu]:\n\t\t\tself.par[uu] = vv\n\t\telse:\n\t\t\tself.par[uu] = vv\n\t\t\tself.rank[vv] += 1\n\t\tself.size += 1\n\t\treturn True\n\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n uf = DSU(n+1)\n for z in range(threshold+1, n+1):\n for x in range(z+z, n+1, z):\n uf.union(z, x)\n ans = [False] * len(queries)\n for i, (u, v) in enumerate(queries):\n ans[i] = uf.find(u) == uf.find(v)\n return ans\n```
3
A die simulator generates a random number from `1` to `6` for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (**1-indexed**) consecutive times. Given an array of integers `rollMax` and an integer `n`, return _the number of distinct sequences that can be obtained with exact_ `n` _rolls_. Since the answer may be too large, return it **modulo** `109 + 7`. Two sequences are considered different if at least one element differs from each other. **Example 1:** **Input:** n = 2, rollMax = \[1,1,2,2,2,3\] **Output:** 34 **Explanation:** There will be 2 rolls of die, if there are no constraints on the die, there are 6 \* 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. **Example 2:** **Input:** n = 2, rollMax = \[1,1,1,1,1,1\] **Output:** 30 **Example 3:** **Input:** n = 3, rollMax = \[1,1,1,2,2,3\] **Output:** 181 **Constraints:** * `1 <= n <= 5000` * `rollMax.length == 6` * `1 <= rollMax[i] <= 15`
How to build the graph of the cities? Connect city i with all its multiples 2*i, 3*i, ... Answer the queries using union-find data structure.
Union Find py3, connect all multiplies
graph-connectivity-with-threshold
0
1
# Code\n```\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n p = [i for i in range(n+1)]\n def find(i):\n if i!=p[i]:\n p[i] = find(p[i])\n return p[i]\n graph = {i:set([]) for i in range(1,n+1)}\n for i in range(threshold+1,n+1):\n j = i*2\n while j <= n:\n pi,pj = find(i),find(j)\n if pi!=pj:\n pi,pj = sorted([pi,pj])\n p[pj] = pi\n j += i\n res = []\n for i,j in queries:\n res.append(find(i) == find(j))\n return res\n \n \n\n \n```
0
We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true: * `x % z == 0`, * `y % z == 0`, and * `z > threshold`. Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them). Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._ **Example 1:** **Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\] **Output:** \[false,false,true\] **Explanation:** The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: \[1,4\] 1 is not connected to 4 \[2,5\] 2 is not connected to 5 \[3,6\] 3 is connected to 6 through path 3--6 **Example 2:** **Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\] **Output:** \[true,true,true,true,true\] **Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. **Example 3:** **Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\] **Output:** \[false,false,false,false,false\] **Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\]. **Constraints:** * `2 <= n <= 104` * `0 <= threshold <= n` * `1 <= queries.length <= 105` * `queries[i].length == 2` * `1 <= ai, bi <= cities` * `ai != bi`
The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.
Union Find py3, connect all multiplies
graph-connectivity-with-threshold
0
1
# Code\n```\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n p = [i for i in range(n+1)]\n def find(i):\n if i!=p[i]:\n p[i] = find(p[i])\n return p[i]\n graph = {i:set([]) for i in range(1,n+1)}\n for i in range(threshold+1,n+1):\n j = i*2\n while j <= n:\n pi,pj = find(i),find(j)\n if pi!=pj:\n pi,pj = sorted([pi,pj])\n p[pj] = pi\n j += i\n res = []\n for i,j in queries:\n res.append(find(i) == find(j))\n return res\n \n \n\n \n```
0
A die simulator generates a random number from `1` to `6` for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (**1-indexed**) consecutive times. Given an array of integers `rollMax` and an integer `n`, return _the number of distinct sequences that can be obtained with exact_ `n` _rolls_. Since the answer may be too large, return it **modulo** `109 + 7`. Two sequences are considered different if at least one element differs from each other. **Example 1:** **Input:** n = 2, rollMax = \[1,1,2,2,2,3\] **Output:** 34 **Explanation:** There will be 2 rolls of die, if there are no constraints on the die, there are 6 \* 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. **Example 2:** **Input:** n = 2, rollMax = \[1,1,1,1,1,1\] **Output:** 30 **Example 3:** **Input:** n = 3, rollMax = \[1,1,1,2,2,3\] **Output:** 181 **Constraints:** * `1 <= n <= 5000` * `rollMax.length == 6` * `1 <= rollMax[i] <= 15`
How to build the graph of the cities? Connect city i with all its multiples 2*i, 3*i, ... Answer the queries using union-find data structure.
python3 prime sieve + union find
graph-connectivity-with-threshold
0
1
\n\n# Code\n```\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n self.parent = list(range(n+1))\n for i in range(threshold+1,n+1):\n for j in range(i,n+1,i):\n self.union(j,i)\n \n res = []\n for a,b in queries:\n if self.find(a)== self.find(b):\n res.append(True)\n else:\n res.append(False)\n return res\n\n def find(self, a):\n acopy = a\n while a != self.parent[a]:\n a = self.parent[a]\n while acopy != a:\n self.parent[acopy], acopy = a, self.parent[acopy]\n return a\n\n def union(self, a, b):\n self.parent[self.find(b)] = self.find(a)\n\n```
0
We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true: * `x % z == 0`, * `y % z == 0`, and * `z > threshold`. Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them). Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._ **Example 1:** **Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\] **Output:** \[false,false,true\] **Explanation:** The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: \[1,4\] 1 is not connected to 4 \[2,5\] 2 is not connected to 5 \[3,6\] 3 is connected to 6 through path 3--6 **Example 2:** **Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\] **Output:** \[true,true,true,true,true\] **Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. **Example 3:** **Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\] **Output:** \[false,false,false,false,false\] **Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\]. **Constraints:** * `2 <= n <= 104` * `0 <= threshold <= n` * `1 <= queries.length <= 105` * `queries[i].length == 2` * `1 <= ai, bi <= cities` * `ai != bi`
The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.
python3 prime sieve + union find
graph-connectivity-with-threshold
0
1
\n\n# Code\n```\nclass Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n self.parent = list(range(n+1))\n for i in range(threshold+1,n+1):\n for j in range(i,n+1,i):\n self.union(j,i)\n \n res = []\n for a,b in queries:\n if self.find(a)== self.find(b):\n res.append(True)\n else:\n res.append(False)\n return res\n\n def find(self, a):\n acopy = a\n while a != self.parent[a]:\n a = self.parent[a]\n while acopy != a:\n self.parent[acopy], acopy = a, self.parent[acopy]\n return a\n\n def union(self, a, b):\n self.parent[self.find(b)] = self.find(a)\n\n```
0
A die simulator generates a random number from `1` to `6` for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (**1-indexed**) consecutive times. Given an array of integers `rollMax` and an integer `n`, return _the number of distinct sequences that can be obtained with exact_ `n` _rolls_. Since the answer may be too large, return it **modulo** `109 + 7`. Two sequences are considered different if at least one element differs from each other. **Example 1:** **Input:** n = 2, rollMax = \[1,1,2,2,2,3\] **Output:** 34 **Explanation:** There will be 2 rolls of die, if there are no constraints on the die, there are 6 \* 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. **Example 2:** **Input:** n = 2, rollMax = \[1,1,1,1,1,1\] **Output:** 30 **Example 3:** **Input:** n = 3, rollMax = \[1,1,1,2,2,3\] **Output:** 181 **Constraints:** * `1 <= n <= 5000` * `rollMax.length == 6` * `1 <= rollMax[i] <= 15`
How to build the graph of the cities? Connect city i with all its multiples 2*i, 3*i, ... Answer the queries using union-find data structure.
you can use the concept of Disjoint set Union (DSU) or Union-Find data structure
graph-connectivity-with-threshold
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 areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n def find(parent, x):\n if parent[x] == x:\n return x\n parent[x] = find(parent, parent[x])\n return parent[x]\n\n def union(parent, x, y):\n root_x = find(parent, x)\n root_y = find(parent, y)\n if root_x != root_y:\n parent[root_x] = root_y\n\n # Initialize parent array for DSU\n parent = list(range(n + 1))\n\n # Iterate through all pairs of cities\n for x in range(threshold + 1, n + 1):\n for y in range(2 * x, n + 1, x):\n union(parent, x, y)\n\n # Check if queries are connected\n result = []\n for a, b in queries:\n result.append(find(parent, a) == find(parent, b))\n\n return result\n\n```
0
We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true: * `x % z == 0`, * `y % z == 0`, and * `z > threshold`. Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them). Return _an array_ `answer`_, where_ `answer.length == queries.length` _and_ `answer[i]` _is_ `true` _if for the_ `ith` _query, there is a path between_ `ai` _and_ `bi`_, or_ `answer[i]` _is_ `false` _if there is no path._ **Example 1:** **Input:** n = 6, threshold = 2, queries = \[\[1,4\],\[2,5\],\[3,6\]\] **Output:** \[false,false,true\] **Explanation:** The divisors for each number: 1: 1 2: 1, 2 3: 1, 3 4: 1, 2, 4 5: 1, 5 6: 1, 2, 3, 6 Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the only ones directly connected. The result of each query: \[1,4\] 1 is not connected to 4 \[2,5\] 2 is not connected to 5 \[3,6\] 3 is connected to 6 through path 3--6 **Example 2:** **Input:** n = 6, threshold = 0, queries = \[\[4,5\],\[3,4\],\[3,2\],\[2,6\],\[1,3\]\] **Output:** \[true,true,true,true,true\] **Explanation:** The divisors for each number are the same as the previous example. However, since the threshold is 0, all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected. **Example 3:** **Input:** n = 5, threshold = 1, queries = \[\[4,5\],\[4,5\],\[3,2\],\[2,3\],\[3,4\]\] **Output:** \[false,false,false,false,false\] **Explanation:** Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected. Please notice that there can be multiple queries for the same pair of nodes \[x, y\], and that the query \[x, y\] is equivalent to the query \[y, x\]. **Constraints:** * `2 <= n <= 104` * `0 <= threshold <= n` * `1 <= queries.length <= 105` * `queries[i].length == 2` * `1 <= ai, bi <= cities` * `ai != bi`
The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction.
you can use the concept of Disjoint set Union (DSU) or Union-Find data structure
graph-connectivity-with-threshold
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 areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n def find(parent, x):\n if parent[x] == x:\n return x\n parent[x] = find(parent, parent[x])\n return parent[x]\n\n def union(parent, x, y):\n root_x = find(parent, x)\n root_y = find(parent, y)\n if root_x != root_y:\n parent[root_x] = root_y\n\n # Initialize parent array for DSU\n parent = list(range(n + 1))\n\n # Iterate through all pairs of cities\n for x in range(threshold + 1, n + 1):\n for y in range(2 * x, n + 1, x):\n union(parent, x, y)\n\n # Check if queries are connected\n result = []\n for a, b in queries:\n result.append(find(parent, a) == find(parent, b))\n\n return result\n\n```
0
A die simulator generates a random number from `1` to `6` for each roll. You introduced a constraint to the generator such that it cannot roll the number `i` more than `rollMax[i]` (**1-indexed**) consecutive times. Given an array of integers `rollMax` and an integer `n`, return _the number of distinct sequences that can be obtained with exact_ `n` _rolls_. Since the answer may be too large, return it **modulo** `109 + 7`. Two sequences are considered different if at least one element differs from each other. **Example 1:** **Input:** n = 2, rollMax = \[1,1,2,2,2,3\] **Output:** 34 **Explanation:** There will be 2 rolls of die, if there are no constraints on the die, there are 6 \* 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34. **Example 2:** **Input:** n = 2, rollMax = \[1,1,1,1,1,1\] **Output:** 30 **Example 3:** **Input:** n = 3, rollMax = \[1,1,1,2,2,3\] **Output:** 181 **Constraints:** * `1 <= n <= 5000` * `rollMax.length == 6` * `1 <= rollMax[i] <= 15`
How to build the graph of the cities? Connect city i with all its multiples 2*i, 3*i, ... Answer the queries using union-find data structure.
time: O(n log n), space: O(n) 4 lines
slowest-key
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 slowestKey(self, releaseTimes: List[int], keyPressed: str) -> str:\n diff = releaseTimes[0:1] + [releaseTimes[i+1] - releaseTimes[i] for i in range(len(releaseTimes)-1)]\n keyPressed = [x for x in keyPressed]\n \n hash_ = [(k, val) for k, val in zip(diff, keyPressed)]\n return sorted(hash_, reverse=True)[0][1]\n```
1
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. _Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ **Example 1:** **Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd " **Output:** "c " **Explanation:** The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. **Example 2:** **Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda " **Output:** "a " **Explanation:** The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. **Constraints:** * `releaseTimes.length == n` * `keysPressed.length == n` * `2 <= n <= 1000` * `1 <= releaseTimes[i] <= 109` * `releaseTimes[i] < releaseTimes[i+1]` * `keysPressed` contains only lowercase English letters.
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
time: O(n log n), space: O(n) 4 lines
slowest-key
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 slowestKey(self, releaseTimes: List[int], keyPressed: str) -> str:\n diff = releaseTimes[0:1] + [releaseTimes[i+1] - releaseTimes[i] for i in range(len(releaseTimes)-1)]\n keyPressed = [x for x in keyPressed]\n \n hash_ = [(k, val) for k, val in zip(diff, keyPressed)]\n return sorted(hash_, reverse=True)[0][1]\n```
1
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Using Dictionary
slowest-key
0
1
\n\n# Code\n```\nclass Solution:\n def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n time = {}\n prev = 0\n m = 0\n for i in range(0, len(releaseTimes)):\n a = releaseTimes[i]-prev\n prev = releaseTimes[i]\n m = max(m,a)\n if keysPressed[i] not in time:\n time[keysPressed[i]] = a\n else:\n time[keysPressed[i]]=max(time[keysPressed[i]], a)\n\n return sorted([k for k, v in sorted(time.items(), reverse=True, key=lambda item:item[1]) if v==m], reverse=True)[0]\n\n```
1
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. _Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ **Example 1:** **Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd " **Output:** "c " **Explanation:** The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. **Example 2:** **Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda " **Output:** "a " **Explanation:** The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. **Constraints:** * `releaseTimes.length == n` * `keysPressed.length == n` * `2 <= n <= 1000` * `1 <= releaseTimes[i] <= 109` * `releaseTimes[i] < releaseTimes[i+1]` * `keysPressed` contains only lowercase English letters.
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
Using Dictionary
slowest-key
0
1
\n\n# Code\n```\nclass Solution:\n def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n time = {}\n prev = 0\n m = 0\n for i in range(0, len(releaseTimes)):\n a = releaseTimes[i]-prev\n prev = releaseTimes[i]\n m = max(m,a)\n if keysPressed[i] not in time:\n time[keysPressed[i]] = a\n else:\n time[keysPressed[i]]=max(time[keysPressed[i]], a)\n\n return sorted([k for k, v in sorted(time.items(), reverse=True, key=lambda item:item[1]) if v==m], reverse=True)[0]\n\n```
1
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Python - One pass Solution - Clean & simple
slowest-key
0
1
**Python :**\n\n```\ndef slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n\tkey = [keysPressed[0]]\n\tmax_dur = releaseTimes[0]\n\n\tfor i in range(1, len(releaseTimes)):\n\t\tif releaseTimes[i] - releaseTimes[i - 1] == max_dur:\n\t\t\tkey.append(keysPressed[i])\n\n\t\tif releaseTimes[i] - releaseTimes[i - 1] > max_dur:\n\t\t\tmax_dur = releaseTimes[i] - releaseTimes[i - 1]\n\t\t\tkey = [keysPressed[i]]\n\n\n\treturn max(key)\n```\n\n**Like it ? please upvote !**
10
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. _Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ **Example 1:** **Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd " **Output:** "c " **Explanation:** The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. **Example 2:** **Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda " **Output:** "a " **Explanation:** The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. **Constraints:** * `releaseTimes.length == n` * `keysPressed.length == n` * `2 <= n <= 1000` * `1 <= releaseTimes[i] <= 109` * `releaseTimes[i] < releaseTimes[i+1]` * `keysPressed` contains only lowercase English letters.
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
Python - One pass Solution - Clean & simple
slowest-key
0
1
**Python :**\n\n```\ndef slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n\tkey = [keysPressed[0]]\n\tmax_dur = releaseTimes[0]\n\n\tfor i in range(1, len(releaseTimes)):\n\t\tif releaseTimes[i] - releaseTimes[i - 1] == max_dur:\n\t\t\tkey.append(keysPressed[i])\n\n\t\tif releaseTimes[i] - releaseTimes[i - 1] > max_dur:\n\t\t\tmax_dur = releaseTimes[i] - releaseTimes[i - 1]\n\t\t\tkey = [keysPressed[i]]\n\n\n\treturn max(key)\n```\n\n**Like it ? please upvote !**
10
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
[Python3] Simple And Readable Solution
slowest-key
0
1
```\nclass Solution:\n def slowestKey(self, r: List[int], k: str) -> str:\n times = {r[0]: [k[0]]}\n \n for i in range(1 , len(r)):\n t = r[i] - r[i - 1]\n if(t in times):\n times[t].append(k[i])\n else:\n times[t] = [k[i]]\n \n keys = times[max(times.keys())]\n \n return max(keys)\n```
7
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time. You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released. The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`. Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**. _Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._ **Example 1:** **Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd " **Output:** "c " **Explanation:** The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'. **Example 2:** **Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda " **Output:** "a " **Explanation:** The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16. **Constraints:** * `releaseTimes.length == n` * `keysPressed.length == n` * `2 <= n <= 1000` * `1 <= releaseTimes[i] <= 109` * `releaseTimes[i] < releaseTimes[i+1]` * `keysPressed` contains only lowercase English letters.
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
[Python3] Simple And Readable Solution
slowest-key
0
1
```\nclass Solution:\n def slowestKey(self, r: List[int], k: str) -> str:\n times = {r[0]: [k[0]]}\n \n for i in range(1 , len(r)):\n t = r[i] - r[i - 1]\n if(t in times):\n times[t].append(k[i])\n else:\n times[t] = [k[i]]\n \n keys = times[max(times.keys())]\n \n return max(keys)\n```
7
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.