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 in-place w/ Stack
replace-non-coprime-numbers-in-array
0
1
# Intuition\nNote that we can greedily merge elements since the problem explicitly states that it can be shown that the order of merge does not matter. \n# Approach\nGiven that we can implement a greedy approach, we just need to keep track of the last number we have merged as we iterate over the array.\n# Complexity\n-...
0
You are given an array of integers `nums`. Perform the following steps: 1. Find **any** two **adjacent** numbers in `nums` that are **non-coprime**. 2. If no such numbers are found, **stop** the process. 3. Otherwise, delete the two numbers and **replace** them with their **LCM (Least Common Multiple)**. 4. **Repe...
How can you use rows and encodedText to find the number of columns of the matrix? Once you have the number of rows and columns, you can create the matrix and place encodedText in it. How should you place it in the matrix? How should you traverse the matrix to "decode" originalText?
✅Python easy to understand || Beginner friendly
find-all-k-distant-indices-in-an-array
0
1
```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n ind_j = []\n for ind, elem in enumerate(nums):\n if elem == key:\n ind_j.append(ind)\n res = []\n for i in range(len(nums)):\n for j in ind_j:\n ...
8
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
O(N) two-pass solution in Python
find-all-k-distant-indices-in-an-array
0
1
for each index `i`, we check for two possible key indexes - `keys[left]` and `keys[left + 1]`. If either of them is less than or equal to k, then add to `res`.\n\nIn order to handle the edges, I added negative and positive infinity to both sides.\n\n```\nclass Solution:\n def findKDistantIndices(self, nums: List[int...
3
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
python Beginner friendly soln..
find-all-k-distant-indices-in-an-array
0
1
```class Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n temp=[]\n result=[]\n for u,v in enumerate(nums):\n if v==key:\n temp.append(u)\n for i in range(0,len(nums)):\n for j in temp:\n if ab...
0
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
Python easy solution without using external function | Fast and single pass
find-all-k-distant-indices-in-an-array
0
1
Time :0(n) | Space : 0(n)\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n \n res_idx = set()\n n = len(nums)\n for idx in range(n):\n if key==nums[idx]:\n sp = idx - k if idx - k > 0 else 0\n ep =...
1
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
Python 5 lines
find-all-k-distant-indices-in-an-array
0
1
```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n ans = set()\n for i, num in enumerate(nums):\n if num == key:\n ans.update(range(max(0, i-k), min(i+k+1, len(nums))))\n return sorted(list(res))\n```
1
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
Clean Python Brute Force Solution
find-all-k-distant-indices-in-an-array
0
1
```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n n, ans = len(nums), []\n keys_index = [i for i in range(n) if nums[i] == key] # Holds the indices of all elements equal to key.\n m = len(keys_index)\n for i in range(n):\n f...
1
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
O(N) 5-line one pass without sorting
find-all-k-distant-indices-in-an-array
0
1
# Code\n```python\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n k_d_indices = set()\n for i, num in enumerate(nums):\n if num == key:\n k_d_indices.update(range(max(0, i-k), min(len(nums), i+k+1)))\n return list(k_d_...
0
You are given a **0-indexed** integer array `nums` and two integers `key` and `k`. A **k-distant index** is an index `i` of `nums` for which there exists at least one index `j` such that `|i - j| <= k` and `nums[j] == key`. Return _a list of all k-distant indices sorted in **increasing order**_. **Example 1:** **Inp...
We can check if every empty cell is a part of a consecutive row of empty cells that has a width of at least stampWidth as well as a consecutive column of empty cells that has a height of at least stampHeight. We can prove that this condition is sufficient and necessary to fit the stamps while following the given restri...
📌 [VISUAL] | [Python] | Easy to Understand | O(N^2) Time | O(N^2) Space
count-artifacts-that-can-be-extracted
0
1
\uD83D\uDD3A**Please UPVOTE: Can we hit 20?** \uD83D\uDD3A\n\n**Approach**\nHere we want to check if each part of an artifact is completely dug up. To do this we check each artifact, comparing it to what has been dug to see if it is completely excavated.\n\n**Visual**\nHere is a visual for the example in the question d...
26
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
📌 [VISUAL] | [Python] | Easy to Understand | O(N^2) Time | O(N^2) Space
count-artifacts-that-can-be-extracted
0
1
\uD83D\uDD3A**Please UPVOTE: Can we hit 20?** \uD83D\uDD3A\n\n**Approach**\nHere we want to check if each part of an artifact is completely dug up. To do this we check each artifact, comparing it to what has been dug to see if it is completely excavated.\n\n**Visual**\nHere is a visual for the example in the question d...
26
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
💯 Python elegant, short and simple to understand with explanations
count-artifacts-that-can-be-extracted
0
1
## Solution 1 - Hash dig positions\n\n1. Since we know all the dig spots, we add all of them into a set for fast lookup. \n1. Then we go through each artifact and check if all the positions for that artifact exist in the dig spots set. \n - If they do, we increment our results counter, otherwise proceed to the next ...
6
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
💯 Python elegant, short and simple to understand with explanations
count-artifacts-that-can-be-extracted
0
1
## Solution 1 - Hash dig positions\n\n1. Since we know all the dig spots, we add all of them into a set for fast lookup. \n1. Then we go through each artifact and check if all the positions for that artifact exist in the dig spots set. \n - If they do, we increment our results counter, otherwise proceed to the next ...
6
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Python Solution using Matrix and Simple Counting
count-artifacts-that-can-be-extracted
0
1
We number each artifact differently in a grid matrix of size n * n. Then we set the value of each grid[r][c] for r, c in dig to -1 meaning that they have been dug up. Now traverse the grid matrix finally and see which artifact numbers still remains. Those artifacts are the once which were not fully excavated. Now subrt...
3
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
Python Solution using Matrix and Simple Counting
count-artifacts-that-can-be-extracted
0
1
We number each artifact differently in a grid matrix of size n * n. Then we set the value of each grid[r][c] for r, c in dig to -1 meaning that they have been dug up. Now traverse the grid matrix finally and see which artifact numbers still remains. Those artifacts are the once which were not fully excavated. Now subrt...
3
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Python 6 lines
count-artifacts-that-can-be-extracted
0
1
```\nclass Solution:\n def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:\n dig = set((r, c) for r, c in dig)\n ans = 0\n for r0, c0, r1, c1 in artifacts:\n if all((r, c) in dig for r in range(r0, r1 + 1) for c in range(c0, c1 + 1)):\n ...
2
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
Python 6 lines
count-artifacts-that-can-be-extracted
0
1
```\nclass Solution:\n def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:\n dig = set((r, c) for r, c in dig)\n ans = 0\n for r0, c0, r1, c1 in artifacts:\n if all((r, c) in dig for r in range(r0, r1 + 1) for c in range(c0, c1 + 1)):\n ...
2
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
4 Line super simple
count-artifacts-that-can-be-extracted
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 `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
4 Line super simple
count-artifacts-that-can-be-extracted
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 a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Can you dig it?
count-artifacts-that-can-be-extracted
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince this is not an online problem -- "how many artifacts are uncovered after each shovel-ful in \'dig\'?" -- we can process all of ```dig``` to build a binary map of which cells are uncovered.\n\nThen, it\'s a matter of seeing, for each...
0
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
Can you dig it?
count-artifacts-that-can-be-extracted
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince this is not an online problem -- "how many artifacts are uncovered after each shovel-ful in \'dig\'?" -- we can process all of ```dig``` to build a binary map of which cells are uncovered.\n\nThen, it\'s a matter of seeing, for each...
0
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Python | Prefix Sum
count-artifacts-that-can-be-extracted
0
1
# Code\n```\nclass Solution:\n def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:\n g = [[0] * n for _ in range(n)]\n for r, c in dig:\n g[r][c] = 1\n for r in range(n):\n for c in range(n):\n g[r][c] += (g[r - 1][c] if r...
0
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
Python | Prefix Sum
count-artifacts-that-can-be-extracted
0
1
# Code\n```\nclass Solution:\n def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:\n g = [[0] * n for _ in range(n)]\n for r, c in dig:\n g[r][c] = 1\n for r in range(n):\n for c in range(n):\n g[r][c] += (g[r - 1][c] if r...
0
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Simple solution using prefix sums
count-artifacts-that-can-be-extracted
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing prefix sums,calculating if all the squares that occupy the treasure are dug or not\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$...
0
There is an `n x n` **0-indexed** grid with some artifacts buried in it. You are given the integer `n` and a **0-indexed** 2D integer array `artifacts` describing the positions of the rectangular artifacts where `artifacts[i] = [r1i, c1i, r2i, c2i]` denotes that the `ith` artifact is buried in the subgrid where: * `...
Could you convert this into a graph problem? Consider the pairs as edges and each number as a node. We have to find an Eulerian path of this graph. Hierholzer’s algorithm can be used.
Simple solution using prefix sums
count-artifacts-that-can-be-extracted
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing prefix sums,calculating if all the squares that occupy the treasure are dug or not\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$...
0
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zz...
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
[Python 3] Find Maximum of first k-1 elements or (k+1)th element | Beats 100%
maximize-the-topmost-element-after-k-moves
0
1
The num after the kth element do not matter as they can\'t be accessed.\nSo, handling some corner cases like:\n1. If len(num) == 1.\n2. if k == 0\n3. Comparing k and len(nums)\n\n**DO UPVOTE if you found it useful.**\n```\nclass Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n if len(nums) ...
10
You are given a **0-indexed** integer array `nums` representing the contents of a **pile**, where `nums[0]` is the topmost element of the pile. In one move, you can perform **either** of the following: * If the pile is not empty, **remove** the topmost element of the pile. * If there are one or more removed eleme...
Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to "generate" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated i...
[Python 3] Find Maximum of first k-1 elements or (k+1)th element | Beats 100%
maximize-the-topmost-element-after-k-moves
0
1
The num after the kth element do not matter as they can\'t be accessed.\nSo, handling some corner cases like:\n1. If len(num) == 1.\n2. if k == 0\n3. Comparing k and len(nums)\n\n**DO UPVOTE if you found it useful.**\n```\nclass Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n if len(nums) ...
10
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
Python 9 lines
maximize-the-topmost-element-after-k-moves
0
1
```\nclass Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n if len(nums) == 1:\n return -1 if k % 2 == 1 else nums[0]\n if k <= 1:\n return nums[k]\n if k < len(nums):\n return max(max(nums[:k-1]), nums[k])\n if k < len(nums) + 2: \n ...
2
You are given a **0-indexed** integer array `nums` representing the contents of a **pile**, where `nums[0]` is the topmost element of the pile. In one move, you can perform **either** of the following: * If the pile is not empty, **remove** the topmost element of the pile. * If there are one or more removed eleme...
Since we need to reduce search space, instead of checking if every number is a palindrome in base-10, can we try to "generate" the palindromic numbers? If you are provided with a d digit number, how can you generate a palindrome with 2*d or 2*d - 1 digit? Try brute-forcing and checking if the palindrome you generated i...
Python 9 lines
maximize-the-topmost-element-after-k-moves
0
1
```\nclass Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n if len(nums) == 1:\n return -1 if k % 2 == 1 else nums[0]\n if k <= 1:\n return nums[k]\n if k < len(nums):\n return max(max(nums[:k-1]), nums[k])\n if k < len(nums) + 2: \n ...
2
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
[Python3] - Dijkstra - Simple solution
minimum-weighted-subgraph-with-the-required-paths
0
1
# Intuition\nShortest path in positive weight graph -> Dijkstra\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe idea is the following: paths from `s1` to `dest` and from `s2` to `dest` can have common point `x`. Then we need to reach:\n\nFrom `s1` to `x`, for this we use Dijkstra...
2
You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`. Last...
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
Dijkstra of Graph and Dual | Commented and Explained
minimum-weighted-subgraph-with-the-required-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBy using a graph and it\'s dual we can solve a meeting vertext problem like this. This allows us to find the join of the two solution spaces, and can lead to optimizations on time as detailed herein. \n\nFirst, if we can never reach our d...
0
You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`. Last...
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
Triple Dijkstra in Python, Faster than 92%
minimum-weighted-subgraph-with-the-required-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem can be re-framed as the problem to find a meeting vertex `k` so that $$\\delta_{s_1, k} + \\delta_{s_2, k} + \\delta_{k, d}$$ is minimized, where $$\\delta_{s_1, k}$$ is the shortest distance between `src1` and `k`, $$\\delta...
0
You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`. Last...
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
80+ beats in both
minimum-weighted-subgraph-with-the-required-paths
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
You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`. Last...
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
2 dijkstras HACK me :)
minimum-weighted-subgraph-with-the-required-paths
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ndef dijk(s,g,n):\n dis=[float("inf")]*n\n par=[-1]*n\n dis[s]=0\n q=[(0,s)]\n while q:\n wt,t=heapq.heappop(q)\n if wt!=dis[t]:\n continue\n for i,w in g[t]:\n if w+wt<dis[i]:\n ...
0
You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`. Last...
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
could be faster than dijkstra in average
minimum-weighted-subgraph-with-the-required-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf there is a subgraph comply, there should exist at least one node that, src1 and src2 both reach that node and that node reach dest. The dest is one of them.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nstra...
0
You are given an integer `n` denoting the number of nodes of a **weighted directed** graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a **directed** edge from `fromi` to `toi` with weight `weighti`. Last...
Simulate how the robot moves and keep track of how many spaces it has cleaned so far. When can we stop the simulation? When the robot reaches a space that it has already cleaned and is facing the same direction as before, we can stop the simulation.
divide-array-into-equal-pairs
divide-array-into-equal-pairs
0
1
\n# Code\n```\nclass Solution:\n def divideArray(self, nums: List[int]) -> bool:\n if len(nums)%2!=0:\n return False\n else:\n for i in nums:\n if nums.count(i)%2!=0:\n return False\n else:\n return True\n```
1
You are given an integer array `nums` consisting of `2 * n` integers. You need to divide `nums` into `n` pairs such that: * Each element belongs to **exactly one** pair. * The elements present in a pair are **equal**. Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`. **Example 1...
How can we model the relationship between different bombs? Can "graphs" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixe...
[Java/Python 3] 4/1 liner O(n) code.
divide-array-into-equal-pairs
1
1
**Method 1: Count and check parity**\n\n```java\n public boolean divideArray(int[] nums) {\n int[] cnt = new int[501];\n for (int n : nums)\n ++cnt[n];\n return IntStream.of(cnt).allMatch(n -> n % 2 == 0);\n }\n```\n\n```python\n def divideArray(self, nums: List[int]) -> bool:\n...
41
You are given an integer array `nums` consisting of `2 * n` integers. You need to divide `nums` into `n` pairs such that: * Each element belongs to **exactly one** pair. * The elements present in a pair are **equal**. Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`. **Example 1...
How can we model the relationship between different bombs? Can "graphs" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixe...
Simplest Python 1 liner
divide-array-into-equal-pairs
0
1
\n\n# Code\n```\nclass Solution:\n def divideArray(self, nums: List[int]) -> bool:\n return all(not x&1 for x in Counter(nums).values())\n```
2
You are given an integer array `nums` consisting of `2 * n` integers. You need to divide `nums` into `n` pairs such that: * Each element belongs to **exactly one** pair. * The elements present in a pair are **equal**. Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`. **Example 1...
How can we model the relationship between different bombs? Can "graphs" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixe...
Easy Python Solution
divide-array-into-equal-pairs
0
1
```\ndef divideArray(self, nums: List[int]) -> bool:\n for i in nums:\n if nums.count(i)%2==1:\n return False\n return True\n```
3
You are given an integer array `nums` consisting of `2 * n` integers. You need to divide `nums` into `n` pairs such that: * Each element belongs to **exactly one** pair. * The elements present in a pair are **equal**. Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`. **Example 1...
How can we model the relationship between different bombs? Can "graphs" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixe...
Python ||O(N)|| simple solution
divide-array-into-equal-pairs
0
1
Time Complexcity : best -> O(N)\n wrost -> O(NlogN)\nSpace Complexcity O(N)\n```\nclass Solution:\n def divideArray(self, nums: List[int]) -> bool:\n if len(nums)%2!=0:\n return False\n n=len(nums)\n nums.sort()\n p1,p2=[],[]\n for i in range(n...
2
You are given an integer array `nums` consisting of `2 * n` integers. You need to divide `nums` into `n` pairs such that: * Each element belongs to **exactly one** pair. * The elements present in a pair are **equal**. Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`. **Example 1...
How can we model the relationship between different bombs? Can "graphs" help us? Bombs are nodes and are connected to other bombs in their range by directed edges. If we know which bombs will be affected when any bomb is detonated, how can we find the total number of bombs that will be detonated if we start from a fixe...
✅ ✅ Python3 O(NlogN) Solution || Max Heap ✅ ✅
minimum-operations-to-halve-array-sum
0
1
# Complexity\n- Time complexity:\nO(N logN)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def halveArray(self, nums: List[int]) -> int:\n heap = []\n for num in nums:\n heappush(heap,-1 * num)\n\n initalSum = sum(nums)\n targetSum = initalSum / 2\n k = 0...
1
You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.) Return _the **minimum** number of operations to reduce the sum of_ `nums` _by **at least** h...
null
[Java/Python 3] PriorityQueue/heap w/ brief explanation and analysis.
minimum-operations-to-halve-array-sum
1
1
**Q & A**\n*Q1:* Why in `PriorityQueue<Double> pq=new PriorityQueue<>((a,b)->b-a);` the lambda expression does not work with `double`?\n*A1:* Not very sure, but I guess it is because that in Java `Comparator` interface there is only one `int compare(T o1, T o2)` method, of which the return type is `int`. Please refer ...
18
You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.) Return _the **minimum** number of operations to reduce the sum of_ `nums` _by **at least** h...
null
python 3 || priority queue
minimum-operations-to-halve-array-sum
0
1
```\nclass Solution:\n def halveArray(self, nums: List[int]) -> int:\n s = sum(nums)\n goal = s / 2\n res = 0\n \n for i, num in enumerate(nums):\n nums[i] = -num\n heapq.heapify(nums)\n \n while s > goal:\n halfLargest = -heapq.heappop(nu...
2
You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.) Return _the **minimum** number of operations to reduce the sum of_ `nums` _by **at least** h...
null
Max Heap Python3 Short Solution
minimum-operations-to-halve-array-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first thought you can notice that you constantly want to be picking the largest possible number after each halving to minimize the number of operations. The brute force solution would be to sort the list and then pop the last element a...
1
You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.) Return _the **minimum** number of operations to reduce the sum of_ `nums` _by **at least** h...
null
Easy Problem with simple Intuition and Approcah Explanation
minimum-operations-to-halve-array-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy intuition is that the task is to reduce the sum of an array to half by performing the minimum number of operations. To achieve this, select the largest value in the array, halve it, and subtract this halved value from the total sum.\n#...
0
You are given an array `nums` of positive integers. In one operation, you can choose **any** number from `nums` and reduce it to **exactly** half the number. (Note that you may choose this reduced number in future operations.) Return _the **minimum** number of operations to reduce the sum of_ `nums` _by **at least** h...
null
[Python3] dp
minimum-white-tiles-after-covering-with-carpets
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/7e91381aab0f51486f380f703245463c99fed635) for solutions of biweekly 74. \n\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n \n @cache\n def fn(i, n):\n """...
2
You are given a **0-indexed binary** string `floor`, which represents the colors of tiles on a floor: * `floor[i] = '0'` denotes that the `ith` tile of the floor is colored **black**. * On the other hand, `floor[i] = '1'` denotes that the `ith` tile of the floor is colored **white**. You are also given `numCarpet...
The brute force solution is to check every substring, which would TLE. How can we improve this solution? In an equal count substring, the first character appears count times, the second character appears count times, and so on. The length of an equal count substring is the number of unique characters multiplied by coun...
Simple Explanation and Solution (Memoization) [Python]
minimum-white-tiles-after-covering-with-carpets
0
1
# Intuition\nBacktracking memoization solution. At every step we either place a carpet or don\'t - we do whatever minimizes the number of exposed white tiles. For every tile we make a binary choice, which means complexity $O(2^n)$, but with memoization we reduce that to $O(n^2)$.\n\n# Complexity\n- Time complexity: $$\...
0
You are given a **0-indexed binary** string `floor`, which represents the colors of tiles on a floor: * `floor[i] = '0'` denotes that the `ith` tile of the floor is colored **black**. * On the other hand, `floor[i] = '1'` denotes that the `ith` tile of the floor is colored **white**. You are also given `numCarpet...
The brute force solution is to check every substring, which would TLE. How can we improve this solution? In an equal count substring, the first character appears count times, the second character appears count times, and so on. The length of an equal count substring is the number of unique characters multiplied by coun...
python3 dp beats 93%
minimum-white-tiles-after-covering-with-carpets
0
1
\n\n# Code\n```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n floor = \'0\'+floor\n dp = [[inf for x in range(len(floor))] for y in range(numCarpets+1)]\n c = 0\n for i in range(len(floor)):\n if floor[i]==\'1\':\n ...
0
You are given a **0-indexed binary** string `floor`, which represents the colors of tiles on a floor: * `floor[i] = '0'` denotes that the `ith` tile of the floor is colored **black**. * On the other hand, `floor[i] = '1'` denotes that the `ith` tile of the floor is colored **white**. You are also given `numCarpet...
The brute force solution is to check every substring, which would TLE. How can we improve this solution? In an equal count substring, the first character appears count times, the second character appears count times, and so on. The length of an equal count substring is the number of unique characters multiplied by coun...
Dp Super Detailed Explanation and Process
minimum-white-tiles-after-covering-with-carpets
0
1
\n## Initial thoughts \n\nIt looks like initially, me an others considered a greedy approach to optimize the placement of carpets to cover the most white tiles at each step. With counterexamples It became clear though that the approach didn\'t yield the optimal solution. From the solutions section it seemed was rather ...
0
You are given a **0-indexed binary** string `floor`, which represents the colors of tiles on a floor: * `floor[i] = '0'` denotes that the `ith` tile of the floor is colored **black**. * On the other hand, `floor[i] = '1'` denotes that the `ith` tile of the floor is colored **white**. You are also given `numCarpet...
The brute force solution is to check every substring, which would TLE. How can we improve this solution? In an equal count substring, the first character appears count times, the second character appears count times, and so on. The length of an equal count substring is the number of unique characters multiplied by coun...
Python Clean solution || Simple and easy
count-hills-and-valleys-in-an-array
0
1
We start by taking a for loop which goes from 1 to length of array -1.\nSince we cannot take 2 adjacent values such that nums[i] == nums[j]. \nSo, we update the current value to previous value which will help us in counting the next hill or valley. \n\nTime complexity = O(n)\nSpace complexity = O(1)\n\n```class Solutio...
56
You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closest non-equal neighbors of `i` are larger than `nums[i]`. Adjacent indices `i` and `...
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
Python Clean solution & explanation of an edge case
count-hills-and-valleys-in-an-array
0
1
# Intuition\nWe are iterating from 1st to last -1 element.\nFor each one determine is it hill or velly:\nelement-1 < element > element + 1 or element-1 > element < element + 1\n\n# Approach\nImportant to not count the same velly [4, ***1,1,1*** ,4] multiple times.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space co...
2
You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closest non-equal neighbors of `i` are larger than `nums[i]`. Adjacent indices `i` and `...
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
[Python3] One pass || O(1) space
count-hills-and-valleys-in-an-array
0
1
```\nclass Solution:\n def countHillValley(self, nums: List[int]) -> int:\n \n #cnt: An integer to store total hills and valleys\n #left: Highest point of hill or lowest point of valley left of the current index\n cnt, left = 0, nums[0]\n \n for i in range(1, len(nums)-1):\n...
3
You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closest non-equal neighbors of `i` are larger than `nums[i]`. Adjacent indices `i` and `...
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
python
count-hills-and-valleys-in-an-array
0
1
```\ndef countHillValley(self, nums: List[int]) -> int:\n nums1 = [nums[0]]\n for i in range(1, len(nums)):\n if nums[i] != nums1[-1]:\n nums1.append(nums[i])\n cnt = 0\n for i in range(1, len(nums1) - 1):\n if nums1[i - 1] < nums1[i] > nums1[i + 1] or nu...
2
You are given a **0-indexed** integer array `nums`. An index `i` is part of a **hill** in `nums` if the closest non-equal neighbors of `i` are smaller than `nums[i]`. Similarly, an index `i` is part of a **valley** in `nums` if the closest non-equal neighbors of `i` are larger than `nums[i]`. Adjacent indices `i` and `...
Try "sorting" the array first. Now find all indices in the array whose values are equal to target.
Not a stupid problem!
count-collisions-on-a-road
1
1
**Similar Question :-** [ https://leetcode.com/problems/asteroid-collision/]\n**C++ Solution**\n\n```\nclass Solution {\npublic:\n int countCollisions(string dir) {\n \n int res(0), n(size(dir)), i(0), carsFromRight(0);\n \n while (i < n and dir[i] == \'L\') i++; // skipping all the cars ...
124
There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point. You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be either `'L'`, `'R'`, or `'S'` denoting whether the `ith` car is moving towar...
To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer...
One-liner in Python
count-collisions-on-a-road
0
1
All the cars that move to the middle will eventually collide.... \n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n return sum(d!=\'S\' for d in directions.lstrip(\'L\').rstrip(\'R\'))\n```
74
There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point. You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be either `'L'`, `'R'`, or `'S'` denoting whether the `ith` car is moving towar...
To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer...
Short Easy Python Solution With Explanation
count-collisions-on-a-road
0
1
We can transform this problem into whether go right or go left cars will stop and count the sum of stops. After transformation, we just need to check the situation of each go left and go right car individually.\n\nStarting from left->right,\n\nIf there is no car at the beginning go right or stop, then go left car after...
13
There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point. You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be either `'L'`, `'R'`, or `'S'` denoting whether the `ith` car is moving towar...
To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer...
Efficient Python solution O(N) time O(1) space with clear explanation
count-collisions-on-a-road
0
1
This question is similar to the [Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) question.\n\nWe need a few variables:\n- has_stationary - determines if there stationary objects which will result in collisions\n- number of cars moving towards the right - when they hit a left/stationary car, they ...
5
There are `n` cars on an infinitely long road. The cars are numbered from `0` to `n - 1` from left to right and each car is present at a **unique** point. You are given a **0-indexed** string `directions` of length `n`. `directions[i]` can be either `'L'`, `'R'`, or `'S'` denoting whether the `ith` car is moving towar...
To calculate the average of a subarray, you need the sum and the K. K is already given. How could you quickly calculate the sum of a subarray? Use the Prefix Sums method to calculate the subarray sums. It is possible that the sum of all the elements does not fit in a 32-bit integer type. Be sure to use a 64-bit integer...
No Segment Tree and NOT Pretty [100%, 48%]
longest-substring-of-one-repeating-character
0
1
# Complexity\n- Time complexity: $O(nlogn)$ (*assuming* array resizing is const time)\n\n- Space complexity: $(On)$\n\n# Code\n```python\nfrom heapq import heappush, heappop\nclass Solution:\n def longestRepeating(self, A: str, C: str, I: List[int]) -> List[int]:\n ii = [[0, 0, 1, A[0]]]\n for i in ran...
0
You are given a **0-indexed** string `s`. You are also given a **0-indexed** string `queryCharacters` of length `k` and a **0-indexed** array of integer **indices** `queryIndices` of length `k`, both of which are used to describe `k` queries. The `ith` query updates the character in `s` at index `queryIndices[i]` to t...
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
longest substring with one repeating charecter
longest-substring-of-one-repeating-character
0
1
# Intuition \n<!-- Describe your first thoughts on how to solve this problem. -->sliding window approach \n\n# Approach\n<!-- Describe your approach to solving the problem. -->can refer to the longest substring with k unique charecter here it can be k=1\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time compl...
0
You are given a **0-indexed** string `s`. You are also given a **0-indexed** string `queryCharacters` of length `k` and a **0-indexed** array of integer **indices** `queryIndices` of length `k`, both of which are used to describe `k` queries. The `ith` query updates the character in `s` at index `queryIndices[i]` to t...
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
[Python] AC Merge Intervals Explain | SortedContainers
longest-substring-of-one-repeating-character
0
1
# Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can use segment tree but it didn\'t work for me in python TLE :(\nWe can also think this problem as merging intervals, each interval will represent range of repeated characters.\ninterval - [start,end,character]\nFor each query update t...
0
You are given a **0-indexed** string `s`. You are also given a **0-indexed** string `queryCharacters` of length `k` and a **0-indexed** array of integer **indices** `queryIndices` of length `k`, both of which are used to describe `k` queries. The `ith` query updates the character in `s` at index `queryIndices[i]` to t...
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
best python sol
longest-substring-of-one-repeating-character
0
1
\n# Code\n```\n\nfrom sortedcontainers import SortedList\nclass Solution:\n def longestRepeating(self, s: str, qc: str, qi):\n qr = list(zip(list(qc), qi))\n srt = SortedList([])\n mx = SortedList([])\n cr = s[0]\n sz = 1\n start, end = 0, 0\n for i in range(1, len(s)...
0
You are given a **0-indexed** string `s`. You are also given a **0-indexed** string `queryCharacters` of length `k` and a **0-indexed** array of integer **indices** `queryIndices` of length `k`, both of which are used to describe `k` queries. The `ith` query updates the character in `s` at index `queryIndices[i]` to t...
Could you model all the meetings happening at the same time as a graph? What data structure can you use to efficiently share the secret? You can use the union-find data structure to quickly determine who knows the secret and share the secret.
Superb Questions--->Python3
find-the-difference-of-two-arrays
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
Given two **0-indexed** integer arrays `nums1` and `nums2`, return _a list_ `answer` _of size_ `2` _where:_ * `answer[0]` _is a list of all **distinct** integers in_ `nums1` _which are **not** present in_ `nums2`_._ * `answer[1]` _is a list of all **distinct** integers in_ `nums2` _which are **not** present in_ `n...
The range of possible answers includes all even numbers between 100 and 999 inclusive. Could you check each possible answer to see if it could be formed from the digits in the array?
Python | Greedy
minimum-deletions-to-make-array-beautiful
0
1
```\nclass Solution:\n def minDeletion(self, nums: List[int]) -> int:\n # Greedy !\n # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0\n # at the begining, we consider the num on the even index\n # when we delete a num, we need consider the num on the odd i...
15
You are given a **0-indexed** integer array `nums`. The array `nums` is **beautiful** if: * `nums.length` is even. * `nums[i] != nums[i + 1]` for all `i % 2 == 0`. Note that an empty array is considered beautiful. You can delete any number of elements from `nums`. When you delete an element, all the elements to ...
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. Can you use this to find the middle node of a linked list? If you are given the middle node, the node before it, and the node after it, how can you modify the linked list?
Python Simple Solution O(n) Time and O(1) Space
minimum-deletions-to-make-array-beautiful
0
1
We iterate over nums from left to right and **greedily choose elements** which satisfy the given condition in our final array. While iterating, we need to **keep a count** of how many elements we have chosen so far to make greedy choices.\n\n### Idea:\n1. Iterate from left to right uptil second last element:\n 1.1 I...
9
You are given a **0-indexed** integer array `nums`. The array `nums` is **beautiful** if: * `nums.length` is even. * `nums[i] != nums[i + 1]` for all `i % 2 == 0`. Note that an empty array is considered beautiful. You can delete any number of elements from `nums`. When you delete an element, all the elements to ...
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. Can you use this to find the middle node of a linked list? If you are given the middle node, the node before it, and the node after it, how can you modify the linked list?
[Python 3] Two Pointer Greedy Solution
minimum-deletions-to-make-array-beautiful
0
1
**Approach**:\nInitialise steps to 0.\nUse two pointers, one to iterate through the array and other to keep track of the index in the updated list after removing (as the indices will change because of shifting).\n\nIf the index is not divisible by 2, then increment the index by 1. Otherwise, taking care of an edge case...
2
You are given a **0-indexed** integer array `nums`. The array `nums` is **beautiful** if: * `nums.length` is even. * `nums[i] != nums[i + 1]` for all `i % 2 == 0`. Note that an empty array is considered beautiful. You can delete any number of elements from `nums`. When you delete an element, all the elements to ...
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. Can you use this to find the middle node of a linked list? If you are given the middle node, the node before it, and the node after it, how can you modify the linked list?
Python simple solution beats 100.00%
find-palindrome-with-fixed-length
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. A **palindrome** is a number that reads the same backwards and forwar...
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the ...
Python simple solution beats 100.00%
find-palindrome-with-fixed-length
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 have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`...
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
Python | simple and straightforward
find-palindrome-with-fixed-length
0
1
```\nclass Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n # think the palindromes in half\n # e.g. len = 4 we only consider the first 2 digits\n # half: 10, 11, 12, 13, 14, ..., 19, 20, \n # full: 1001, 1111, 1221, 1331, ...\n # e.g. len = ...
7
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. A **palindrome** is a number that reads the same backwards and forwar...
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the ...
Python | simple and straightforward
find-palindrome-with-fixed-length
0
1
```\nclass Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n # think the palindromes in half\n # e.g. len = 4 we only consider the first 2 digits\n # half: 10, 11, 12, 13, 14, ..., 19, 20, \n # full: 1001, 1111, 1221, 1331, ...\n # e.g. len = ...
7
You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`...
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
[Python3] Math solution with explanation
find-palindrome-with-fixed-length
0
1
Taking into account the palindrome property, we want to work with only half of the digits, and get the rest as the same half, but in reverse order. For this purpose, we have a **helper** function, in which for even numbers the order of the left side is changed to receive the right part, and for odd numbers the last dig...
3
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. A **palindrome** is a number that reads the same backwards and forwar...
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the ...
[Python3] Math solution with explanation
find-palindrome-with-fixed-length
0
1
Taking into account the palindrome property, we want to work with only half of the digits, and get the rest as the same half, but in reverse order. For this purpose, we have a **helper** function, in which for even numbers the order of the left side is changed to receive the right part, and for odd numbers the last dig...
3
You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`...
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
Simple Solution python
find-palindrome-with-fixed-length
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N*intLength)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(N*intLength)\n<!-- Add your space c...
0
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. A **palindrome** is a number that reads the same backwards and forwar...
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the ...
Simple Solution python
find-palindrome-with-fixed-length
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N*intLength)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(N*intLength)\n<!-- Add your space c...
0
You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`...
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
Python | Straightforward Solution | Half Palin
find-palindrome-with-fixed-length
0
1
# Code\n```\nfrom math import log10\nfrom bisect import bisect_left\n\nclass Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n # num of palindrome with intLength\n # k = (intLength + 1) // 2\n # total cnt of palindrome with intLength = 9 * 10 ** (k - 1)\n ...
0
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. A **palindrome** is a number that reads the same backwards and forwar...
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the ...
Python | Straightforward Solution | Half Palin
find-palindrome-with-fixed-length
0
1
# Code\n```\nfrom math import log10\nfrom bisect import bisect_left\n\nclass Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n # num of palindrome with intLength\n # k = (intLength + 1) // 2\n # total cnt of palindrome with intLength = 9 * 10 ** (k - 1)\n ...
0
You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`...
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
Math way: construct the prefix half
find-palindrome-with-fixed-length
0
1
# Intuition\nConstruct the prefix half of Palindrome in increasing order. \n\n# Approach\nGiven the half-palindrome\'s lenght = k, so number must no less than \n10**(k-1). The index=1 should 10**k-1. Distinct half-paalindrome will contribute to one paalindrome in incresing order. \n\nExample: \nintLength =4, half-leng...
0
Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. A **palindrome** is a number that reads the same backwards and forwar...
The shortest path between any two nodes in a tree must pass through their Lowest Common Ancestor (LCA). The path will travel upwards from node s to the LCA and then downwards from the LCA to node t. Find the path strings from root → s, and root → t. Can you use these two strings to prepare the final answer? Remove the ...
Math way: construct the prefix half
find-palindrome-with-fixed-length
0
1
# Intuition\nConstruct the prefix half of Palindrome in increasing order. \n\n# Approach\nGiven the half-palindrome\'s lenght = k, so number must no less than \n10**(k-1). The index=1 should 10**k-1. Distinct half-paalindrome will contribute to one paalindrome in incresing order. \n\nExample: \nintLength =4, half-leng...
0
You have a **1-indexed** binary string of length `n` where all the bits are `0` initially. We will flip all the bits of this binary string (i.e., change them from `0` to `1`) one by one. You are given a **1-indexed** integer array `flips` where `flips[i]` indicates that the bit at index `i` will be flipped in the `ith`...
For any value of queries[i] and intLength, how can you check if there exists at least queries[i] palindromes of length intLength? Since a palindrome reads the same forwards and backwards, consider how you can efficiently find the first half (ceil(intLength/2) digits) of the palindrome.
python3 Solution
maximum-value-of-k-coins-from-piles
0
1
\n```\nclass Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n \n @functools.lru_cache(None)\n def dp(i,K):\n if k==0 or i==len(piles):\n return 0\n\n res,cur=dp(i+1,K),0\n\n for j in range(min(len(piles[i]),K)):\n ...
4
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
Python 3 || 9 lines, recursion || T/M: 91% / 33%
maximum-value-of-k-coins-from-piles
0
1
```\nclass Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n \n @lru_cache(None)\n def dfs(coins, moves):\n if len(piles) == coins: return 0\n\n ans, curr, pile = dfs(coins+1, moves), 0, piles[coins]\n\n for j in range(min(len(pile),...
3
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
Python 3 || 9 lines, recursion || T/M: 91% / 33%
maximum-value-of-k-coins-from-piles
0
1
```\nclass Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n \n @lru_cache(None)\n def dfs(coins, moves):\n if len(piles) == coins: return 0\n\n ans, curr, pile = dfs(coins+1, moves), 0, piles[coins]\n\n for j in range(min(len(pile),...
3
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
prefix sum + 2d DP
maximum-value-of-k-coins-from-piles
0
1
# Intuition\nUse DP and prefix sum\n\n# Approach\nFirst for each pile, build a prefix sum (aka cummulative sum) up to k elements (we can just trim/ignore if there is more).\n\nThen focus on the first pile.\nWe can take first coin, or two, or ... k and then deal with smaller problem (one less pile and same or less coins...
2
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
PYTHON || easy solution with explanation || recursion with caching
maximum-value-of-k-coins-from-piles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ndynamic programming problem \n# Approach\n<!-- Describe your approach to solving the problem. -->\n- we first skip all nodes to start from last assume i have 4 piles (try last piles , then try 3rd and last pile , etc)\n- with base case if...
2
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
Easy python solution
maximum-value-of-k-coins-from-piles
0
1
```\nclass Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n presum = [list(accumulate(p, initial=0)) for p in piles]\n n = len(piles)\n dp = [[0] * (k + 1) for _ in range(n + 1)]\n for i, s in enumerate(presum, 1):\n for j in range(k + 1):\n ...
1
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
No-brainer DFS solution with cache
maximum-value-of-k-coins-from-piles
0
1
# Intuition\nIntuition 1: for pile i, I can pick l = 0, 1, ..., min(k, len(pile[i])) coins from pile i;\nIntuition 2: when I pick l coins on pile i, I then can pick k-l coins from i+1 to N-1 piles.\n \n# Approach\nSolve a subproblem: Find the maximum total value if we are picking from ith pile upto (N-1)th pile ...
1
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
python 3 - top-down DP
maximum-value-of-k-coins-from-piles
0
1
# Intuition\nFrom the question, you need to exhaust the possibilities of:\n1.picking certain number of coin from a pile\n2.loop the remaining piles with k_remain\n\nThese are the 2 state variables.\n\nFrom eg.2, you know you can\'t do greedy. Previous choice affect future choice. So DP is the only solution.\n\n# Approa...
1
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
Bottom-Up DP Python
maximum-value-of-k-coins-from-piles
0
1
\n\n```\nclass Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n n = len(piles)\n dp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]\n for i in range(1, n + 1):\n for coins in range(0, k + 1):\n currSum = 0\n for currCoin...
1
There are `n` **piles** of coins on a table. Each pile consists of a **positive number** of coins of assorted denominations. In one move, you can choose any coin on **top** of any pile, remove it, and add it to your wallet. Given a list `piles`, where `piles[i]` is a list of integers denoting the composition of the `...
If the path starts at room i, what properties must the other two rooms in the cycle have? The other two rooms must be connected to room i, and must be connected to each other.
[Python/Java/C++] Solution without XOR
minimum-bit-flips-to-convert-number
0
1
# Divmod Remainder Approach:\n#### Time Complexity: O(log(min(s,g))) --> O(log(n)) \n#### Space Complexity: O(1)\n\nWe divide s and q by 2 until either s or g equals zero.\nDuring this process, if the remainder of either of them **do not** equal eachother, we increment the counter.\n\n***This process is similar to conv...
17
A **bit flip** of a number `x` is choosing a bit in the binary representation of `x` and **flipping** it from either `0` to `1` or `1` to `0`. * For example, for `x = 7`, the binary representation is `111` and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from t...
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
✔ python | easy | interview thinking
minimum-bit-flips-to-convert-number
0
1
The given question requires us to count the total number of flips we need to do inorder to make `start -> goal`.\nEx: \n7 - 0111\n10 - 1010\nHere, we only flip the bits which are different in both **start** and **goal**, i.e. `01` or `10`. And, what helps us to find if the bits are different? **XOR**. \nNow, we count ...
7
A **bit flip** of a number `x` is choosing a bit in the binary representation of `x` and **flipping** it from either `0` to `1` or `1` to `0`. * For example, for `x = 7`, the binary representation is `111` and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from t...
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
Curious Logic Python3
minimum-bit-flips-to-convert-number
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)$$ --...
5
A **bit flip** of a number `x` is choosing a bit in the binary representation of `x` and **flipping** it from either `0` to `1` or `1` to `0`. * For example, for `x = 7`, the binary representation is `111` and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from t...
Can we use a data structure to quickly query whether we have a certain ingredient? Once we verify that we can make a recipe, we can add it to our ingredient data structure. We can then check if we can make more recipes as a result of this.
Pascal Triangle
find-triangular-sum-of-an-array
0
1
We can do a simulation for a O(n * n) solution, but it\'s not interesting. Instead, we will use a bit of math to look at more efficient solutions.\n\nEach number in the array contributes to the final sum a certain number of times. We can visualize how to figure out factors for each number using [Pascal\'s triangle](ht...
35
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
Clean Python 3 Solution O(n)
find-triangular-sum-of-an-array
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOnce the pascal\'s triangle/binomial coefficients idea is clear the implementation is easy as follows, for each term in the initial array calculate its contribution in the final array.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time com...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
nested loop solution
find-triangular-sum-of-an-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)$$ --...
7
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
Python 2265 ms, faster than 86.98% of Python3 online submissions
find-triangular-sum-of-an-array
0
1
```\ndef triangularSum(self, nums: List[int]) -> int:\n if not nums:\n return 0\n if len(nums) == 1:\n return nums[0]\n \n n = len(nums)\n \n while n != 1:\n nums = [(nums[i] + nums[i+1]) % 10 for i in range(n-1)]\n n = len(nums)\n ...
2
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
[Java/Python 3] Compute in-place w/ analysis.
find-triangular-sum-of-an-array
1
1
```java\n public int triangularSum(int[] nums) {\n for (int n = nums.length; n > 0; --n) {\n for (int i = 1; i < n; ++i) {\n nums[i - 1] += nums[i];\n nums[i - 1] %= 10;\n }\n }\n return nums[0];\n }\n```\n```python\n def triangularSum(se...
22
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
Python 3 | Intuitive | Brute Force + Optimal
find-triangular-sum-of-an-array
0
1
# Approach\nGoals: return the single element of triangular sum\n\n![image](https://assets.leetcode.com/uploads/2022/02/22/ex1drawio.png)\n\n\nWe can see from the image that we will sum up the first cell and the second cell. Then, since it\'s triangular, the length of the top row is greater (+1) than the next row. \n\n#...
8
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
Python3 with helper
find-triangular-sum-of-an-array
0
1
```\nclass Solution:\n def helper(self, nums: List[int]) -> List[int]:\n dp = []\n i = 0\n while i < len(nums) - 1:\n dp.append((nums[i] + nums[i + 1]) % 10)\n i += 1\n return dp\n \n def triangularSum(self, nums: List[int]) -> int:\n while len(nums) > 1...
5
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
9 lines Easy python solution
find-triangular-sum-of-an-array
0
1
**PLEASE UPVOTE IF YOU FIND THIS SOLUTION HELPFUL **\n\tclass Solution:\n\t\tdef triangularSum(self, nums: List[int]) -> int:\n\t\t\n\t\t\tarr=nums.copy()\n\t\t\tlst=[]\n\t\t\twhile len(arr)!=1:\n\t\t\t\tfor i in range(0,len(arr)-1):\n\t\t\t\t\ts=arr[i]+arr[i+1]\n\t\t\t\t\tlst.append(s%10) #to get the last digit of i...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` is a digit between `0` and `9` (**inclusive**). The **triangular sum** of `nums` is the value of the only element present in `nums` after the following process terminates: 1. Let `nums` comprise of `n` elements. If `n == 1`, **end** the process. Oth...
Can an odd length string ever be valid? From left to right, if a locked ')' is encountered, it must be balanced with either a locked '(' or an unlocked index on its left. If neither exist, what conclusion can be drawn? If both exist, which one is more preferable to use? After the above, we may have locked indices of '(...
[Java/Python 3] One pass S O(1) T O(n) codes and follow up, w/ brief explanation and analysis.
number-of-ways-to-select-buildings
1
1
Traverse the input `s`:\n1. If encontering `0`, count subsequences ending at current `0`: `0`, `10` and `010`\'s; The number of `10` depends on how many `1`s before current `0`, and the number of `010` depends on how many `01` before current `0`;\n\nSimilarly, \n\n2. If encontering `1`, count subsequences ending at cur...
131
You are given a **0-indexed** binary string `s` which represents the types of buildings along a street where: * `s[i] = '0'` denotes that the `ith` building is an office and * `s[i] = '1'` denotes that the `ith` building is a restaurant. As a city official, you would like to **select** 3 buildings for random insp...
Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately. Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits. The number of trailing zeros C is noth...
[Python 3] BEATS 100%
number-of-ways-to-select-buildings
0
1
# Intuition\nFor each house calculate how many inspections where this house is the last one\n\n# Approach\n1. Iterate over houses\n2. If house is \'1\' $\\Longrightarrow$ previous house should be \'0\'\n 2.1 We can choose any previous \'0\' as the 2nd house and any \'1\' before that \'0\' as the 1st\n 2.2 Because of ...
3
You are given a **0-indexed** binary string `s` which represents the types of buildings along a street where: * `s[i] = '0'` denotes that the `ith` building is an office and * `s[i] = '1'` denotes that the `ith` building is a restaurant. As a city official, you would like to **select** 3 buildings for random insp...
Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately. Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits. The number of trailing zeros C is noth...
5 line Python Solution | Easy + Fast
number-of-ways-to-select-buildings
0
1
```\nclass Solution:\n def numberOfWays(self, s: str) -> int:\n x0,x1,x01,x10,ans = 0,0,0,0,0\n for i in s:\n if i=="1": x1+=1;x01+=x0;ans+=x10\n else: x0+=1;x10+=x1;ans+=x01\n return ans
2
You are given a **0-indexed** binary string `s` which represents the types of buildings along a street where: * `s[i] = '0'` denotes that the `ith` building is an office and * `s[i] = '1'` denotes that the `ith` building is a restaurant. As a city official, you would like to **select** 3 buildings for random insp...
Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately. Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits. The number of trailing zeros C is noth...
Python DP
number-of-ways-to-select-buildings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this case, the dp should not be initialized as a list, but it should be initalized as a hashmap.\nIf a character in s is \'1\', then the number of ways to select one \'1\' is incremented by 1, the number of ways to select \'101\' is in...
1
You are given a **0-indexed** binary string `s` which represents the types of buildings along a street where: * `s[i] = '0'` denotes that the `ith` building is an office and * `s[i] = '1'` denotes that the `ith` building is a restaurant. As a city official, you would like to **select** 3 buildings for random insp...
Calculating the number of trailing zeros, the last five digits, and the first five digits can all be done separately. Use a prime factorization property to find the number of trailing zeros. Use modulo to find the last 5 digits. Use a logarithm property to find the first 5 digits. The number of trailing zeros C is noth...