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
Go/Python/JavaScript/Java O(n) time | O(n) space
destination-city
1
1
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc destCity(paths [][]string) string {\n routes := make(map[string]int)\n\n for _,pair := range(paths)...
1
You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._ It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil...
Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.
Go/Python/JavaScript/Java O(n) time | O(n) space
destination-city
1
1
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc destCity(paths [][]string) string {\n routes := make(map[string]int)\n\n for _,pair := range(paths)...
1
Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length **6** is labelled as follows: Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you ...
Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.
🚀Unbeatable Python Mastery: Soaring above 97.12% in destination city Challenge! 🏆 #PythonMagic
destination-city
0
1
# Intuition\n\uD83E\uDDE0 **Intuition Behind the Dominant Python Solution**\n\n**Step 1:** \uD83D\uDCCD Begin by segregating the source and destination cities into separate lists. This ensures clarity in tracking city connections.\n\n**Step 2:** \uD83D\uDD17 Leverage the power of Python\'s `symmetric_difference()` meth...
1
You are given the array `paths`, where `paths[i] = [cityAi, cityBi]` means there exists a direct path going from `cityAi` to `cityBi`. _Return the destination city, that is, the city without any path outgoing to another city._ It is guaranteed that the graph of paths forms a line without any loop, therefore, there wil...
Do BFS to find the kth level friends. Then collect movies saw by kth level friends and sort them accordingly.
🚀Unbeatable Python Mastery: Soaring above 97.12% in destination city Challenge! 🏆 #PythonMagic
destination-city
0
1
# Intuition\n\uD83E\uDDE0 **Intuition Behind the Dominant Python Solution**\n\n**Step 1:** \uD83D\uDCCD Begin by segregating the source and destination cities into separate lists. This ensures clarity in tracking city connections.\n\n**Step 2:** \uD83D\uDD17 Leverage the power of Python\'s `symmetric_difference()` meth...
1
Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length **6** is labelled as follows: Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you ...
Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.
Simple Python solution
check-if-all-1s-are-at-least-length-k-places-away
0
1
\n\n# Code\n```\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n a = []\n for i in range(len(nums)):\n if nums[i] == 1:\n a.append(i+1)\n return all((a[i+1]-a[i]) >= k+1 for i in range(len(a)-1))\n```
1
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
Python easy solution , beats 86% efficiency ✅✅🚀🚀
check-if-all-1s-are-at-least-length-k-places-away
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 binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
[Python] i guess it's cheating but it works tho
check-if-all-1s-are-at-least-length-k-places-away
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n n = k #\'<- the cheating line\n f...
2
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
Only judge when 1 appears
check-if-all-1s-are-at-least-length-k-places-away
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly judge when 1 appear\n# Approach\n<!-- Describe your approach to solving the problem. -->\ni = first 1 index &\nnext 1 index must >= i + 1\nLoop for count(1) - 1 (last 1 have no next 1 to judge)\n# Complexity\n- Time complexity:\n<!--...
0
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
Using string with separator solution (Explaned)
check-if-all-1s-are-at-least-length-k-places-away
0
1
# Approach\nSeparate the string by k*"0" then we get an array of strings, if we encounter a string where the number of 1\'s is greater than 1, then there are not enough zeros between 1\'s and the condition is not met, then return false, otherwise if the strings in the array do not contain more than one 1 then there are...
0
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
My Solution :) BEATS 92.9% RUNTIME
check-if-all-1s-are-at-least-length-k-places-away
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n ...
0
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
check individual differences
check-if-all-1s-are-at-least-length-k-places-away
0
1
Don\'t need to check differences of non-adjacent 1s. If two 1s i and jare correctly separated, then 1 k where index of k is j + n will definitely be greater than k. Therefore we just need to check the indices of inner 1s.\n\n\nOther hand, if two 1s aren\'t correctly separated, we can sniff that out first without having...
0
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
Python | BruteForce Solution
check-if-all-1s-are-at-least-length-k-places-away
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
Solution
check-if-all-1s-are-at-least-length-k-places-away
0
1
# Approach\nIterate through the array and check each distance\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n j = 0\n for x in nums:\n if j > 0 and x == 1:\n ret...
0
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`. **Example 1:** **Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2 **Output:** true **Explanation:** Each of the 1s are at least 2 places away from each other. **Example ...
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
C++ Solution with Easiest Explanation using Map (beats 83% runtime && 50% Memory)
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1-> We can use window sliding and keep all the values in map that can tell us min and max value in that window.\n2-> If the range (i.e., max-min) is greater than limit then we need to delete element from the left of window that we can do ...
2
Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ **Example 1:** **Input:** nums = \[8,2,4,7\], limit = 4 **Output:** 2 **Explanation:** All su...
null
Brute Force - Two Heaps - Treemap - Monotonic Queue, should be well-explained
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit
0
1
# Approach 1: Brute Force\nIn this approach, what I do is just create a max heap and a min heap for every number in the list and use nested for loop to find the valid "window "for every number and return the max one. \n\n# Complexity\n- Time complexity:\n$n^2log(n)$ because when pushing element to each heap, I need $lo...
5
Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ **Example 1:** **Input:** nums = \[8,2,4,7\], limit = 4 **Output:** 2 **Explanation:** All su...
null
Monotonic Queue Implementation
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit
0
1
```\nfrom collections import deque\n\nclass Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n maxQueue = deque()\n minQueue = deque()\n \n length = len(nums)\n \n i = 0\n maxSize = 0\n \n for j, num in enumerate(nums):\n ...
2
Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ **Example 1:** **Input:** nums = \[8,2,4,7\], limit = 4 **Output:** 2 **Explanation:** All su...
null
[Python3] | O(m * knlogkn)
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
```\nclass Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n row=len(mat)\n col=len(mat[0])\n temp=[i for i in mat[0]]\n for i in range(1,row):\n currSum=[]\n for j in range(col):\n for it in range(len(temp)):\n ...
2
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k ...
null
[Python3] | O(m * knlogkn)
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
```\nclass Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n row=len(mat)\n col=len(mat[0])\n temp=[i for i in mat[0]]\n for i in range(1,row):\n currSum=[]\n for j in range(col):\n for it in range(len(temp)):\n ...
2
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** tru...
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
Simple python3 solution | Heap | 122 ms - faster than 84.54% solutions
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Complexity\n- Time complexity: $$O(k \\cdot m \\cdot max(n, \\log(k \\cdot m)))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(k \\cdot m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nimport heapq\n\nclass Solution:\n def kthSmallest(self...
0
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k ...
null
Simple python3 solution | Heap | 122 ms - faster than 84.54% solutions
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Complexity\n- Time complexity: $$O(k \\cdot m \\cdot max(n, \\log(k \\cdot m)))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(k \\cdot m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nimport heapq\n\nclass Solution:\n def kthSmallest(self...
0
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** tru...
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
Python - 2 lines
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Complexity\n- Time complexity:\n$$O(MN^2klogk)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def kthSmallest(self, m, k):\n for r in range(1, len(m)): m[0] = sorted([a+b for a in m[0] for b in m[r][:]])[:k]\n return m[0][k-1]\n\n \n\n\n\n\n```
0
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k ...
null
Python - 2 lines
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Complexity\n- Time complexity:\n$$O(MN^2klogk)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def kthSmallest(self, m, k):\n for r in range(1, len(m)): m[0] = sorted([a+b for a in m[0] for b in m[r][:]])[:k]\n return m[0][k-1]\n\n \n\n\n\n\n```
0
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** tru...
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
MinHeap with Backtracking | Commented and Explained
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom the problem description we have at most 40 rows and 40 columns, and from which we will select the 200th smallest at worst. This gives us bounds that make a minheap with backtracking set up possible for our implementation needs, as th...
0
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k ...
null
MinHeap with Backtracking | Commented and Explained
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom the problem description we have at most 40 rows and 40 columns, and from which we will select the 200th smallest at worst. This gives us bounds that make a minheap with backtracking set up possible for our implementation needs, as th...
0
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** tru...
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
Python Priority Queue
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
\n# Approach\nUse a priority queue to keep track of current sum and its indexes. Pop next element from the queue, we can push new m elements to the queue by increasing index at each row by 1\n\n# Complexity\n- Time complexity:\nO(log(m * n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->...
0
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k ...
null
Python Priority Queue
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
\n# Approach\nUse a priority queue to keep track of current sum and its indexes. Pop next element from the queue, we can push new m elements to the queue by increasing index at each row by 1\n\n# Complexity\n- Time complexity:\nO(log(m * n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->...
0
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** tru...
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
Python (Simple Dijkstra's algorithm)
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
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 `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k ...
null
Python (Simple Dijkstra's algorithm)
find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. **Example 1:** **Input:** arr = \[2,6,4,1\] **Output:** false **Explanation:** There are no three consecutive odds. **Example 2:** **Input:** arr = \[1,2,34,3,4,5,7,23,12\] **Output:** tru...
Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1.
【Video】Give me 5 minutes - How we think about a solution
build-an-array-with-stack-operations
1
1
# Intuition\nThere is an answer in Example 1. lol\n\n---\n\n# Solution Video\n\nhttps://youtu.be/MCYiEw2zvNw\n\n\u25A0 Timeline of the video\n\n`0:04` Basic idea to solve this question\n`1:04` How do you operate each number from the steam of integers?\n`3:34` What operation we need for the two patterns\n`5:17` Coding\n...
7
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
【Video】Give me 5 minutes - How we think about a solution
build-an-array-with-stack-operations
1
1
# Intuition\nThere is an answer in Example 1. lol\n\n---\n\n# Solution Video\n\nhttps://youtu.be/MCYiEw2zvNw\n\n\u25A0 Timeline of the video\n\n`0:04` Basic idea to solve this question\n`1:04` How do you operate each number from the steam of integers?\n`3:34` What operation we need for the two patterns\n`5:17` Coding\n...
7
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
✅☑[C++/Java/Python/JavaScript] || Beats 100% || 2 Approaches || EXPLAINED🔥
build-an-array-with-stack-operations
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Brute Force)***\n\n\n1. We initialize an empty vector of strings called `ans`, which will store the sequence of "`Push`" and "`Pop`" instructions.\n\n1. We also initialize an integer `i` to `1`, which represen...
4
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
✅☑[C++/Java/Python/JavaScript] || Beats 100% || 2 Approaches || EXPLAINED🔥
build-an-array-with-stack-operations
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Brute Force)***\n\n\n1. We initialize an empty vector of strings called `ans`, which will store the sequence of "`Push`" and "`Pop`" instructions.\n\n1. We also initialize an integer `i` to `1`, which represen...
4
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
Python one line
build-an-array-with-stack-operations
0
1
```python []\nclass Solution:\n def buildArray(self, target: List[int], n: int) -> List[str]:\n return [\n x\n for i in range(1, target[-1] + 1)\n for x in ["Push"] + ["Pop"] * (i not in set(target))\n ]\n\n```
3
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
Python one line
build-an-array-with-stack-operations
0
1
```python []\nclass Solution:\n def buildArray(self, target: List[int], n: int) -> List[str]:\n return [\n x\n for i in range(1, target[-1] + 1)\n for x in ["Push"] + ["Pop"] * (i not in set(target))\n ]\n\n```
3
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
✅ 99.80% Iterative Set Stack Simulation
build-an-array-with-stack-operations
1
1
# Intuition\nGiven a target list of numbers and a stream of numbers from 1 to $ n $, the goal is to simulate a stack to recreate the target list using just "Push" and "Pop" operations. The intuitive approach is to push each number from the stream onto the stack. If the number is not in the target list, we pop it off im...
15
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
✅ 99.80% Iterative Set Stack Simulation
build-an-array-with-stack-operations
1
1
# Intuition\nGiven a target list of numbers and a stream of numbers from 1 to $ n $, the goal is to simulate a stack to recreate the target list using just "Push" and "Pop" operations. The intuitive approach is to push each number from the stream onto the stack. If the number is not in the target list, we pop it off im...
15
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
✅ Simulation Approach | 99.60% Faster | Nov Daily (Annoying desc -> Easy Q) ✅
build-an-array-with-stack-operations
0
1
# Intuition\nWhen you first read the problems description, it makes like 0 sense. Once you look at some of the test cases and constraints though, this question becomes a lot easier. First we see that every time we want to keep a value we only add a single "Push" and any time we don\'t want to, we add "Push" "Pop" and s...
1
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
✅ Simulation Approach | 99.60% Faster | Nov Daily (Annoying desc -> Easy Q) ✅
build-an-array-with-stack-operations
0
1
# Intuition\nWhen you first read the problems description, it makes like 0 sense. Once you look at some of the test cases and constraints though, this question becomes a lot easier. First we see that every time we want to keep a value we only add a single "Push" and any time we don\'t want to, we add "Push" "Pop" and s...
1
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
Understandable python using stacks
build-an-array-with-stack-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
Understandable python using stacks
build-an-array-with-stack-operations
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
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
Beats 97.44% of other users🔥
build-an-array-with-stack-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
Beats 97.44% of other users🔥
build-an-array-with-stack-operations
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
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
understandable code
build-an-array-with-stack-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the tw...
Check the bits one by one whether they need to be flipped.
understandable code
build-an-array-with-stack-operations
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
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** be...
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
O(n**2) straightforward python solution.
count-triplets-that-can-form-two-arrays-of-equal-xor
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\na == b means a ^ b == 0\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\niterative two pointers, the first reprersent the start search position of a, the second represent the end search position of b. Then calculate...
0
Given an array of integers `arr`. We want to select three indices `i`, `j` and `k` where `(0 <= i < j <= k < arr.length)`. Let's define `a` and `b` as follows: * `a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]` * `b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]` Note that **^** denotes the **bitwise-xor** operation. Return...
As long as there are at least (n - 1) connections, there is definitely a way to connect all computers. Use DFS to determine the number of isolated computer clusters.
O(n**2) straightforward python solution.
count-triplets-that-can-form-two-arrays-of-equal-xor
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\na == b means a ^ b == 0\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\niterative two pointers, the first reprersent the start search position of a, the second represent the end search position of b. Then calculate...
0
There are `n` oranges in the kitchen and you decided to eat some of these oranges every day as follows: * Eat one orange. * If the number of remaining oranges `n` is divisible by `2` then you can eat `n / 2` oranges. * If the number of remaining oranges `n` is divisible by `3` then you can eat `2 * (n / 3)` oran...
We are searching for sub-array of length ≥ 2 and we need to split it to 2 non-empty arrays so that the xor of the first array is equal to the xor of the second array. This is equivalent to searching for sub-array with xor = 0. Keep the prefix xor of arr in another array, check the xor of all sub-arrays in O(n^2), if th...
😯 Intuitive & Readable: Recursive, OO + Functional, Depth-First Tree Traversal Edge Count [Python]
minimum-time-to-collect-all-apples-in-a-tree
0
1
<i><span style="color:dodgerblue">Please upvote if you find this post useful.</span> \uD83D\uDE4F</i>\n\n---\n\n# Intuition\n\nThe essence of this problem can be simply stated as:\n\n> Count the number of edges that need to be traversed to reach all apples.\n\nThe requirement to count the "time" including "coming back"...
4
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
FASTEST SIMPLE PYTHON SOLUTION || DFS TRAVERSAL
minimum-time-to-collect-all-apples-in-a-tree
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(V+2E)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(V+E)$$\n<!-- Add your space complexity h...
3
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
✅ Easy python3 solution using DFS (beats 99% on time) ✅
minimum-time-to-collect-all-apples-in-a-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is to create a graph from the edges and not consider the input as a straight tree with all nodes in order.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst build the adjacency list from the edges. ...
1
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
[Python3] [Beats 100%] Linear Time & Space w/ No Hashtable
minimum-time-to-collect-all-apples-in-a-tree
0
1
# Intuition\n1. Find out every node\'s parent node. \n2. Traverse from each apple upward to the nearest seen node.\n\n# Approach\n1. For every edge, if we have already seen the left vertex, then know that the right vertex must be its child. The same holds for the reverse. We then record that we have seen the right vert...
1
Given an undirected tree consisting of `n` vertices numbered from `0` to `n-1`, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. _Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at **vertex 0** and coming back to this vertex....
Use dynamic programming. dp[i][j][k]: smallest movements when you have one finger on i-th char and the other one on j-th char already having written k first characters from word.
[Python] memorization and prefix sum; Explained
number-of-ways-of-cutting-a-pizza
0
1
The key to this problem is how to count the number of apples on the region we want to cut.\n\nWe can simply use the prefix sum that help to identify the number of apples between any two index.\n\nTherefore, we need to pre-process the input array, get the prefix sum horizatonally and vertically.\n\nWith the prefix sum a...
3
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
Clean Code Python
number-of-ways-of-cutting-a-pizza
0
1
**Please Upvote**\n```\nMOD = 1000000007\nclass Solution:\n def ways(self, pizza: List[str], k: int) -> int:\n \n m, n = len(pizza), len(pizza[0])\n \n @lru_cache(None)\n def dfs(k, i = 0, j = 0, res = 0):\n \n if not(0 <= i < m and 0 <= j < n): return 0\n\n ...
1
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
Python 3 Recursion with Memoization
number-of-ways-of-cutting-a-pizza
0
1
The basic intuition is recursively cut the pizza as the problem requests. After each cut we apply recursively the cut function to the remaining pizza. \n\n### A few ways to reduce time complexity\n- Use memoization (LRU-Caches)\n- Use coordinates of top-left and bottom-right corners to represent current pizza. It is ob...
1
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
✅Python3✅ DP+PrefSum+Memoization
number-of-ways-of-cutting-a-pizza
0
1
We can use dynamic programming to solve this problem. Let\'s define dp[i][j][p] as the number of ways to cut the pizza of size (i+1) * (j+1) into p pieces such that every piece contains at least one apple. The base cases are dp[i][j][1] = 1 if there is at least one apple in the pizza[i][j], otherwise dp[i][j][1] = 0.\n...
28
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
Image Explanation🏆- [DP + Prefix Sum] - C++/Java/Python
number-of-ways-of-cutting-a-pizza
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Number of Ways of Cutting a Pizza` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/65dab028-42d6-46b8-9b30-44feaed866d2_1680231935.7565331.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/231b4ea2-...
137
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
✔💯 DAY 365 | 100% | [JAVA/C++/PYTHON] | EXPLAINED | 4*3 WAYS | DRY RUN | PROOF 💫
number-of-ways-of-cutting-a-pizza
1
1
# Please Upvote as it really motivates me\n![image.png](https://assets.leetcode.com/users/images/ac94199d-6533-4955-b62e-00d9a0489529_1680226020.1444046.png)\n\n##### \u2022\tThey are several ways to solve the "Number of Ways of Cutting a Pizza" problem:\n##### \u2022\tDynamic Programming with Prefix Sums:\nThis is the...
11
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
✅✅Python🔥Simple Solution🔥Easy to Understand🔥
number-of-ways-of-cutting-a-pizza
1
1
# Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers this week. I planned to give for next 10,000 Subscribers a...
45
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
Clean Codes🔥🔥|| Full Explanation✅|| D.P✅|| C++|| Java|| Python3
number-of-ways-of-cutting-a-pizza
1
1
# Intuition :\n- We can cut pizza either horizontally or vertically provided that each piece has atleast one apple and we can use only k-1 cuts\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : use D.P to store no. of ways to cut pizza\n- `dp[m][n][k]` array stores the number of ways ...
7
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
Python DP code for reference
number-of-ways-of-cutting-a-pizza
0
1
Inspired by [this post](https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/solutions/623759/c-dp-cutting-with-picture-explanation/?orderBy=most_votes)\n```\nclass Solution:\n def ways(self, pizza: List[str], K: int) -> int:\n m,n = len(pizza),len(pizza[0])\n grid = [[0]*(n+1) for _ in rang...
4
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
(Python) No need prefix, Just Check!
number-of-ways-of-cutting-a-pizza
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 (r * c * k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O (r * c * k)\n<!-- Add your space compl...
10
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
Python3 | Space Optimized Bottom-Up DP | O(k * r * c * (r + c)) Time, O(r * c) Space
number-of-ways-of-cutting-a-pizza
0
1
Please upvote if it helps!\n```\nclass Solution:\n def ways(self, pizza: List[str], k: int) -> int:\n rows, cols = len(pizza), len(pizza[0])\n \n # first, need way to query if a section contains an apple given a top left (r1, c1) and bottom right (r2, c2)\n # we can do this in constant ti...
4
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut positi...
Simulate the process to get the final answer.
List usage O(N) solution
consecutive-characters
1
1
# Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Add the elements to the list and everytime u try to add the character just check the character that you are trying to add is equal to the present character if that is the case then increment the count and then store the v...
1
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string `s`, return _the **power** of_ `s`. **Example 1:** **Input:** s = "leetcode " **Output:** 2 **Explanation:** The substring "ee " is of length 2 with the character 'e' only. **Example ...
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
List usage O(N) solution
consecutive-characters
1
1
# Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Add the elements to the list and everytime u try to add the character just check the character that you are trying to add is equal to the present character if that is the case then increment the count and then store the v...
1
You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "3242415 " **Output:** 5 **Explanation:** "24241 " i...
Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).
Easy python solution
consecutive-characters
0
1
```\ndef maxPower(self, s: str) -> int:\n c,ans = 1,1\n for i in range(len(s)-1):\n if s[i]==s[i+1]:\n c+=1\n ans=max(c,ans)\n else:\n c=1\n return ans\n```
8
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string `s`, return _the **power** of_ `s`. **Example 1:** **Input:** s = "leetcode " **Output:** 2 **Explanation:** The substring "ee " is of length 2 with the character 'e' only. **Example ...
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
Easy python solution
consecutive-characters
0
1
```\ndef maxPower(self, s: str) -> int:\n c,ans = 1,1\n for i in range(len(s)-1):\n if s[i]==s[i+1]:\n c+=1\n ans=max(c,ans)\n else:\n c=1\n return ans\n```
8
You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "3242415 " **Output:** 5 **Explanation:** "24241 " i...
Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).
Python ✅✅✅ || Faster than 99.60% || Memory Beats 97.63%
consecutive-characters
0
1
# Code\n```\nclass Solution:\n def maxPower(self, s):\n cnt = 0\n m = 0\n for i in range(1, len(s)):\n if (s[i-1] == s[i]): \n cnt += 1\n m = max(cnt, m)\n else: cnt = 0\n return m + 1\n```\n![image.png](https://assets.leetcode.com/users...
3
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string `s`, return _the **power** of_ `s`. **Example 1:** **Input:** s = "leetcode " **Output:** 2 **Explanation:** The substring "ee " is of length 2 with the character 'e' only. **Example ...
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
Python ✅✅✅ || Faster than 99.60% || Memory Beats 97.63%
consecutive-characters
0
1
# Code\n```\nclass Solution:\n def maxPower(self, s):\n cnt = 0\n m = 0\n for i in range(1, len(s)):\n if (s[i-1] == s[i]): \n cnt += 1\n m = max(cnt, m)\n else: cnt = 0\n return m + 1\n```\n![image.png](https://assets.leetcode.com/users...
3
You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "3242415 " **Output:** 5 **Explanation:** "24241 " i...
Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).
Python O(n) by linear scan. [w/ Comment]
consecutive-characters
0
1
Python O(n) by linear scan.\n\n---\n\n```\nclass Solution:\n def maxPower(self, s: str) -> int:\n \n # the minimum value for consecutive is 1\n local_max, global_max = 1, 1\n \n # dummy char for initialization\n prev = \'#\'\n for char in s:\n \n ...
9
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string `s`, return _the **power** of_ `s`. **Example 1:** **Input:** s = "leetcode " **Output:** 2 **Explanation:** The substring "ee " is of length 2 with the character 'e' only. **Example ...
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
Python O(n) by linear scan. [w/ Comment]
consecutive-characters
0
1
Python O(n) by linear scan.\n\n---\n\n```\nclass Solution:\n def maxPower(self, s: str) -> int:\n \n # the minimum value for consecutive is 1\n local_max, global_max = 1, 1\n \n # dummy char for initialization\n prev = \'#\'\n for char in s:\n \n ...
9
You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "3242415 " **Output:** 5 **Explanation:** "24241 " i...
Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).
Python Solution | 99% Faster | Simple Logic - Iterative Checking Based
consecutive-characters
0
1
```\nclass Solution:\n def maxPower(self, s: str) -> int:\n if len(s) == 1:\n return 1\n count = 0\n i = 1\n ans = -inf\n while i < len(s):\n if s[i] == s[i-1]:\n count += 1\n ans = max(ans,count)\n else:\n ...
0
The **power** of the string is the maximum length of a non-empty substring that contains only one unique character. Given a string `s`, return _the **power** of_ `s`. **Example 1:** **Input:** s = "leetcode " **Output:** 2 **Explanation:** The substring "ee " is of length 2 with the character 'e' only. **Example ...
The tricky part is determining how the minute hand affects the position of the hour hand. Calculate the angles separately then find the difference.
Python Solution | 99% Faster | Simple Logic - Iterative Checking Based
consecutive-characters
0
1
```\nclass Solution:\n def maxPower(self, s: str) -> int:\n if len(s) == 1:\n return 1\n count = 0\n i = 1\n ans = -inf\n while i < len(s):\n if s[i] == s[i-1]:\n count += 1\n ans = max(ans,count)\n else:\n ...
0
You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome. Return _the length of the maximum length **awesome substring** of_ `s`. **Example 1:** **Input:** s = "3242415 " **Output:** 5 **Explanation:** "24241 " i...
Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]).
Easy | Python Solution | Hashmap
simplified-fractions
0
1
# Code\n```\nclass Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n vis = {}\n ans = []\n for i in range(1, n+1):\n for j in range(i+1, n+1):\n if i/j not in vis:\n vis[i/j] = 1\n ans.append(f"{i}/{j}")\n ret...
2
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
simple python solution
simplified-fractions
0
1
\n\n# Code\n```\nclass Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n l=[]\n l2=[]\n for i in range(1,n+1):\n for j in range(i+1,n+1):\n if i/j not in l2:\n l2.append(i/j)\n l.append(str(i)+\'/\'+str(j))\n ...
1
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Easy to understand Python3 solution
simplified-fractions
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
easy solution using 2 loop
simplified-fractions
0
1
## My solution\n```\nclass Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n ans = []\n for i in range(1, n):\n for j in range(i+1, n+1):\n if gcd(i, j)==1: ans.append(f\'{i}/{j}\')\n return ans\n```
0
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Python | Brute Force GCD
simplified-fractions
0
1
# Code\n```\nclass Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n res = [f"{n_}/{d_}" for d_ in range(2, n + 1) for n_ in range(1, d_) if gcd(n_, d_) == 1]\n return res\n```
0
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Python3 GCD
simplified-fractions
0
1
\n\n# Code\n```\nclass Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n \n ans=[]\n \n for i in range(2,n+1):\n j=1\n \n while j<i:\n if gcd(i,j)==1:\n ans.append(str(j)+"/"+str(i))\n j+=1\n...
0
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Simple python3 solution | 123 ms - faster than 100% solutions
simplified-fractions
0
1
# Complexity\n- Time complexity: $$O(n \\cdot n \\cdot log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nsee Euclidean algorithm\'s efficiency ([wiki](https://en.wikipedia.org/wiki/Euclidean_algorithm#Algorithmic_efficiency))\n\n- Space complexity: $$O(n \\cdot n)$$\n<!-- Add your space complexity here,...
0
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Python3 - Easy Solution
simplified-fractions
0
1
```\nclass Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n output = []\n for denominator in range(1, n+1):\n for numerator in range(1, denominator):\n if math.gcd(denominator, numerator) == 1:\n output.append(f\'{numerator}/{denominator}\')...
0
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Solution Python Easy
count-good-nodes-in-binary-tree
0
1
# Intuition\nUse preorder to compare nodes from top to bottom.\n\n# Approach\nWhile traversing to the bottom, save the lower limit as the maximum node value in the path, and compare it to each node.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(h), (O(n) for skewed tree, O(log(n) for balanced tree...
1
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Solution Python Easy
count-good-nodes-in-binary-tree
0
1
# Intuition\nUse preorder to compare nodes from top to bottom.\n\n# Approach\nWhile traversing to the bottom, save the lower limit as the maximum node value in the path, and compare it to each node.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(h), (O(n) for skewed tree, O(log(n) for balanced tree...
1
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string go...
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
Recursive approach✅ | O( n)✅ | (Step by step explanation)✅
count-good-nodes-in-binary-tree
0
1
# Intuition\nThe problem asks to find the number of "good" nodes in a binary tree. A node is considered "good" if its value is greater than or equal to the maximum value in the path from the root to that node.\n\n# Approach\nThe approach is based on a depth-first search (DFS) traversal of the binary tree. We maintain t...
1
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
Recursive approach✅ | O( n)✅ | (Step by step explanation)✅
count-good-nodes-in-binary-tree
0
1
# Intuition\nThe problem asks to find the number of "good" nodes in a binary tree. A node is considered "good" if its value is greater than or equal to the maximum value in the path from the root to that node.\n\n# Approach\nThe approach is based on a depth-first search (DFS) traversal of the binary tree. We maintain t...
1
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string go...
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
🥇 C++ | PYTHON || EXPLAINED || ; ]
count-good-nodes-in-binary-tree
0
1
**UPVOTE IF HELPFuuL**\n\n**APPROACH**\n\nAny sort of traversal would work here.\nWhile traversing the tree, keep a variable that stores the maximum value till now in the path.\nCompare it with node value to decide whether it is a ood node or not.\n\n\n**BASE CASE**\n* Return ```0```, whenever ```root == NULL```\n\n**R...
66
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
🥇 C++ | PYTHON || EXPLAINED || ; ]
count-good-nodes-in-binary-tree
0
1
**UPVOTE IF HELPFuuL**\n\n**APPROACH**\n\nAny sort of traversal would work here.\nWhile traversing the tree, keep a variable that stores the maximum value till now in the path.\nCompare it with node value to decide whether it is a ood node or not.\n\n\n**BASE CASE**\n* Return ```0```, whenever ```root == NULL```\n\n**R...
66
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string go...
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
[Python 3] Extremely Simple 8 Line Recursive Solution, beats >99%.
count-good-nodes-in-binary-tree
0
1
# Intuition\nWhether a node is "good" or not is based on the node before it. This screams "recursion" to me, so I took a shot at it.\n\n# Approach\nWe want our function to return an int (the number of good nodes). We could implement this by dragging a counter through each function as a variable and incrementing it as w...
3
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
[Python 3] Extremely Simple 8 Line Recursive Solution, beats >99%.
count-good-nodes-in-binary-tree
0
1
# Intuition\nWhether a node is "good" or not is based on the node before it. This screams "recursion" to me, so I took a shot at it.\n\n# Approach\nWe want our function to return an int (the number of good nodes). We could implement this by dragging a counter through each function as a variable and incrementing it as w...
3
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string go...
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
BFS With MaxValue | Template of Similar Problems Python
count-good-nodes-in-binary-tree
0
1
From very First problem I used to apply BFS only so i have come up with this soln.\nevery Easy/Mediam level Tree Problems has same concept of travesal of tree and keep track of other parameter like path or sum etc... you can use Same template given hear or your Own..\n\n```\nclass Solution:\n def goodNodes(self, roo...
99
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
BFS With MaxValue | Template of Similar Problems Python
count-good-nodes-in-binary-tree
0
1
From very First problem I used to apply BFS only so i have come up with this soln.\nevery Easy/Mediam level Tree Problems has same concept of travesal of tree and keep track of other parameter like path or sum etc... you can use Same template given hear or your Own..\n\n```\nclass Solution:\n def goodNodes(self, roo...
99
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string go...
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
✅[Python] DFS Iterative, beats 88%✅
count-good-nodes-in-binary-tree
0
1
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n# Intuition\nThe problem asks us to return the number of good nodes in a binary tree. A node is consid...
14
Given a binary tree `root`, a node _X_ in the tree is named **good** if in the path from root to _X_ there are no nodes with a value _greater than_ X. Return the number of **good** nodes in the binary tree. **Example 1:** **Input:** root = \[3,1,4,3,null,1,5\] **Output:** 4 **Explanation:** Nodes in blue are **good*...
Convert the number in an array of its digits. Brute force on every digit to get the maximum number.
✅[Python] DFS Iterative, beats 88%✅
count-good-nodes-in-binary-tree
0
1
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n# Intuition\nThe problem asks us to return the number of good nodes in a binary tree. A node is consid...
14
Given a string `s` of lower and upper case English letters. A good string is a string which doesn't have **two adjacent characters** `s[i]` and `s[i + 1]` where: * `0 <= i <= s.length - 2` * `s[i]` is a lower-case letter and `s[i + 1]` is the same letter but in upper-case or **vice-versa**. To make the string go...
Use DFS (Depth First Search) to traverse the tree, and constantly keep track of the current path maximum.
Python - knapsack with repetitions, bottom up DP
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Intuition\nWithin combinatorial optimization there are 3 school models of knapsack: fractional (greedy solution, easiest), integer with repetitions and integer without repetitions (hardest). This is integer with repetitions, weigth/capacity is target and cost, value is number constructed. Items to pick as much as you...
0
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python - knapsack with repetitions, bottom up DP
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Intuition\nWithin combinatorial optimization there are 3 school models of knapsack: fractional (greedy solution, easiest), integer with repetitions and integer without repetitions (hardest). This is integer with repetitions, weigth/capacity is target and cost, value is number constructed. Items to pick as much as you...
0
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows: * `S1 = "0 "` * `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1` Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert(x)` inverts all the bits in `x` (`0` changes to ...
Use dynamic programming to find the maximum digits to paint given a total cost. Build the largest number possible using this DP table.
Python | Easiest Solution Faster than 100% | Top Down Approach
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python | Easiest Solution Faster than 100% | Top Down Approach
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows: * `S1 = "0 "` * `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1` Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert(x)` inverts all the bits in `x` (`0` changes to ...
Use dynamic programming to find the maximum digits to paint given a total cost. Build the largest number possible using this DP table.
DFS+Memo || both 2d + 1d DP || Unbounded knapsack
form-largest-integer-with-digits-that-add-up-to-target
0
1
\n\n# Code\n```\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n\n\n dp = [-1]*(target+1) \n def dfs(t):\n\n if t==0: return 0 \n if t<0: return -inf \n\n if dp[t] != -1: return dp[t] \n\n \n dp[t] = max(dfs(t - c...
0
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
DFS+Memo || both 2d + 1d DP || Unbounded knapsack
form-largest-integer-with-digits-that-add-up-to-target
0
1
\n\n# Code\n```\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n\n\n dp = [-1]*(target+1) \n def dfs(t):\n\n if t==0: return 0 \n if t<0: return -inf \n\n if dp[t] != -1: return dp[t] \n\n \n dp[t] = max(dfs(t - c...
0
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows: * `S1 = "0 "` * `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1` Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert(x)` inverts all the bits in `x` (`0` changes to ...
Use dynamic programming to find the maximum digits to paint given a total cost. Build the largest number possible using this DP table.
Python (Simple DP)
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.
Python (Simple DP)
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given two positive integers `n` and `k`, the binary string `Sn` is formed as follows: * `S1 = "0 "` * `Si = Si - 1 + "1 " + reverse(invert(Si - 1))` for `i > 1` Where `+` denotes the concatenation operation, `reverse(x)` returns the reversed string `x`, and `invert(x)` inverts all the bits in `x` (`0` changes to ...
Use dynamic programming to find the maximum digits to paint given a total cost. Build the largest number possible using this DP table.
PYTHON SIMPLE DP ᓚᘏᗢ
form-largest-integer-with-digits-that-add-up-to-target
0
1
# Approach\ndp which is easy to see and read :) <3\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n\n# Code\n```\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n dp=[""]*(target+1)\n for i in range(0,target+1):\n for j in range(1,10...
0
Given an array of integers `cost` and an integer `target`, return _the **maximum** integer you can paint under the following rules_: * The cost of painting a digit `(i + 1)` is given by `cost[i]` (**0-indexed**). * The total cost used must be equal to `target`. * The integer does not have `0` digits. Since the ...
Use the maximum length of words to determine the length of the returned answer. However, don't forget to remove trailing spaces.