title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python | Simulation | Simple Solution | O(mn)
decode-the-slanted-ciphertext
0
1
# Code\n```\nclass Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n cols = len(encodedText)//rows\n matrix = [[0]*cols for _ in range(rows)]\n for i in range(rows):\n for j in range(cols):\n matrix[i][j] = encodedText[i*cols + j]\n i,...
0
A string `originalText` is encoded using a **slanted transposition cipher** to a string `encodedText` with the help of a matrix having a **fixed number of rows** `rows`. `originalText` is placed first in a top-left to bottom-right manner. The blue cells are filled first, followed by the red cells, then the yellow cel...
Convert lights into an array of ranges representing the range where each street light can light up and sort the start and end points of the ranges. Do we need to traverse all possible positions on the street? No, we don't, we only need to go to the start and end points of the ranges for each streetlight.
python3 simple union find
process-restricted-friend-requests
0
1
\n\n# Code\n```\nclass Solution:\n def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:\n res = []\n self.parent = list(range(n))\n for a,b in requests:\n temp = self.parent.copy()\n self.union(a,b)\n flag = Tr...
1
You are given an integer `n` indicating the number of people in a network. Each person is labeled from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `restrictions`, where `restrictions[i] = [xi, yi]` means that person `xi` and person `yi` **cannot** become **friends**, either **directly** or **in...
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
[Python] [272 ms,36 MB] Maintain connected components of the graph
process-restricted-friend-requests
0
1
Maintain two lists of sets ```connected_components``` and ```banned_by_comps``` to store the connected components the restrictions of nodes in each connected component. Maintain a dictionary ```connected_comp_dict``` to map each node to its connected compoent. Update them when a new edge is added.\n```\nclass Solution:...
2
You are given an integer `n` indicating the number of people in a network. Each person is labeled from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `restrictions`, where `restrictions[i] = [xi, yi]` means that person `xi` and person `yi` **cannot** become **friends**, either **directly** or **in...
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
Hash Table + Union Find | 661 ms - faster than 71.86% solutions
process-restricted-friend-requests
0
1
# Complexity\n- Time complexity: $$O(m \\cdot\\log(m) + k \\cdot m \\cdot \\alpha(n))$$\n- Space complexity: $$O(n + m + k)$$\n\nwhere `m = restrictions.length, k = requests.length`,\n$\\alpha(n)$ is inverse Ackermann function ([wiki](https://en.wikipedia.org/wiki/Ackermann_function#Inverse)).\n\nBecause `n < 1000, m <...
0
You are given an integer `n` indicating the number of people in a network. Each person is labeled from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `restrictions`, where `restrictions[i] = [xi, yi]` means that person `xi` and person `yi` **cannot** become **friends**, either **directly** or **in...
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
Union Find + small trick
process-restricted-friend-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic union find data structure to be used. The part to tell if the a restriction would be violated before a connection can be made needs some thinking, which is the hardest part of this problem.\n\n# Approach\n<!-- Describe your approach...
0
You are given an integer `n` indicating the number of people in a network. Each person is labeled from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `restrictions`, where `restrictions[i] = [xi, yi]` means that person `xi` and person `yi` **cannot** become **friends**, either **directly** or **in...
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
Constant Space
two-furthest-houses-with-different-colors
1
1
The maximum distance will always include either first or the last house. This can be proven by a contradiction.\n\nTherefore, we need to return the maximum of two cases: `max(j, n - i - 1)`, where\n- `i` is the leftmost position of the color different from the last color.\n- `j` is the rightmost position of the color d...
80
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
Easy Python solution | Beats 89.95%
two-furthest-houses-with-different-colors
0
1
\n# Code\n```\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n ind1, ind2 = 0, -1\n size = len(colors)\n while ind1 < size:\n front = colors[ind1]\n if front != colors[-1]:\n return size - ind1 - 1\n last = colors[ind2]\n ...
2
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
[Python3] one of end points will be used
two-furthest-houses-with-different-colors
0
1
Downvoters, lease a comment! \n\nIt is not difficult to find out that at least one of the end points will be used. \n\nPlease check out this [commit](https://github.com/gaosanyong/leetcode/commit/b5ca73e6f7d317e9f30f7e67a499b0bf489ec019) for the solutions of weekly 268. \n```\nclass Solution:\n def maxDistance(self,...
33
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
Python3 | both side checking | fastest
two-furthest-houses-with-different-colors
0
1
```\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n clr1=colors[0]\n clr2=colors[-1]\n mx=0\n for i in range(len(colors)-1,-1,-1):\n if clr1!=colors[i]:\n mx=max(mx,i)\n break\n for i in range(len(colors)):\n ...
4
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
90% O(n) - Fast & Easy 2-pointer / Greedy
two-furthest-houses-with-different-colors
0
1
Easiest way to do a scan like this is with two pointers. Fix a left pointer, and while they\'re equal, move the right pointer from the end, inward until they arent. Then, take the distance by index. However, that will only solve the example cases. To correctly solve an edge case (where Greedy comes in to play), do the ...
6
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
Easy Python Solution
two-furthest-houses-with-different-colors
0
1
```\ndef maxDistance(self, colors: List[int]) -> int:\n m=0\n for i in range(0,len(colors)):\n for j in range(len(colors)-1,0,-1):\n if colors[i]!=colors[j] and j>i:\n m=max(m,j-i)\n return m\n```
6
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
Python3 simple solution
two-furthest-houses-with-different-colors
0
1
```\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n x = []\n for i in range(len(colors)-1):\n for j in range(i+1,len(colors)):\n if colors[i] != colors[j]:\n x.append(j-i)\n return max(x)\n```\n**If you like this solution, please...
2
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
Simple Python Solution: O(n)
two-furthest-houses-with-different-colors
0
1
## INTUITION:\n\n- __Target__: Compute the maximum distance between two houses of different colors\n- __Assumption__: \n\t- The distance between any two houses is uniform and equal to one.\n\t- There has to be atleast two elements in the array/list to compute the distance.\n- Maximum possible distance is observed when...
3
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
Two solutions O(n) and O(n^2)
two-furthest-houses-with-different-colors
0
1
O(n)\n```\nclass Solution:\n def maxDistance(self, colors: List[int]) -> int:\n i=0\n l=len(colors)\n j=l-1\n while colors[j] == colors[0]:\n j-=1\n \n while colors[-1] == colors[i]:\n i+=1\n return max(j,l-1-i)\n```\nO(n^2)\n```\n max_dis...
4
There are `n` houses evenly lined up on the street, and each house is beautifully painted. You are given a **0-indexed** integer array `colors` of length `n`, where `colors[i]` represents the color of the `ith` house. Return _the **maximum** distance between **two** houses with **different** colors_. The distance bet...
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
[Python3] simulation
watering-plants
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b5ca73e6f7d317e9f30f7e67a499b0bf489ec019) for the solutions of weekly 268. \n```\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n ans = 0\n can = capacity\n for i, x in enumerate(p...
25
You want to water `n` plants in your garden with a watering can. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`. There is a river at `x = -1` that you can refill your watering can at. Each plant needs a specific amount of water. You w...
Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?
[Python3] simulation
watering-plants
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b5ca73e6f7d317e9f30f7e67a499b0bf489ec019) for the solutions of weekly 268. \n```\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n ans = 0\n can = capacity\n for i, x in enumerate(p...
25
You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`. For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ). Return an array `answer` where `answer[i]` is...
Simulate the process. Return to refill the container once you meet a plant that needs more water than you have.
Awesome Logic problem
watering-plants
0
1
```\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n stored=capacity\n ans=0\n for i,v in enumerate(plants):\n if capacity>=v:\n ans+=1\n capacity-=v\n else:\n\t\t\t# main Logic\n ans+=i+(i+...
2
You want to water `n` plants in your garden with a watering can. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`. There is a river at `x = -1` that you can refill your watering can at. Each plant needs a specific amount of water. You w...
Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?
Awesome Logic problem
watering-plants
0
1
```\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n stored=capacity\n ans=0\n for i,v in enumerate(plants):\n if capacity>=v:\n ans+=1\n capacity-=v\n else:\n\t\t\t# main Logic\n ans+=i+(i+...
2
You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`. For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ). Return an array `answer` where `answer[i]` is...
Simulate the process. Return to refill the container once you meet a plant that needs more water than you have.
[PYTHON 3] FASTER THAN 96.9% | LESS THAN 84.8%
watering-plants
0
1
Runtime: **47 ms, faster than 96.80%** of Python3 online submissions for Watering Plants.\nMemory Usage: **14 MB, less than 84.80%** of Python3 online submissions for Watering Plants.\n```\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n s, p, c = 0, -1, capacity\n ...
2
You want to water `n` plants in your garden with a watering can. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`. There is a river at `x = -1` that you can refill your watering can at. Each plant needs a specific amount of water. You w...
Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?
[PYTHON 3] FASTER THAN 96.9% | LESS THAN 84.8%
watering-plants
0
1
Runtime: **47 ms, faster than 96.80%** of Python3 online submissions for Watering Plants.\nMemory Usage: **14 MB, less than 84.80%** of Python3 online submissions for Watering Plants.\n```\nclass Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n s, p, c = 0, -1, capacity\n ...
2
You are given an array `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`. For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ). Return an array `answer` where `answer[i]` is...
Simulate the process. Return to refill the container once you meet a plant that needs more water than you have.
Simple Python Solution 8 Lines 63 %
watering-plants
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 want to water `n` plants in your garden with a watering can. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`. There is a river at `x = -1` that you can refill your watering can at. Each plant needs a specific amount of water. You w...
Can we use a trie to build the folder structure? Can we utilize hashing to hash the folder structures?
Simple Python Solution 8 Lines 63 %
watering-plants
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 `arr` of positive integers. You are also given the array `queries` where `queries[i] = [lefti, righti]`. For each query `i` compute the **XOR** of elements from `lefti` to `righti` (that is, `arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]` ). Return an array `answer` where `answer[i]` is...
Simulate the process. Return to refill the container once you meet a plant that needs more water than you have.
Arrays of Indices
range-frequency-queries
1
1
Since the value is limited to 10,000, we can just store positions for each value and then binary-search for the range.\n\n> Note: a lot of folks got TLE because they collected frequencies for each number and each position. This allows answering queries in O(1), but populating the array takes O(n * m) time and space.\n\...
41
Design a data structure to find the **frequency** of a given value in a given subarray. The **frequency** of a value in a subarray is the number of occurrences of that value in the subarray. Implement the `RangeFreqQuery` class: * `RangeFreqQuery(int[] arr)` Constructs an instance of the class with the given **0-i...
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
[Python3] binary search
range-frequency-queries
0
1
Downvoters, leave a comment! \n\nPlease check out this [commit](https://github.com/gaosanyong/leetcode/commit/b5ca73e6f7d317e9f30f7e67a499b0bf489ec019) for the solutions of weekly 268. \n```\nclass RangeFreqQuery:\n\n def __init__(self, arr: List[int]):\n self.loc = defaultdict(list)\n for i, x in enum...
9
Design a data structure to find the **frequency** of a given value in a given subarray. The **frequency** of a value in a subarray is the number of occurrences of that value in the subarray. Implement the `RangeFreqQuery` class: * `RangeFreqQuery(int[] arr)` Constructs an instance of the class with the given **0-i...
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
Easy solution - Python
range-frequency-queries
0
1
Please upvote if you like the solution\n\n# Code\n```\nclass RangeFreqQuery:\n \n \n def __init__(self, arr: List[int]):\n self.arr = arr\n self.mydict = {}\n \n\n def query(self, left: int, right: int, value: int) -> int:\n if value in self.mydict and self.mydict[value][0]==left...
0
Design a data structure to find the **frequency** of a given value in a given subarray. The **frequency** of a value in a subarray is the number of occurrences of that value in the subarray. Implement the `RangeFreqQuery` class: * `RangeFreqQuery(int[] arr)` Constructs an instance of the class with the given **0-i...
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
Binary Search, Count Dict, DP Python
range-frequency-queries
0
1
# Complexity\n- Time complexity:\n\n O(N + qlog(N)) \n\n O(N) to build count list.\n log(N) for each q queries.\n\n- Space complexity:\n\n O(N)\n\n# Code\n```\nfrom bisect import bisect_right, bisect_left\nclass RangeFreqQuery:\n \n def __init__(self, arr: List[int]):\n self.count = [[] for _ i...
0
Design a data structure to find the **frequency** of a given value in a given subarray. The **frequency** of a value in a subarray is the number of occurrences of that value in the subarray. Implement the `RangeFreqQuery` class: * `RangeFreqQuery(int[] arr)` Constructs an instance of the class with the given **0-i...
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
[Python3] enumerate k-symmetric numbers
sum-of-k-mirror-numbers
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b5ca73e6f7d317e9f30f7e67a499b0bf489ec019) for the solutions of weekly 268. \n\n```\nclass Solution:\n def kMirror(self, k: int, n: int) -> int:\n \n def fn(x):\n """Return next k-symmetric number."""\n n ...
48
A **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. * For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 are `9` and `1001` respectively, which read the same both forward and b...
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
[Python3] Easy Python Brute Force with comment
sum-of-k-mirror-numbers
0
1
```python\nclass Solution:\n def kMirror(self, k: int, n: int) -> int:\n\n def numberToBase(n, b):\n if n == 0:\n return [0]\n digits = []\n while n:\n digits.append(n % b)\n n //= b\n return digits[::-1]\n \n ...
10
A **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. * For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 are `9` and `1001` respectively, which read the same both forward and b...
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
Python Itertools Product base k generation
sum-of-k-mirror-numbers
0
1
# Intuition\nGenerate all base-k palindromes in order, then convert them to base 10 to check if they are also palidromes there\n\n# Approach\nPalindromes come in two forms- even length and odd length. \n\nTo generate an even palindrome, first generate the first half of the palindrome, then mirror it around the middle. ...
0
A **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. * For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 are `9` and `1001` respectively, which read the same both forward and b...
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
69th Solution
sum-of-k-mirror-numbers
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 **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. * For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 are `9` and `1001` respectively, which read the same both forward and b...
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
python3 (generating all palindromes)
sum-of-k-mirror-numbers
0
1
![image](https://assets.leetcode.com/users/images/db265c98-ff43-431d-8b97-7cbc47e40bd3_1637515355.7147493.png)\n\n\n```\n def kMirror(self, k: int, n: int) -> int:\n @cache \n def helper(start, n): \n if n == 1:\n return [str(i) for i in range(start, k)]\n ...
2
A **k-mirror number** is a **positive** integer **without leading zeros** that reads the same both forward and backward in base-10 **as well as** in base-k. * For example, `9` is a 2-mirror number. The representation of `9` in base-10 and base-2 are `9` and `1001` respectively, which read the same both forward and b...
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
One line solution
count-common-words-with-one-occurrence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
Count common words with one occurrence
count-common-words-with-one-occurrence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
Python3 solution, clean code with full comments.
count-common-words-with-one-occurrence
0
1
```\nclass Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n \n counter = 0\n \n count_words_1 = convert(words1)\n \n count_words_2 = convert(words2) \n \n count_words_1 = remove_multipel_occurences(c...
1
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
[Python3] 2-line freq table
count-common-words-with-one-occurrence
0
1
Downvoters, leave a comment! \n\nFor solutions of biweekly 66, please check out this [commit](https://github.com/gaosanyong/leetcode/commit/2efa877859ad8f79f212b8ebde3edf5730d457ad)\n```\nclass Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n freq1, freq2 = Counter(words1), Cou...
14
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
Python | 2-liner solution
count-common-words-with-one-occurrence
0
1
```\nclass Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n fix = lambda w: set(filter(lambda x: x[1] == 1, Counter(w).items()))\n\n return len(fix(words1) & fix(words2))\n```
1
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
Python Easy Solution
count-common-words-with-one-occurrence
0
1
```\nclass Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n w1,w2,r = words1 , words2 , 0\n for i in w1:\n if w1.count(i) == w2.count(i) == 1:\n r += 1\n return r\n```
5
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
2 Liner Python Solution || 110ms (50 %) || Memory (82 %)
count-common-words-with-one-occurrence
0
1
```\nclass Solution:\n\tdef countWords(self, words1: List[str], words2: List[str]) -> int:\n\t\tcount = Counter(words1 + words2)\n\t\treturn len([word for word in count if count[word] == 2 and word in words1 and word in words2])\n```\n-------------------\n***----- Taha Choura -----***\n*taha.choura@outlook.com*
3
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
✅ Beats 98.84% solutions,✅ Python easy to understand code with explanation --- ✅ By BOLT CODING ✅
count-common-words-with-one-occurrence
0
1
# Explanation\nHere we are creating 2 Counter objects and keeping track of all the words.\nWe can iterate through either of the counter and check if number == 1, if this case passes we check if the occurence of same word is 1 in the other counter. If both condition satisfies we will update the count and return that val...
3
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
Python Solution | Faster than 99% | O(n) time complexity
count-common-words-with-one-occurrence
0
1
![image](https://assets.leetcode.com/users/images/79b78d71-a7d6-465d-b03e-f3accd1f40b3_1647471815.8207211.png)\n\nExplanation can be found after full solution code block.\nFull Solution:\n```\ncount1 = {}\nfor i in words1:\n\tif i in count1:\n\t\t\tcount1[i] += 1\n\telse:\n\t\tcount1[i] = 1\n ans = 0\n count2 = {}\n fo...
7
Given two string arrays `words1` and `words2`, return _the number of strings that appear **exactly once** in **each** of the two arrays._ **Example 1:** **Input:** words1 = \[ "leetcode ", "is ", "amazing ", "as ", "is "\], words2 = \[ "amazing ", "leetcode ", "is "\] **Output:** 2 **Explanation:** - "leetcode " app...
A number can be the average of its neighbors if one neighbor is smaller than the number and the other is greater than the number. We can put numbers smaller than the median on odd indices and the rest on even indices.
[Python3] greedy
minimum-number-of-food-buckets-to-feed-the-hamsters
0
1
\nDownvoters, leave a comment! \n\nFor solutions of biweekly 66, please check out this [commit](https://github.com/gaosanyong/leetcode/commit/2efa877859ad8f79f212b8ebde3edf5730d457ad)\n```\nclass Solution:\n def minimumBuckets(self, street: str) -> int:\n street = list(street)\n ans = 0 \n for i...
12
You are given a **0-indexed** string `hamsters` where `hamsters[i]` is either: * `'H'` indicating that there is a hamster at index `i`, or * `'.'` indicating that index `i` is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at le...
Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?
python 3 | one pass greedy solution | O(n)/O(1)
minimum-number-of-food-buckets-to-feed-the-hamsters
0
1
```\nclass Solution:\n def minimumBuckets(self, street: str) -> int:\n n = len(street)\n buckets = 0\n prevBucket = -2\n for i, c in enumerate(street):\n if c == \'.\' or prevBucket == i - 1:\n continue\n \n buckets += 1\n if i !=...
1
You are given a **0-indexed** string `hamsters` where `hamsters[i]` is either: * `'H'` indicating that there is a hamster at index `i`, or * `'.'` indicating that index `i` is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at le...
Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?
[Python3] pattern match
minimum-number-of-food-buckets-to-feed-the-hamsters
0
1
```python\nclass Solution:\n def minimumBuckets(self, street: str) -> int:\n \n patterns = [\'H.H\', \'.H\', \'H.\', \'H\'] # 4 patterns (excluding \'.\' cuz it costs 0 )\n costs = [1, 1, 1, -1] # corresponding costs\n res = 0\n for p, c in zip(patterns, costs): # firstly, detect \...
2
You are given a **0-indexed** string `hamsters` where `hamsters[i]` is either: * `'H'` indicating that there is a hamster at index `i`, or * `'.'` indicating that index `i` is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at le...
Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?
Basic steps detailed explaination mentioned - Python
minimum-number-of-food-buckets-to-feed-the-hamsters
0
1
\n\n# Approach\nDetailed explaination inline in the code\n\n# Complexity\n- Time complexity:\nO(n+m)\nm - size of list of indices of hamsters\n\n\n# Code\n```\nclass Solution:\n def minimumBuckets(self, hamsters: str) -> int:\n\n #check if there is no empty place in string\n if \'.\' not in hamsters:\n...
0
You are given a **0-indexed** string `hamsters` where `hamsters[i]` is either: * `'H'` indicating that there is a hamster at index `i`, or * `'.'` indicating that index `i` is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at le...
Can we first solve a simpler problem? Counting the number of subsequences with 1s followed by 0s. How can we keep track of the partially matched subsequences to help us find the answer?
One Liner Beats 98.90%
minimum-cost-homecoming-of-a-robot-in-a-grid
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
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
[Python 3] Greedy - Simple + Easy to Understand
minimum-cost-homecoming-of-a-robot-in-a-grid
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 $$O(M + N)$$\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity ...
1
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
EASY SOLUTION in Python with DETAILED EXPLANATION || Beats 95.4%
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the question asks about the minimum cost, You just have to go straight to the Home without any extra moves, by directly changing the position of Robot to required Row and Column accordingly. Do refer to the Hint if you don\'t unders...
3
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
75% TC and 67% SC easy python solution
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
```\ndef minCost(self, startPos: List[int], homePos: List[int], rowC: List[int], colC: List[int]) -> int:\n\tm, n = len(rowC), len(colC)\n\ti1, j1 = startPos\n\ti2, j2 = homePos\n\tans = 0\n\tif(i1 <= i2):\n\t\tfor i in range(i1+1, i2+1):\n\t\t\tans += rowC[i]\n\telse:\n\t\tfor i in range(i1-1, i2-1, -1):\n\t\t\tans +=...
1
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
📌📌 Greedy Approach || Well-Coded and Explained || 95% faster 🐍
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
## IDEA : \n In this Question directly we can find the cost for rows and column from source to target and add in last. \n* From going starting rows to target rows we have to add cost of the up or down path. \n\n* Similarly, for going from starting column to target column we have to add all the costs of coming column ...
3
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
Python 2-liner Beat 97%
minimum-cost-homecoming-of-a-robot-in-a-grid
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:\nO(m + n)\n\n- Space complexity:\nO(1) can be\n\n# Code\n```\nclass Solution:\n def minCost(self, startPos: List[int], homePos: L...
0
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
Python | Simple Solution With Explanation
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
\n# Code\n```\nclass Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n cost = 0\n """\n Since the robot can\'t walk in the diagonals hence whhatever path the robot takes, \n it has to cover all the intermediate rows ...
0
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
Python Solution with Greedy Approach
minimum-cost-homecoming-of-a-robot-in-a-grid
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 is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
python3 1 liner beats 94%
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
\n# Code\n```\nclass Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n return sum(rowCosts[startPos[0]+1:homePos[0]+1]) + sum(colCosts[startPos[1]+1:homePos[1]+1])+sum(rowCosts[homePos[0]:startPos[0]]) + sum(colCosts[homePos[1]:startPos[...
0
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
Python easy sol...
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
# Code\n```\nclass Solution:\n def minCost(self, s: List[int], h: List[int], r: List[int], c: List[int]) -> int:\n res=0\n while s!=h:\n m=float(inf)\n if s[0]<h[0] or s[1]<h[1]:\n if s[0]<h[0]:\n m=min(m,r[s[0]+1])\n s[0]+=1\n ...
0
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
Easy basic solution - Python
minimum-cost-homecoming-of-a-robot-in-a-grid
0
1
\n\n# Approach\nExplained inline in code\n\n# Complexity\n- Time complexity:\nO(n+m)\n\n\n# Code\n```\nclass Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n\n if startPos==homePos:\n return 0\n \n mincost = 0\n...
0
There is an `m x n` grid, where `(0, 0)` is the top-left cell and `(m - 1, n - 1)` is the bottom-right cell. You are given an integer array `startPos` where `startPos = [startrow, startcol]` indicates that **initially**, a **robot** is at the cell `(startrow, startcol)`. You are also given an integer array `homePos` wh...
null
[Python3] just count
count-fertile-pyramids-in-a-land
0
1
Downvoters, leave a comment! \n\nFor solutions of biweekly 66, please check out this [commit](https://github.com/gaosanyong/leetcode/commit/2efa877859ad8f79f212b8ebde3edf5730d457ad)\n```\nclass Solution:\n def countPyramids(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n vals = ...
5
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
Depth First Search Recursive - Dynamic Programming Solution
count-fertile-pyramids-in-a-land
0
1
# Complexity\n- Time complexity: If I don\'t use DP to store results then the TC = m * n * 2^(min(m,n)). With DP our TC is : o(m * n). \n- Because worst case all elements will be fertile. Which means we will get all dp results in the first iteration itself as we traverse through all the land. \n- And for the rema...
0
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
Python DP with clear naming
count-fertile-pyramids-in-a-land
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 farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
Python, DP 97%, 97%
count-fertile-pyramids-in-a-land
0
1
# Intuition\nFirst of all the direct and inverted pyramids are just the same problem, solved with direct and reversed order or rows.\n\n# Approach\nThe smallest pyramind is a single cell (not counted in the result)\nEach pyramid step sits on 3 other overlapping pyramids and can extend below as far as the shortest of th...
0
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
Python3 || Faster than 100% || O(m*n) time || O(n) space || no in-place grid modification
count-fertile-pyramids-in-a-land
0
1
# Intuition\nLarger pyramids contain smaller pyramids suggesting recursion.\n\nThere are two key notions: \nIf a cell hosts some pyramid then it also hosts any pyramid of smaller size. Most solutions look at the apex, while I prefer the base\n\nTo decide if a cell hosts a pyramid of height $H$ we need knowledge about n...
0
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
Python (Simple DP)
count-fertile-pyramids-in-a-land
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 farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
Python3 beats 90% short solution
count-fertile-pyramids-in-a-land
0
1
# Code\n```\nclass Solution:\n def countPyramids(self, G):\n m, n, ans = len(G), len(G[0]), 0\n \n @lru_cache(None)\n def dp(i, j, dr):\n if G[i][j] == 1 and 0 <= i + dr < m and j > 0 and j + 1 < n and G[i+dr][j] == 1:\n return min(dp(i+dr, j-1, dr), dp(i+dr, j+1...
0
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
2 Python Approach - Brute Force to most Optimized Solution
count-fertile-pyramids-in-a-land
1
1
\tclass Solution:\n\t\tdef countPyramids(self, grid: List[List[int]]) -> int:\n\t\t\t#Simple Idea one - Brute Force\n\t\t\t#This will give us tle sometime and sometimes passes\n\t\t\t#F-LC\n\t\t\t"""\n\t\t\tn = len(grid)\n\t\t\tm = len(grid[0])\n\t\t\tprefix = [[0 for _ in range(m+1)] for i in range(n+1)]\n\t\t\tfor i ...
0
A farmer has a **rectangular grid** of land with `m` rows and `n` columns that can be divided into unit cells. Each cell is either **fertile** (represented by a `1`) or **barren** (represented by a `0`). All cells outside the grid are considered barren. A **pyramidal plot** of land can be defined as a set of cells wit...
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
NO SEARCHING | NO SORTING 👑 | BEATS 100%
find-target-indices-after-sorting-array
0
1
# Intuition\nwe dont need actual indices, we dont care about sequence or order so we don\'t need sort.\nbinary search \n# Approach\nJust count number of elements which are less than or equal to given target. say lessThanOrEqualCount\nThen count number of elements which are strictly less than given target onlyLessThanCo...
10
You are given a **0-indexed** integer array `nums` and a target element `target`. A **target index** is an index `i` such that `nums[i] == target`. Return _a list of the target indices of_ `nums` after _sorting_ `nums` _in **non-decreasing** order_. If there are no target indices, return _an **empty** list_. The retu...
Try to use the operation so that each row has only one negative number. If you have only one negative element you cannot convert it to positive.
Python3 || Easy beginner solution.
find-target-indices-after-sorting-array
0
1
# Please upvote if you find the solution helpful\n\n# Code\n```\nclass Solution:\n def targetIndices(self, nums: List[int], target: int) -> List[int]:\n l=[]\n nums.sort()\n for i in range(len(nums)):\n if nums[i]==target:\n l.append(i)\n return l\n ...
4
You are given a **0-indexed** integer array `nums` and a target element `target`. A **target index** is an index `i` such that `nums[i] == target`. Return _a list of the target indices of_ `nums` after _sorting_ `nums` _in **non-decreasing** order_. If there are no target indices, return _an **empty** list_. The retu...
Try to use the operation so that each row has only one negative number. If you have only one negative element you cannot convert it to positive.
Easiest solution in python u will ever find
find-target-indices-after-sorting-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given a **0-indexed** integer array `nums` and a target element `target`. A **target index** is an index `i` such that `nums[i] == target`. Return _a list of the target indices of_ `nums` after _sorting_ `nums` _in **non-decreasing** order_. If there are no target indices, return _an **empty** list_. The retu...
Try to use the operation so that each row has only one negative number. If you have only one negative element you cannot convert it to positive.
2 Lines of Code--->Using BST Logic
find-target-indices-after-sorting-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
You are given a **0-indexed** integer array `nums` and a target element `target`. A **target index** is an index `i` such that `nums[i] == target`. Return _a list of the target indices of_ `nums` after _sorting_ `nums` _in **non-decreasing** order_. If there are no target indices, return _an **empty** list_. The retu...
Try to use the operation so that each row has only one negative number. If you have only one negative element you cannot convert it to positive.
w Explanation||C++/Python/C solutions Sliding Window|| Beats 98.25%
k-radius-subarray-averages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis function calculates sliding window averages for a given input vector nums and window size k. It first checks if there are enough elements in the input vector to form a valid window. If not, it returns a vector with all elements set t...
6
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
Python3 Solution
k-radius-subarray-averages
0
1
\n```\nclass Solution:\n def getAverages(self, nums: List[int], k: int) -> List[int]:\n n=len(nums)\n counts=(2*k+1)\n prefix=[0]\n for x in nums:\n prefix.append(prefix[-1]+x)\n\n ans=[]\n for i in range(n):\n if i-k>=0 and i+k<n:\n ans....
2
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
Sliding_Window.py
k-radius-subarray-averages
0
1
# Approach\nSliding_Window\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n![](https://cdn.hashnode.com/res/hashnode/image/upload/v1653169623956/S71q7bcr7.gif)\n# Code\n```\nclass Solution:\n def getAverages(self, nums: List[int], k: int) -> List[int]:\n a=k ...
4
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
Python3 soln
k-radius-subarray-averages
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHave a helper function that calculates the average and run it through the List for all n items in the array.\n\nHowever, there time limit was exceeded for this initial thought process, hence the solution shifted to having an additional Li...
1
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
Python Easy Code. Beats 90%. O(n)
k-radius-subarray-averages
0
1
# Intuition\n\nSliding window approach will be used to get the sum and change it as we keep propagating with the array. If k==0 we return nums itself. if 2*k + 1 > n : we return [-1]*n (n being len(nums)). Otherwise we calculate average for indexes k to n - k -1.\n\n# Complexity \nO(n)\n\n# Code\n```\nclass Solution:\n...
1
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
Python3, one pass, 100% faster, 53% less mem.
k-radius-subarray-averages
0
1
# Intuition\nJust scan the input.\nKeep track of sum of sliding window sum.\n\n# Approach\n1. start with `[-1, -1, ..., -1]` of size `n`\n2. calculate the initial window sum `s := sum(nums[:r])`\n3. store int(sum / radius)\n4. slide the window by adding element from the right and removing from the left.\n5. repeat from...
1
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
Simple Two Pointers Python3 Solution | O(N) Beats 96.34% | Sliding Window with Detailed Explanation
k-radius-subarray-averages
0
1
Initialized a result array **res** with a length equal to the input array nums, filled with -1s. This array will store the average values of the subarrays. The variables **left** and **windowSum** are initialized to 0, representing the left pointer of the sliding window and the sum of elements within the window, respec...
1
You are given a **0-indexed** array `nums` of `n` integers, and an integer `k`. The **k-radius average** for a subarray of `nums` **centered** at some index `i` with the **radius** `k` is the average of **all** elements in `nums` between the indices `i - k` and `i + k` (**inclusive**). If there are less than `k` eleme...
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
[Python 3] Remove from left, right, both sides || beats 99% || 766ms 🥷🏼
removing-minimum-and-maximum-from-array
0
1
```python3 []\nclass Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n minp, maxp, minel, maxel, L = 0, 0, float(\'inf\'), float(\'-inf\'), len(nums)\n for i, n in enumerate(nums):\n if n > maxel:\n maxel = n\n maxp = i\n if n < minel:...
2
You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array. A **deletion** is de...
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
one liner and easy for beginners
removing-minimum-and-maximum-from-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array. A **deletion** is de...
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
best python3 code beats up to 93%
removing-minimum-and-maximum-from-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBest easy to understand code of python\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n![Screenshot from 2023-07-10 14-53-18.png](https://assets.leetcode.com/users/images/ffe51283-a87a-47d0-b421-b...
2
You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array. A **deletion** is de...
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
Basic nested lf-else(97.54% beats)
removing-minimum-and-maximum-from-array
0
1
# Intuition\nWe need to remove the min and max element from the list in such a way that the no.of deletions is the least. \n\n# Approach\nFor starters we need to find out from which end we need to start out deletions.\n\nFor finding that:\n1)Find out the index\'s of both the elements\n2)Check the distance the extreme e...
1
You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array. A **deletion** is de...
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
python3 solution easy to under stand
removing-minimum-and-maximum-from-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array. A **deletion** is de...
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
Basic Python Solution
removing-minimum-and-maximum-from-array
0
1
simply find the minimum of the two options available. first option is going one way to the larger index and deleting the smaller along the way (consider this from both sides). second option is going from left for the smaller index and going from right for the larger index.\n\n```\nclass Solution:\n def minimumDeleti...
3
You are given a **0-indexed** array of **distinct** integers `nums`. There is an element in `nums` that has the **lowest** value and an element that has the **highest** value. We call them the **minimum** and **maximum** respectively. Your goal is to remove **both** these elements from the array. A **deletion** is de...
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
[Python3] BFS or DFS by group
find-all-people-with-secret
0
1
Pleaes check out this [commit](https://github.com/gaosanyong/leetcode/commit/b3dd8d234940d5e4afc6a22cc8fc1f4a2e69dd3d) for solutions of weekly 269.\n\n```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n can = {0, firstPerson}\n for _, grp ...
29
You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend **multiple meetings** at the same time...
null
📌📌 Really the Simplest answer I came through || BFS or DFS 🐍
find-all-people-with-secret
0
1
## IDEA :\n* Firstly group all the meetings with the key as time on which meeting is happening.\n\n* So one by one go through all the groups (timing by increasing order) and add all the persons to whom secrets got get shared.\n* Here `sh` denotes the persons having secret with them.\n* Going through each group find the...
12
You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend **multiple meetings** at the same time...
null
Python BFS
find-all-people-with-secret
0
1
```\nclass Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n g = defaultdict(dict)\n for p1, p2, t in meetings:\n g[t][p1] = g[t].get(p1, [])\n g[t][p1].append(p2)\n g[t][p2] = g[t].get(p2, [])\n g[t][p2]...
7
You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend **multiple meetings** at the same time...
null
[With Pictures] Easy to Understand Union-Find Approach
find-all-people-with-secret
0
1
**Intuition**\n\nThe key to this problem is observing that:\n1. We need to keep track of all people who know the secret (i.e., this is the disjoint set containing person `0`); and\n2. When we have people meeting at the same time, we will connect the people who meet each other. \n\t* However, this can result in disjoint...
3
You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a **0-indexed** 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend **multiple meetings** at the same time...
null
Three Cycles
finding-3-digit-even-numbers
0
1
**C++**\n```cpp\nvector<int> findEvenNumbers(vector<int>& digits) {\n vector<int> res;\n int cnt[10] = {};\n for (auto d : digits)\n ++cnt[d];\n for (int i = 1; i < 10; ++i)\n for (int j = 0; cnt[i] > 0 && j < 10; ++j)\n for (int k = 0; cnt[j] > (i == j) && k < 10; k += 2)\n ...
73
You are given an integer array `digits`, where each element is a digit. The array may contain duplicates. You need to find **all** the **unique** integers that follow the given requirements: * The integer consists of the **concatenation** of **three** elements from `digits` in **any** arbitrary order. * The integ...
Choose the pile with the maximum number of stones each time. Use a data structure that helps you find the mentioned pile each time efficiently. One such data structure is a Priority Queue.
[Python3] brute-force
finding-3-digit-even-numbers
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b1948f8814bebeca475cbb354cd44d19092dff59) for solutions of weekly 270.\n\n```\nclass Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n ans = set()\n for x, y, z in permutations(digits, 3): \n ...
33
You are given an integer array `digits`, where each element is a digit. The array may contain duplicates. You need to find **all** the **unique** integers that follow the given requirements: * The integer consists of the **concatenation** of **three** elements from `digits` in **any** arbitrary order. * The integ...
Choose the pile with the maximum number of stones each time. Use a data structure that helps you find the mentioned pile each time efficiently. One such data structure is a Priority Queue.
98% Runtime 91% Memory One liner with 3 loops and counter solution
finding-3-digit-even-numbers
0
1
![image.png](https://assets.leetcode.com/users/images/236164b0-aa50-4ef9-a440-6f4fa2cab8ae_1694961637.2136545.png)\n\n\n# Complexity\n- Time complexity: O(1)\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 S...
1
You are given an integer array `digits`, where each element is a digit. The array may contain duplicates. You need to find **all** the **unique** integers that follow the given requirements: * The integer consists of the **concatenation** of **three** elements from `digits` in **any** arbitrary order. * The integ...
Choose the pile with the maximum number of stones each time. Use a data structure that helps you find the mentioned pile each time efficiently. One such data structure is a Priority Queue.
Python - Short & Simple (dict + sorting)
finding-3-digit-even-numbers
0
1
```\ndef findEvenNumbers(self, digits: List[int]) -> List[int]:\n res = []\n dic = Counter(digits) \n for num in range(100,1000,2):\n flag = 0\n for i,j in Counter(str(num)).items():\n if dic[int(i)] < j:\n flag = 1\n if flag == 0:\...
1
You are given an integer array `digits`, where each element is a digit. The array may contain duplicates. You need to find **all** the **unique** integers that follow the given requirements: * The integer consists of the **concatenation** of **three** elements from `digits` in **any** arbitrary order. * The integ...
Choose the pile with the maximum number of stones each time. Use a data structure that helps you find the mentioned pile each time efficiently. One such data structure is a Priority Queue.
[Python] Simple HashMap Solution, O(n)
finding-3-digit-even-numbers
0
1
* We need 3 digit numbers so we travese form 100 to 999\n* For every num in range we check if its digits are in digits array and frequency of its digits is less than or equal to frequency of digits in digits array.\n```\nclass Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n hmap, res ...
8
You are given an integer array `digits`, where each element is a digit. The array may contain duplicates. You need to find **all** the **unique** integers that follow the given requirements: * The integer consists of the **concatenation** of **three** elements from `digits` in **any** arbitrary order. * The integ...
Choose the pile with the maximum number of stones each time. Use a data structure that helps you find the mentioned pile each time efficiently. One such data structure is a Priority Queue.
Beats 100% || Detailed explanation || Two pointer || [Java/C++/Python]
delete-the-middle-node-of-a-linked-list
1
1
# Intuition\n1. If a point with a speed s moves n units in a given time, a point with speed 2 * s will move 2 * n units at the same time. It means when a pointer with 2*s speed reaches the end, the pointer will s speed will be at exactly the mid point.\n\n# Approach\n1. **Base Case Check:**\n - If the linked list is...
2
You are given the `head` of a linked list. **Delete** the **middle node**, and return _the_ `head` _of the modified linked list_. The **middle node** of a linked list of size `n` is the `⌊n / 2⌋th` node from the **start** using **0-based indexing**, where `⌊x⌋` denotes the largest integer less than or equal to `x`. *...
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
✅✅✅Easy python3 solution.
delete-the-middle-node-of-a-linked-list
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given the `head` of a linked list. **Delete** the **middle node**, and return _the_ `head` _of the modified linked list_. The **middle node** of a linked list of size `n` is the `⌊n / 2⌋th` node from the **start** using **0-based indexing**, where `⌊x⌋` denotes the largest integer less than or equal to `x`. *...
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
Beat 100% - Easy to understand and implement - DFS
step-by-step-directions-from-a-binary-tree-node-to-another
0
1
# Intuition\nFind a path from the root to the start node and another path from the root to the destination node. Identify the node where these two paths intersect. Then, add the path from that node to the start value and the path from that node to the destination value to the result.\n\n![BinArray.png](https://assets.l...
3
You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. Find the **shortest path...
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
3 Steps
step-by-step-directions-from-a-binary-tree-node-to-another
1
1
1. Build directions for both start and destination from the root.\n\t- Say we get "LLRRL" and "LRR".\n2. Remove common prefix path.\n\t- We remove "L", and now start direction is "LRRL", and destination - "RR"\n3. Replace all steps in the start direction to "U" and add destination direction.\n\t- The result is "UUUU" +...
775
You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. Find the **shortest path...
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
[Python3] lca
step-by-step-directions-from-a-binary-tree-node-to-another
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b1948f8814bebeca475cbb354cd44d19092dff59) for solutions of weekly 270.\n\n```\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \n def lca(node): \n """R...
120
You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. Find the **shortest path...
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
Python3 BFS
step-by-step-directions-from-a-binary-tree-node-to-another
0
1
\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -...
1
You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. Find the **shortest path...
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
Python3 || easiest explanation|| LCA Method
step-by-step-directions-from-a-binary-tree-node-to-another
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Find common parent and navigate.**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- find least common parent of start and destination.\n- now find height of start from lca.\n- append hheight times \'U\' in answe...
2
You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. Find the **shortest path...
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
2 Python 🐍 solutions: Graph-based, LCA
step-by-step-directions-from-a-binary-tree-node-to-another
0
1
#### **Solution 1: Graph Based, passed**\n#### Space=O(N) for building graph and queue. Time= O(N) for traversing the tree and for the BFS\nThe idea is build an undirected graph, the directions from Node1--> Node2 is either L or R, and the opposite Node2-->1 is always U\n```\nclass Solution:\n def getDirections(self...
19
You are given the `root` of a **binary tree** with `n` nodes. Each node is uniquely assigned a value from `1` to `n`. You are also given an integer `startValue` representing the value of the start node `s`, and a different integer `destValue` representing the value of the destination node `t`. Find the **shortest path...
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
[Python3] Hierholzer's algo
valid-arrangement-of-pairs
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/b1948f8814bebeca475cbb354cd44d19092dff59) for solutions of weekly 270.\n\n```\nclass Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n graph = defaultdict(list)\n degree = defaultdict(int) # ...
39
You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`. Return _**any** valid arrangement of_ `pairs`. **Note:** The inputs will be generated such that there exist...
null
Eulerian path linear time
valid-arrangement-of-pairs
0
1
Read this tutorial on Eulerian path for undirected graph https://cp-algorithms.com/graph/euler_path.html\n\nThe algorithm can be extended to directed graph by looking at indegrees and outdegrees as described here https://math.stackexchange.com/a/2433946\n\nThe idea is we check if the graph makes an Eulerian cycle or pa...
0
You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`. Return _**any** valid arrangement of_ `pairs`. **Note:** The inputs will be generated such that there exist...
null
Eulerian Circuit
valid-arrangement-of-pairs
0
1
Almost same as Q332, but the key point here is where to start.\n\nIf there is no eulerian cycle, there must be a point where there is one more vertex out than vertexes in, which is where we should start. If not such point exists, then there must be a eulerian cycle, in which case we may start anywhere we want.\n\n# Cod...
0
You are given a **0-indexed** 2D integer array `pairs` where `pairs[i] = [starti, endi]`. An arrangement of `pairs` is **valid** if for every index `i` where `1 <= i < pairs.length`, we have `endi-1 == starti`. Return _**any** valid arrangement of_ `pairs`. **Note:** The inputs will be generated such that there exist...
null