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
🚀🔥Leetcode 1218 | Python Solution + Video Tutorial 🎯🐍
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\nhttps://youtu.be/Ho7uSMTguCU\n<!-- Describe your first thoughts on how to solve this problem. -->\n\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# Code\n```\nclass Solution:...
8
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
[Python] it's all about expectations (explained)
longest-arithmetic-subsequence-of-given-difference
0
1
The key idea here is to maintain a dictionary with:\n1. **keys** being the numbers that we *expect* to encounter in order to increase subsequence, and \n2. the respective **values** representing lengths of currently constructed subsequences.\n\nEvery time we hit one of the expected numbers `n`, we increase the subseque...
7
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
[Python] it's all about expectations (explained)
longest-arithmetic-subsequence-of-given-difference
0
1
The key idea here is to maintain a dictionary with:\n1. **keys** being the numbers that we *expect* to encounter in order to increase subsequence, and \n2. the respective **values** representing lengths of currently constructed subsequences.\n\nEvery time we hit one of the expected numbers `n`, we increase the subseque...
7
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
4 Line Python || HashMap + DP || Two Sum Variation
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\nMain Intuition comes from problem "Two Sum"\n\n# Approach\nSimply Hash previously seen values and the count of ongoing AP Length\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n ...
5
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
4 Line Python || HashMap + DP || Two Sum Variation
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\nMain Intuition comes from problem "Two Sum"\n\n# Approach\nSimply Hash previously seen values and the count of ongoing AP Length\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n ...
5
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Easiest python solution using Default Dict best approach for begginers
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to use a dynamic programming approach to calculate the length of subsequences ending at each element of the array. By keeping track of the lengths of subsequences, we can determine the longest subsequence with the required dif...
4
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Easiest python solution using Default Dict best approach for begginers
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to use a dynamic programming approach to calculate the length of subsequences ending at each element of the array. By keeping track of the lengths of subsequences, we can determine the longest subsequence with the required dif...
4
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
[Python, Java] Elegant & Short | DP | HashMap
longest-arithmetic-subsequence-of-given-difference
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n\n```python []\nclass Solution:\n def longestSubsequence(self, nums: List[int], difference: int) -> int:\n dp = defaultdict(int)\n\n for num in nums:\n dp[num] = dp[num - difference] + 1\n\n return max(...
3
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
[Python, Java] Elegant & Short | DP | HashMap
longest-arithmetic-subsequence-of-given-difference
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n\n```python []\nclass Solution:\n def longestSubsequence(self, nums: List[int], difference: int) -> int:\n dp = defaultdict(int)\n\n for num in nums:\n dp[num] = dp[num - difference] + 1\n\n return max(...
3
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
longest-arithmetic-subsequence-of-given-difference
1
1
# Intuition\nUse Dynamic Programming to store the longest length of subsequence at each number.\n\n# Solution Video\nPlease subscribe to my channel from here. I have 222 LeetCode videos as of July 15th, 2023.\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nhttps://youtu.be/Yi2hGxQsL6Y\n\n...
6
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++
longest-arithmetic-subsequence-of-given-difference
1
1
# Intuition\nUse Dynamic Programming to store the longest length of subsequence at each number.\n\n# Solution Video\nPlease subscribe to my channel from here. I have 222 LeetCode videos as of July 15th, 2023.\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nhttps://youtu.be/Yi2hGxQsL6Y\n\n...
6
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
✔️ Python || Short solution || Detailed explanation || DP
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\nLet\'s say the next element for the subsequence will be: `arr[i] + difference`.\nWhen we go through array we need to store this next elements, because if we will met them, than we can add them to subsequence. \n# Approach\n\nLet\'s create a hashtable (dict) with the next structure:\n - key \u2013 next v...
2
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
✔️ Python || Short solution || Detailed explanation || DP
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\nLet\'s say the next element for the subsequence will be: `arr[i] + difference`.\nWhen we go through array we need to store this next elements, because if we will met them, than we can add them to subsequence. \n# Approach\n\nLet\'s create a hashtable (dict) with the next structure:\n - key \u2013 next v...
2
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
🔥Memoization(✅) + Bottom UP || 🔥[C++,JAVA,🐍] || ✅DP + Hashing⭐
longest-arithmetic-subsequence-of-given-difference
1
1
### Connect with me on LinkedIN : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n# Approach(For BottomUP)\n\n1. Initialize a variable `ans` to 0. This variable will store the length of the longest subsequence.\n2. Create an unordered map `mp`. This map will store the count of subsequences ending at each el...
2
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
🔥Memoization(✅) + Bottom UP || 🔥[C++,JAVA,🐍] || ✅DP + Hashing⭐
longest-arithmetic-subsequence-of-given-difference
1
1
### Connect with me on LinkedIN : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n# Approach(For BottomUP)\n\n1. Initialize a variable `ans` to 0. This variable will store the length of the longest subsequence.\n2. Create an unordered map `mp`. This map will store the count of subsequences ending at each el...
2
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Simple C++/Python with unordered_map/dict
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse hash table to record dp[x]=maximal length of the arithmetic progression ending at the number x.\nThe crucial recurrence is: dp[x]=1+dp[x-difference]\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse a loop to...
2
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Simple C++/Python with unordered_map/dict
longest-arithmetic-subsequence-of-given-difference
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse hash table to record dp[x]=maximal length of the arithmetic progression ending at the number x.\nThe crucial recurrence is: dp[x]=1+dp[x-difference]\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse a loop to...
2
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Easy solution with time complexity O(n)
longest-arithmetic-subsequence-of-given-difference
0
1
# Complexity\n![Screenshot 2023-07-15 at 00.08.49.png](https://assets.leetcode.com/users/images/07d1dbe1-7977-492a-8156-da0a4f021cb2_1689369025.5775528.png)\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: in...
1
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Easy solution with time complexity O(n)
longest-arithmetic-subsequence-of-given-difference
0
1
# Complexity\n![Screenshot 2023-07-15 at 00.08.49.png](https://assets.leetcode.com/users/images/07d1dbe1-7977-492a-8156-da0a4f021cb2_1689369025.5775528.png)\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def longestSubsequence(self, arr: List[int], difference: in...
1
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Python3 👍||⚡98/93 faster beats,only 4 lines 🔥|| clean solution ||
longest-arithmetic-subsequence-of-given-difference
0
1
![image.png](https://assets.leetcode.com/users/images/386c35a6-a4df-4515-9251-2505d643efaf_1689335102.765021.png)\n\n\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 So...
1
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Python3 👍||⚡98/93 faster beats,only 4 lines 🔥|| clean solution ||
longest-arithmetic-subsequence-of-given-difference
0
1
![image.png](https://assets.leetcode.com/users/images/386c35a6-a4df-4515-9251-2505d643efaf_1689335102.765021.png)\n\n\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 So...
1
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Go/Python O(n) time | O(n) space
longest-arithmetic-subsequence-of-given-difference
0
1
# 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```golang []\nfunc longestSubsequence(arr []int, difference int) int {\n dp := make(map[int]int)\n answer := 1\n fo...
1
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Go/Python O(n) time | O(n) space
longest-arithmetic-subsequence-of-given-difference
0
1
# 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```golang []\nfunc longestSubsequence(arr []int, difference int) int {\n dp := make(map[int]int)\n answer := 1\n fo...
1
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Dict.py
longest-arithmetic-subsequence-of-given-difference
0
1
# Code\n```\nclass Solution:\n def longestSubsequence(self, arr: List[int], dif: int) -> int:\n m={}\n mx=0\n for i in range(len(arr)):\n val=arr[i]\n if val-dif in m:\n m[val]=m[val-dif]+1\n else:\n m[val]=1\n mx=max(mx,m...
1
Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`. A **subsequence** is a sequence that can be derived from `arr` by deleting some or n...
Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer.
Dict.py
longest-arithmetic-subsequence-of-given-difference
0
1
# Code\n```\nclass Solution:\n def longestSubsequence(self, arr: List[int], dif: int) -> int:\n m={}\n mx=0\n for i in range(len(arr)):\n val=arr[i]\n if val-dif in m:\n m[val]=m[val-dif]+1\n else:\n m[val]=1\n mx=max(mx,m...
1
You are given an integer array `nums`. The _value_ of this array is defined as the sum of `|nums[i] - nums[i + 1]|` for all `0 <= i < nums.length - 1`. You are allowed to select any subarray of the given array and reverse it. You can perform this operation **only once**. Find maximum possible value of the final array...
Use dynamic programming. Let dp[i] be the maximum length of a subsequence of the given difference whose last element is i. dp[i] = 1 + dp[i-k]
Fast DFS with back-tracking
path-with-maximum-gold
0
1
# Intuition\n- Given the requirements, it\'s a classical and straight forward back-tracking question.\n- Most of the solutions are not making a somewhat SAFE assumption given the current set of test cases that we\'re likely to start at the boundary and spiral down inwards. \n- I added that logic and voila it passed t...
0
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your posi...
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Fast DFS with back-tracking
path-with-maximum-gold
0
1
# Intuition\n- Given the requirements, it\'s a classical and straight forward back-tracking question.\n- Most of the solutions are not making a somewhat SAFE assumption given the current set of test cases that we\'re likely to start at the boundary and spiral down inwards. \n- I added that logic and voila it passed t...
0
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
[Python3] DFS
path-with-maximum-gold
0
1
```\nclass Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int:\n def dfs(i, j, v):\n seen.add((i, j))\n dp[i][j] = max(dp[i][j], v)\n for x, y in (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1):\n if 0 <= x < m and 0 <= y < n and grid[x][y] and (x...
27
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your posi...
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
[Python3] DFS
path-with-maximum-gold
0
1
```\nclass Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int:\n def dfs(i, j, v):\n seen.add((i, j))\n dp[i][j] = max(dp[i][j], v)\n for x, y in (i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1):\n if 0 <= x < m and 0 <= y < n and grid[x][y] and (x...
27
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
✅⬆️⬆️🔥🔥100% | 0MS | FASTER | CONCISE | DFS | PROOF ⬆️⬆️⬆️⬆️🔥🙌
path-with-maximum-gold
1
1
# UPVOTE PLS\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# 5*5=25 possiblities use as accumulator & update flag\n<!-- Describe your approach to solving the problem. -->\n![image.png](https://assets.leetcode.com/users/images/a59d0548-3375-47c5-9d5a-e9b98cbceb8f_1673159038.8290944.png)\n\n# Co...
3
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your posi...
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
✅⬆️⬆️🔥🔥100% | 0MS | FASTER | CONCISE | DFS | PROOF ⬆️⬆️⬆️⬆️🔥🙌
path-with-maximum-gold
1
1
# UPVOTE PLS\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# 5*5=25 possiblities use as accumulator & update flag\n<!-- Describe your approach to solving the problem. -->\n![image.png](https://assets.leetcode.com/users/images/a59d0548-3375-47c5-9d5a-e9b98cbceb8f_1673159038.8290944.png)\n\n# Co...
3
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
Python3 | Backtracking
path-with-maximum-gold
0
1
Not a very very fast solution (the runtime is about 5xxx ms) but it may help you understand a pattern easily. \n\n```\nclass Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int: \n m, n = len(grid), len(grid[0])\n \n def helper(i, j, visited):\n if i < 0 or i >= m or j ...
1
In a gold mine `grid` of size `m x n`, each cell in this mine has an integer representing the amount of gold in that cell, `0` if it is empty. Return the maximum amount of gold you can collect under the conditions: * Every time you are located in a cell you will collect all the gold in that cell. * From your posi...
Make a new array A of +1/-1s corresponding to if hours[i] is > 8 or not. The goal is to find the longest subarray with positive sum. Using prefix sums (PrefixSum[i+1] = A[0] + A[1] + ... + A[i]), you need to find for each j, the smallest i < j with PrefixSum[i] + 1 == PrefixSum[j].
Python3 | Backtracking
path-with-maximum-gold
0
1
Not a very very fast solution (the runtime is about 5xxx ms) but it may help you understand a pattern easily. \n\n```\nclass Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int: \n m, n = len(grid), len(grid[0])\n \n def helper(i, j, visited):\n if i < 0 or i >= m or j ...
1
Given an array of integers `arr`, replace each element with its rank. The rank represents how large the element is. The rank has the following rules: * Rank is an integer starting from 1. * The larger the element, the larger the rank. If two elements are equal, their rank must be the same. * Rank should be as s...
Use recursion to try all such paths and find the one with the maximum value.
✅ Beats 97.08% 🔥 || 2 Approaches of DP ||
count-vowels-permutation
1
1
# Approach 1: Tabulation with O(n) Space\n![image.png](https://assets.leetcode.com/users/images/6b2dd784-e4ab-4200-bbaa-e46fa7855ad1_1698465755.9225202.png)\n\n# Intuition :\n**If we know the number of strings of length n - 1, for each of the vowels ending in each of the vowels, then we can know the number of strings o...
6
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
✅ Beats 97.08% 🔥 || 2 Approaches of DP ||
count-vowels-permutation
1
1
# Approach 1: Tabulation with O(n) Space\n![image.png](https://assets.leetcode.com/users/images/6b2dd784-e4ab-4200-bbaa-e46fa7855ad1_1698465755.9225202.png)\n\n# Intuition :\n**If we know the number of strings of length n - 1, for each of the vowels ending in each of the vowels, then we can know the number of strings o...
6
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++
count-vowels-permutation
1
1
# Intuition\nJust follow the rules lol\n\n---\n\n# Solution Video\n\nhttps://youtu.be/SFm0hhVCjl8\n\n\u25A0 Timeline of the video\n`0:04` Convert rules to a diagram\n`1:14` How do you count strings with length of n?\n`3:58` Coding\n`7:39` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forge...
12
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++
count-vowels-permutation
1
1
# Intuition\nJust follow the rules lol\n\n---\n\n# Solution Video\n\nhttps://youtu.be/SFm0hhVCjl8\n\n\u25A0 Timeline of the video\n`0:04` Convert rules to a diagram\n`1:14` How do you count strings with length of n?\n`3:58` Coding\n`7:39` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forge...
12
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
🚀 100% || Easy Iterative Approach || Explained Intuition 🚀
count-vowels-permutation
1
1
# Porblem Description\nGiven an integer `n`, The task is to **determine** the number of **valid** strings of length `n` that can be formed based on a specific set of **rules**. \n\n- The rules for forming these strings are as follows:\n - Each character in the string must be a lowercase vowel, which includes \'a\', ...
32
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
🚀 100% || Easy Iterative Approach || Explained Intuition 🚀
count-vowels-permutation
1
1
# Porblem Description\nGiven an integer `n`, The task is to **determine** the number of **valid** strings of length `n` that can be formed based on a specific set of **rules**. \n\n- The rules for forming these strings are as follows:\n - Each character in the string must be a lowercase vowel, which includes \'a\', ...
32
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Python3 Solution
count-vowels-permutation
0
1
\n```\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n mod=10**9+7\n dp=[[],[1,1,1,1,1]]\n a,e,i,o,u=0,1,2,3,4\n for j in range(2,n+1):\n dp.append([0,0,0,0,0])\n dp[j][a]=(dp[j-1][e]+dp[j-1][i]+dp[j-1][u])\n dp[j][e]=(dp[j-1][a]+dp[j-1...
3
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
Python3 Solution
count-vowels-permutation
0
1
\n```\nclass Solution:\n def countVowelPermutation(self, n: int) -> int:\n mod=10**9+7\n dp=[[],[1,1,1,1,1]]\n a,e,i,o,u=0,1,2,3,4\n for j in range(2,n+1):\n dp.append([0,0,0,0,0])\n dp[j][a]=(dp[j-1][e]+dp[j-1][i]+dp[j-1][u])\n dp[j][e]=(dp[j-1][a]+dp[j-1...
3
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
🔥🚀Beats 100% | 🚩Basic Simple Math Approach | 🧭Time - O(n), Space O(1) | 🔥Optimised Approach
count-vowels-permutation
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis solution is based on a mathematical approach to count the number of valid strings of length \'n\' that can be formed using the given vowel rules. The idea is to iteratively calculate the number of valid strings for each vowel at each...
5
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
🔥🚀Beats 100% | 🚩Basic Simple Math Approach | 🧭Time - O(n), Space O(1) | 🔥Optimised Approach
count-vowels-permutation
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis solution is based on a mathematical approach to count the number of valid strings of length \'n\' that can be formed using the given vowel rules. The idea is to iteratively calculate the number of valid strings for each vowel at each...
5
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
✅ 98.55% DP Transition Matrix
count-vowels-permutation
1
1
# Intuition\n\nThe essence of this problem lies in the transitions between vowels and how they form sequences. Given the constraints, not every vowel can follow every other vowel. This forms a sort of directed graph where each vowel points to the vowels it can be followed by. As we\'re tasked with counting the number o...
88
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
✅ 98.55% DP Transition Matrix
count-vowels-permutation
1
1
# Intuition\n\nThe essence of this problem lies in the transitions between vowels and how they form sequences. Given the constraints, not every vowel can follow every other vowel. This forms a sort of directed graph where each vowel points to the vowels it can be followed by. As we\'re tasked with counting the number o...
88
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
2D DP solution in Python by Akash Sinha
count-vowels-permutation
0
1
# Intuition\nLooking at the problem statement, the first thing which comes to mind is go for a recursive solution based on the constraints of alphabets.\n\n# Approach\n def f(s,n):\n if(n==0):\n return 1\n elif(s==\'\'):\n return f(\'a\',n-1)+f(\'e\',n-1)+f(\'i\',n-1)+f(\'o\',n-1)...
2
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
2D DP solution in Python by Akash Sinha
count-vowels-permutation
0
1
# Intuition\nLooking at the problem statement, the first thing which comes to mind is go for a recursive solution based on the constraints of alphabets.\n\n# Approach\n def f(s,n):\n if(n==0):\n return 1\n elif(s==\'\'):\n return f(\'a\',n-1)+f(\'e\',n-1)+f(\'i\',n-1)+f(\'o\',n-1)...
2
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
✅☑[C++/Java/Python/JavaScript] || EXPLAINED🔥
count-vowels-permutation
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n1. The countVowelPermutation function is the main entry point to calculate the number of valid permutations of vowels for a given length `n`.\n\n1. The `mp` unordered_map stores information about possible vowel transitions. For eac...
2
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
✅☑[C++/Java/Python/JavaScript] || EXPLAINED🔥
count-vowels-permutation
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n1. The countVowelPermutation function is the main entry point to calculate the number of valid permutations of vowels for a given length `n`.\n\n1. The `mp` unordered_map stores information about possible vowel transitions. For eac...
2
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Dyamic programming, constant space solution, EXPLAINED
count-vowels-permutation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen you think about solving this question brute force you will be forced to find all ways in which we can construct a string of length \'n\'. When we think of finding all ways of something, dynamic programming comes to mind.\nTherefore, ...
1
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
Dyamic programming, constant space solution, EXPLAINED
count-vowels-permutation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen you think about solving this question brute force you will be forced to find all ways in which we can construct a string of length \'n\'. When we think of finding all ways of something, dynamic programming comes to mind.\nTherefore, ...
1
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
🔥99% Beats DP & 🔥100% Beats🔥 Matrix Exponentiation | 🔥 Explained Intuition & Approach |
count-vowels-permutation
1
1
# 1st Method : Bottom-Up Dynamic Programming \uD83D\uDD25\n## Intuition \uD83D\uDE80:\nThe problem asks you to count the number of valid strings of length `n` using the given rules for vowel transitions. You can think of this as a dynamic programming problem where you calculate the number of valid strings of different ...
43
Given an integer `n`, your task is to count how many strings of length `n` can be formed under the following rules: * Each character is a lower case vowel (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) * Each vowel `'a'` may only be followed by an `'e'`. * Each vowel `'e'` may only be followed by an `'a'` or an `'i'`. * ...
Do a bitmask DP. For each person, for each set of skills, we can update our understanding of a minimum set of people needed to perform this set of skills.
🔥99% Beats DP & 🔥100% Beats🔥 Matrix Exponentiation | 🔥 Explained Intuition & Approach |
count-vowels-permutation
1
1
# 1st Method : Bottom-Up Dynamic Programming \uD83D\uDD25\n## Intuition \uD83D\uDE80:\nThe problem asks you to count the number of valid strings of length `n` using the given rules for vowel transitions. You can think of this as a dynamic programming problem where you calculate the number of valid strings of different ...
43
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters o...
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Shortest solution, enjoy
split-a-string-in-balanced-strings
0
1
\n# Code\n```\nclass Solution:\n def balancedStringSplit(self, s: str) -> int:\n count, ans = 0, 0\n\n for char in s:\n count += 1 if char == \'R\' else -1\n ans += count == 0\n\n return ans\n\n```\nplease upvote :D
4
**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. Given a **balanced** string `s`, split it into some number of substrings such that: * Each substring is balanced. Return _the **maximum** number of balanced strings you can obtain._ **Example 1:** **Input:** s = "RLRRLLRLR...
Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.
Python3 O(N) - Stack Greedy Algorithm Approach beats 99.9%
split-a-string-in-balanced-strings
0
1
```\nclass Solution:\n def balancedStringSplit(self, s: str) -> int:\n stack, result = [], 0\n \n for char in s: \n if stack == []:\n stack.append(char)\n result += 1\n elif char == stack[-1]:\n stack.a...
3
**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. Given a **balanced** string `s`, split it into some number of substrings such that: * Each substring is balanced. Return _the **maximum** number of balanced strings you can obtain._ **Example 1:** **Input:** s = "RLRRLLRLR...
Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.
Python one-line (99.31%)
split-a-string-in-balanced-strings
0
1
Summary of algo:\n1) set a flag to zero and loop through characters in string;\n2) if char is `R`, add flag by 1; if char is `L`, subtract 1 from flag;\n3) add 1 to counter whenever flag is 0.\nOne-line implementation utilizing accumulate function is below. \n```\nfrom itertools import accumulate\n\nclass Solution:\n ...
44
**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. Given a **balanced** string `s`, split it into some number of substrings such that: * Each substring is balanced. Return _the **maximum** number of balanced strings you can obtain._ **Example 1:** **Input:** s = "RLRRLLRLR...
Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.
Python 3 (three lines) (beats 100.00 %)
split-a-string-in-balanced-strings
0
1
_Six Line Version:_\n```\nclass Solution:\n def balancedStringSplit(self, S: str) -> int:\n m = c = 0\n for s in S:\n if s == \'L\': c += 1\n if s == \'R\': c -= 1\n if c == 0: m += 1\n return m\n\n\n```\n_Three Line Version:_\n```\nclass Solution:\n def balan...
42
**Balanced** strings are those that have an equal quantity of `'L'` and `'R'` characters. Given a **balanced** string `s`, split it into some number of substrings such that: * Each substring is balanced. Return _the **maximum** number of balanced strings you can obtain._ **Example 1:** **Input:** s = "RLRRLLRLR...
Divide the array in four parts [1 - 25%] [25 - 50 %] [50 - 75 %] [75% - 100%] The answer should be in one of the ends of the intervals. In order to check which is element is the answer we can count the frequency with binarySearch.
python || easy to understand || with comments || begineer friendly
queens-that-can-attack-the-king
0
1
```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n board = [[\'\' for i in range(8)] for j in range(8)]\n ans = []\n \n # marking queens position on board\n for queen in queens:\n board[queen[0]][queen[1]]...
1
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
python || easy to understand || with comments || begineer friendly
queens-that-can-attack-the-king
0
1
```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n board = [[\'\' for i in range(8)] for j in range(8)]\n ans = []\n \n # marking queens position on board\n for queen in queens:\n board[queen[0]][queen[1]]...
1
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
Easy Python Code | Long But Easy Approach ✔
queens-that-can-attack-the-king
0
1
Python3 Solution\n\n# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n l=[]\n #to traverse in straight left of king\'s position\n for i in range(king[1],-1,-1):\n if [king[0],i] in queens:\n l.app...
2
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
Easy Python Code | Long But Easy Approach ✔
queens-that-can-attack-the-king
0
1
Python3 Solution\n\n# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n l=[]\n #to traverse in straight left of king\'s position\n for i in range(king[1],-1,-1):\n if [king[0],i] in queens:\n l.app...
2
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
100% faster | Moving each direction separately | Python
queens-that-can-attack-the-king
0
1
![image](https://assets.leetcode.com/users/images/7bdf2c5b-7c89-4215-b9e1-df7dcc196df2_1669825212.6354399.png)\n```\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n ans = []\n for i in range(king[0] - 1, -1, -1):\n if [i, king[1]] in queens:\n ans.appe...
2
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
100% faster | Moving each direction separately | Python
queens-that-can-attack-the-king
0
1
![image](https://assets.leetcode.com/users/images/7bdf2c5b-7c89-4215-b9e1-df7dcc196df2_1669825212.6354399.png)\n```\nclass Solution(object):\n def queensAttacktheKing(self, queens, king):\n ans = []\n for i in range(king[0] - 1, -1, -1):\n if [i, king[1]] in queens:\n ans.appe...
2
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
Python3 simple O(N) solution with DFS (99.47% Runtime)
queens-that-can-attack-the-king
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/f907a276-d31a-4299-b5c4-0fcd965fd4dc_1702972299.649907.png)\nUtilize recursive depth first search to find all 8 directions\n\n# Approach\n<!-- Describe your approach to solving the pro...
0
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
Python3 simple O(N) solution with DFS (99.47% Runtime)
queens-that-can-attack-the-king
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/f907a276-d31a-4299-b5c4-0fcd965fd4dc_1702972299.649907.png)\nUtilize recursive depth first search to find all 8 directions\n\n# Approach\n<!-- Describe your approach to solving the pro...
0
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
python3, sparse board beats 99.5%
queens-that-can-attack-the-king
0
1
# Intuition\na relevant queen must be either\n- in the same diagonal as the king \n- have the same x or same y position as the king\n\nin addition to that you need to check, if any other queen is standing between the queen and the king. So you need to move the queen forward, towards the king and check if it is stepping...
0
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
python3, sparse board beats 99.5%
queens-that-can-attack-the-king
0
1
# Intuition\na relevant queen must be either\n- in the same diagonal as the king \n- have the same x or same y position as the king\n\nin addition to that you need to check, if any other queen is standing between the queen and the king. So you need to move the queen forward, towards the king and check if it is stepping...
0
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
✅BFS || python
queens-that-can-attack-the-king
0
1
# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans=[]\n d={}\n for l in queens:\n d[(l[0],l[1])]=1\n q=[]\n q.append([king[0],king[1],0,1])\n q.append([king[0],king[1],0,-1])\n q....
0
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
✅BFS || python
queens-that-can-attack-the-king
0
1
# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n ans=[]\n d={}\n for l in queens:\n d[(l[0],l[1])]=1\n q=[]\n q.append([king[0],king[1],0,1])\n q.append([king[0],king[1],0,-1])\n q....
0
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
Easy to understand Python3 solution
queens-that-can-attack-the-king
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
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
Easy to understand Python3 solution
queens-that-can-attack-the-king
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 `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
Easy 10 Line Code |||| Must see
queens-that-can-attack-the-king
1
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
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
Easy 10 Line Code |||| Must see
queens-that-can-attack-the-king
1
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 `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
a 13-lines readable solution with clear comment
queens-that-can-attack-the-king
0
1
# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n # define directions\n dirs = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]\n\n # set has faster search performance than list\n qs = {(q[0],...
0
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing...
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
a 13-lines readable solution with clear comment
queens-that-can-attack-the-king
0
1
# Code\n```\nclass Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n # define directions\n dirs = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]\n\n # set has faster search performance than list\n qs = {(q[0],...
0
Given an integer `num`, return _the number of steps to reduce it to zero_. In one step, if the current number is even, you have to divide it by `2`, otherwise, you have to subtract `1` from it. **Example 1:** **Input:** num = 14 **Output:** 6 **Explanation:** Step 1) 14 is even; divide by 2 and obtain 7. Step 2) 7...
Check 8 directions around the King. Find the nearest queen in each direction.
✔ Python3 Solution | O(n) Time & Space | DP
dice-roll-simulation
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Solution 1\n```\nclass Solution:\n def dieSimulator(self, n, A):\n dp = [[0] * 7 for _ in range(n + 1)]\n dp[0][-1] = 1\n for i in range(1, n + 1):\n for j in range(6):\n dp[i][j] = dp[i - 1][-...
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.
✔ Python3 Solution | O(n) Time & Space | DP
dice-roll-simulation
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Solution 1\n```\nclass Solution:\n def dieSimulator(self, n, A):\n dp = [[0] * 7 for _ in range(n + 1)]\n dp[0][-1] = 1\n for i in range(1, n + 1):\n for j in range(6):\n dp[i][j] = dp[i - 1][-...
3
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
Python 3: TC O(N), SC O(N): Dynamic Programming with "rollMax Correction"
dice-roll-simulation
0
1
# Intuition\n\nMy first attempt (commented out) was a VERY brute-force top-down DFS solution. It works, but is fairly slow. Vastly slower than this solution. The reason is it\'s not very clever about avoiding the max sequence length.\n\nSo I looked at some other solutions and didn\'t understand for a while.\n\nHere\'s ...
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.
Python 3: TC O(N), SC O(N): Dynamic Programming with "rollMax Correction"
dice-roll-simulation
0
1
# Intuition\n\nMy first attempt (commented out) was a VERY brute-force top-down DFS solution. It works, but is fairly slow. Vastly slower than this solution. The reason is it\'s not very clever about avoiding the max sequence length.\n\nSo I looked at some other solutions and didn\'t understand for a while.\n\nHere\'s ...
0
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
SImple DP in python3 from front to rear, O(n*max(rollMax))
dice-roll-simulation
0
1
# Code\n```\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n @cache\n def dp(pos,last,lc):\n res = 0\n if pos > n:\n return 1 #exit case\n for i in range(1,7):\n if i !=last:\n res += dp(pos...
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.
SImple DP in python3 from front to rear, O(n*max(rollMax))
dice-roll-simulation
0
1
# Code\n```\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n @cache\n def dp(pos,last,lc):\n res = 0\n if pos > n:\n return 1 #exit case\n for i in range(1,7):\n if i !=last:\n res += dp(pos...
0
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
Python 3: DP Bottom Up, Tabular solution
dice-roll-simulation
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.
Python 3: DP Bottom Up, Tabular solution
dice-roll-simulation
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 array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
Fast and space efficient solution
dice-roll-simulation
0
1
\n# Code\n```\nP = 1_000_000_007\n\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n states = [[0]*(min(mr, n)-1)+[1] for mr in rollMax]\n totals = [1]*len(rollMax)\n total = len(rollMax)\n indices = [0]*len(rollMax)\n for _ in range(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.
Fast and space efficient solution
dice-roll-simulation
0
1
\n# Code\n```\nP = 1_000_000_007\n\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n states = [[0]*(min(mr, n)-1)+[1] for mr in rollMax]\n totals = [1]*len(rollMax)\n total = len(rollMax)\n indices = [0]*len(rollMax)\n for _ in range(n-1):\n ...
0
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
Dictionary DP for Space Savings | Commented and Explained
dice-roll-simulation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor any given valuation of a probability table of this nature, we care only about the appropriate prior valuations that have an impact on our current valuation. Due to this, we can memoize the results in a lookup dictionary table for rows...
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.
Dictionary DP for Space Savings | Commented and Explained
dice-roll-simulation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor any given valuation of a probability table of this nature, we care only about the appropriate prior valuations that have an impact on our current valuation. Due to this, we can memoize the results in a lookup dictionary table for rows...
0
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
Python3 Easy Solution
dice-roll-simulation
0
1
\n# Code\n```\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n MOD = 10 ** 9 + 7\n \n @lru_cache(None)\n def func(idx, prevNum, prevNumFreq):\n if idx == n:\n return 1\n \n ans = 0\n for i in range(1...
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 Easy Solution
dice-roll-simulation
0
1
\n# Code\n```\nclass Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n MOD = 10 ** 9 + 7\n \n @lru_cache(None)\n def func(idx, prevNum, prevNumFreq):\n if idx == n:\n return 1\n \n ans = 0\n for i in range(1...
0
Given an array of integers `arr` and two integers `k` and `threshold`, return _the number of sub-arrays of size_ `k` _and average greater than or equal to_ `threshold`. **Example 1:** **Input:** arr = \[2,2,2,2,5,5,5,8\], k = 3, threshold = 4 **Output:** 3 **Explanation:** Sub-arrays \[2,5,5\],\[5,5,5\] and \[5,5,8\]...
Think on Dynamic Programming. DP(pos, last) which means we are at the position pos having as last the last character seen.
Python easy to read and understand | hash table
maximum-equal-frequency
0
1
```\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n cnt, freq, maxfreq, ans = collections.defaultdict(int), collections.defaultdict(int), 0, 0\n for i, num in enumerate(nums):\n cnt[num] = cnt.get(num, 0) + 1\n freq[cnt[num]] += 1\n freq[cnt[num]-1]...
1
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no rema...
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
Python easy to read and understand | hash table
maximum-equal-frequency
0
1
```\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n cnt, freq, maxfreq, ans = collections.defaultdict(int), collections.defaultdict(int), 0, 0\n for i, num in enumerate(nums):\n cnt[num] = cnt.get(num, 0) + 1\n freq[cnt[num]] += 1\n freq[cnt[num]-1]...
1
Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. Answers within `10-5` of the actual value will be accepted as correct. **Example 1:** **Input:** hour = 12, minutes = 30 **Output:** 165 **Example 2:** **Input:** hour = 3, minutes ...
Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.
1224. Maximum Equal Frequency
maximum-equal-frequency
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 array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no rema...
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
1224. Maximum Equal Frequency
maximum-equal-frequency
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 two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. Answers within `10-5` of the actual value will be accepted as correct. **Example 1:** **Input:** hour = 12, minutes = 30 **Output:** 165 **Example 2:** **Input:** hour = 3, minutes ...
Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.
Python 3 | Solution | Beats 91.14% in runtime
maximum-equal-frequency
0
1
![image.png](https://assets.leetcode.com/users/images/69384c03-07b7-449a-9f87-e2cb2ad6fc5b_1689531999.724009.png)\n\n# Code\n```\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n\n D = defaultdict(int)\n\n for x in nums:\n D[x] += 1\n\n l = len(nums)\n d = le...
0
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no rema...
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
Python 3 | Solution | Beats 91.14% in runtime
maximum-equal-frequency
0
1
![image.png](https://assets.leetcode.com/users/images/69384c03-07b7-449a-9f87-e2cb2ad6fc5b_1689531999.724009.png)\n\n# Code\n```\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n\n D = defaultdict(int)\n\n for x in nums:\n D[x] += 1\n\n l = len(nums)\n d = le...
0
Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. Answers within `10-5` of the actual value will be accepted as correct. **Example 1:** **Input:** hour = 12, minutes = 30 **Output:** 165 **Example 2:** **Input:** hour = 3, minutes ...
Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.
Python - double counting trick
maximum-equal-frequency
0
1
# Intuition\nA bit different approach, more logic deduction then coding.\nCollect frequencies and count of frequencies, double counting (count of counts).\nThere are 4 cases when problem requirements are satisfied:\n#### A: single frequency\n1. if frequency is 1, it doesn\'t matter how many time it appears, when you re...
0
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no rema...
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
Python - double counting trick
maximum-equal-frequency
0
1
# Intuition\nA bit different approach, more logic deduction then coding.\nCollect frequencies and count of frequencies, double counting (count of counts).\nThere are 4 cases when problem requirements are satisfied:\n#### A: single frequency\n1. if frequency is 1, it doesn\'t matter how many time it appears, when you re...
0
Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. Answers within `10-5` of the actual value will be accepted as correct. **Example 1:** **Input:** hour = 12, minutes = 30 **Output:** 165 **Example 2:** **Input:** hour = 3, minutes ...
Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.
Python Easy Solution
maximum-equal-frequency
0
1
\n# Code\n```\nclass Solution:\n def maxEqualFreq(self, A):\n count = collections.Counter()\n freq = [0 for _ in range(len(A) + 1)]\n res = 0\n for n, a in enumerate(A, 1):\n freq[count[a]] -= 1\n freq[count[a] + 1] += 1\n c = count[a] = count[a] + 1\n ...
0
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no rema...
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.
Python Easy Solution
maximum-equal-frequency
0
1
\n# Code\n```\nclass Solution:\n def maxEqualFreq(self, A):\n count = collections.Counter()\n freq = [0 for _ in range(len(A) + 1)]\n res = 0\n for n, a in enumerate(A, 1):\n freq[count[a]] -= 1\n freq[count[a] + 1] += 1\n c = count[a] = count[a] + 1\n ...
0
Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_. Answers within `10-5` of the actual value will be accepted as correct. **Example 1:** **Input:** hour = 12, minutes = 30 **Output:** 165 **Example 2:** **Input:** hour = 3, minutes ...
Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1.
Frequency Distribution - Clean code
maximum-equal-frequency
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe question states\n> every number that has appeared in it will have the same number of occurrences\n\nThis is a clear sign that at the core of the problem we need to keep track of the frequency of the frequencies of each number (call th...
0
Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences. If after removing one element there are no rema...
Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution.