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 d...
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...
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 d...
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 th...
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 (pote...
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 + bs...
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 (pote...
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 plac...
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 v...
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 ...
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 v...
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...
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 s...
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)$$ --...
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 ...
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)$$ --...
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...
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 s...
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
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 ...
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
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...
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 s...
[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 ...
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 ...
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 ...
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...
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 s...
[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-...
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 ...
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-...
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...
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 s...
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)$$ --...
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 ...
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 ...
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)$$ --...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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)$$ --...
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 ...
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 t...
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 al...
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 t...
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 tup...
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 ...
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 al...
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 ...
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 tup...
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 t...
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 al...
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 t...
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 tup...
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...
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 al...
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...
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 tup...
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 ...
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 al...
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 ...
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 tup...
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 ...
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 n...
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 ...
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 wit...
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 poin...
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)...
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 n...
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)...
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 wit...
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 poin...
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 +=...
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 n...
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 +=...
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 wit...
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 poin...
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 ...
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 n...
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 ...
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 wit...
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 poin...
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)$$ --...
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 value...
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 cu...
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)$$ --...
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 c...
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...
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 value...
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 cu...
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...
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 c...
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)$$ --...
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 value...
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 cu...
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)$$ --...
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 c...
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....
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 value...
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 cu...
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....
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 c...
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 ...
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 value...
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 cu...
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 ...
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 c...
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 calculat...
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 value...
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 cu...
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 calculat...
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 c...
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)$$ --...
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 optim...
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)$$ --...
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\] *...
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 optim...
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\] *...
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 elem...
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 optim...
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 elem...
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\] *...
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 optim...
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\] *...
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 mem...
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 optim...
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 mem...
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\] *...
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...
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 optim...
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...
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\] *...
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 optim...
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\] *...
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 ...
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 optim...
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 ...
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\] *...
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 ...
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...
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 ...
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...
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...
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...
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 findLexSmal...
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...
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 = ...
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...
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 ...
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...
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 ...
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...
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 m...
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 ...
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 m...
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. ...
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 ...
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 ...
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 ...
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. ...
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 ...
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 ...
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 ...
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. ...
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 = ...
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 ...
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 = ...
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. ...
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...
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 ...
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...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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)$$ --...
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 ...
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)$$ --...
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 ...
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)$$ --...
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 releas...
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)$$ --...
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 o...
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 ...
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 releas...
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 ...
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 o...
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] - releaseTi...
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 releas...
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] - releaseTi...
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 o...
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 ...
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 releas...
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 ...
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 o...
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.