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 |
|---|---|---|---|---|---|---|---|
Image Explanation🏆- [Recursion -> Memo(4 states - 2 states) -> Bottom Up] - C++/Java/Python | minimum-cost-to-cut-a-stick | 1 | 1 | \n\n# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Minimum Cost to Cut a Stick` by `Aryan Mittal`\n\n\n\n# Approach & Intution\n + (j - i) for all possible cuts k between them. |
Python short and clean. Functional programming. | minimum-cost-to-cut-a-stick | 0 | 1 | # Complexity\n- Time complexity: $$O(m ^ 3)$$\n\n- Space complexity: $$O(m ^ 2)$$\n\nwhere, `m is the number of cuts`.\n\n# Code\n```python\nclass Solution:\n def minCost(self, n: int, cuts: list[int]) -> int:\n s_cuts = sorted(chain(cuts, (0, n)))\n\n @cache\n def min_cost(i: int, j: int) -> in... | 2 | 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. |
Python short and clean. Functional programming. | minimum-cost-to-cut-a-stick | 0 | 1 | # Complexity\n- Time complexity: $$O(m ^ 3)$$\n\n- Space complexity: $$O(m ^ 2)$$\n\nwhere, `m is the number of cuts`.\n\n# Code\n```python\nclass Solution:\n def minCost(self, n: int, cuts: list[int]) -> int:\n s_cuts = sorted(chain(cuts, (0, n)))\n\n @cache\n def min_cost(i: int, j: int) -> in... | 2 | You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively.
Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place.
The blue edges and nodes in the following figure indicate the result:
_Build the result list and return its head._
**Example 1:**
**In... | Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them. |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | minimum-cost-to-cut-a-stick | 1 | 1 | **!! 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 is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u... | 18 | 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. |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | minimum-cost-to-cut-a-stick | 1 | 1 | **!! 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 is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u... | 18 | You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively.
Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place.
The blue edges and nodes in the following figure indicate the result:
_Build the result list and return its head._
**Example 1:**
**In... | Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them. |
Tabulation (Bottom up) | Python / JS Solution | minimum-cost-to-cut-a-stick | 0 | 1 | Hello **Tenno Leetcoders**, \n\nFor this problem, we a given a wooden stick of length `n` units, where the stick is labelled from `0` to `n` and array `cuts` where `cuts[i]` denotes a position you should perform a cut at. \n\nPerforming the cuts in order with the cost of one cut is the length of the stick to be cut, th... | 5 | 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. |
Tabulation (Bottom up) | Python / JS Solution | minimum-cost-to-cut-a-stick | 0 | 1 | Hello **Tenno Leetcoders**, \n\nFor this problem, we a given a wooden stick of length `n` units, where the stick is labelled from `0` to `n` and array `cuts` where `cuts[i]` denotes a position you should perform a cut at. \n\nPerforming the cuts in order with the cost of one cut is the length of the stick to be cut, th... | 5 | You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively.
Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place.
The blue edges and nodes in the following figure indicate the result:
_Build the result list and return its head._
**Example 1:**
**In... | Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them. |
Python || Bottom Up DP || Easy To Understand 🔥 | minimum-cost-to-cut-a-stick | 0 | 1 | # Code\n```\nclass Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts.sort()\n cuts = [0] + cuts + [n]\n m = len(cuts)\n dp = [[0] * m for _ in range(m)]\n for i in range(m - 2, -1, -1):\n for j in range(i + 2, m):\n mini = float(\'inf\'... | 2 | 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. |
Python || Bottom Up DP || Easy To Understand 🔥 | minimum-cost-to-cut-a-stick | 0 | 1 | # Code\n```\nclass Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts.sort()\n cuts = [0] + cuts + [n]\n m = len(cuts)\n dp = [[0] * m for _ in range(m)]\n for i in range(m - 2, -1, -1):\n for j in range(i + 2, m):\n mini = float(\'inf\'... | 2 | You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively.
Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place.
The blue edges and nodes in the following figure indicate the result:
_Build the result list and return its head._
**Example 1:**
**In... | Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them. |
Python easy to understand | three-consecutive-odds | 0 | 1 | ```\ndef threeConsecutiveOdds(self, arr: List[int]) -> bool:\n count = 0\n for num in arr:\n if num % 2 != 0:\n count += 1\n if count == 3:\n return True\n else:\n count = 0\n return False | 1 | 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 easy to understand | three-consecutive-odds | 0 | 1 | ```\ndef threeConsecutiveOdds(self, arr: List[int]) -> bool:\n count = 0\n for num in arr:\n if num % 2 != 0:\n count += 1\n if count == 3:\n return True\n else:\n count = 0\n return False | 1 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Python beats 99%, use string | three-consecutive-odds | 0 | 1 | ```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n return "111" in "".join([str(i%2) for i in arr])\n``` | 41 | 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 beats 99%, use string | three-consecutive-odds | 0 | 1 | ```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n return "111" in "".join([str(i%2) for i in arr])\n``` | 41 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Python Easy Solution | three-consecutive-odds | 0 | 1 | # Code\n```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n if len(arr)<3:\n return 0\n window=[arr[0]%2,arr[1]%2,arr[2]%2]\n if window==[1,1,1]:\n return 1\n for i in range(3,len(arr)):\n window.pop(0)\n window.appe... | 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. |
Python Easy Solution | three-consecutive-odds | 0 | 1 | # Code\n```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n if len(arr)<3:\n return 0\n window=[arr[0]%2,arr[1]%2,arr[2]%2]\n if window==[1,1,1]:\n return 1\n for i in range(3,len(arr)):\n window.pop(0)\n window.appe... | 2 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Simple loop python | three-consecutive-odds | 0 | 1 | ```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n c=0\n for i in arr:\n if i%2==0:\n c=0\n else:\n c+=1\n if c==3:\n return True\n return False\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 loop python | three-consecutive-odds | 0 | 1 | ```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n c=0\n for i in arr:\n if i%2==0:\n c=0\n else:\n c+=1\n if c==3:\n return True\n return False\n``` | 2 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Python3 straight forward solution | three-consecutive-odds | 0 | 1 | ```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n count = 0\n \n for i in range(0, len(arr)):\n if arr[i] %2 != 0:\n count += 1\n if count == 3:\n return True\n else:\n count = 0\... | 21 | 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. |
Python3 straight forward solution | three-consecutive-odds | 0 | 1 | ```\nclass Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n count = 0\n \n for i in range(0, len(arr)):\n if arr[i] %2 != 0:\n count += 1\n if count == 3:\n return True\n else:\n count = 0\... | 21 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Most easiest python code✅✅ | minimum-operations-to-make-array-equal | 0 | 1 | \n\n# Approach\nIF LENGTH OF str = even \nwe need to sum first n//2 odd numbers\nwhich n//2 square\nand vice versa\n\n# Complexity\n- Time complexity:\nI think it will be o(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, n: i... | 2 | You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`).
In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e., perform `arr[x] -=1` and `arr[y] += 1`). The goal is to make ... | null |
Most easiest python code✅✅ | minimum-operations-to-make-array-equal | 0 | 1 | \n\n# Approach\nIF LENGTH OF str = even \nwe need to sum first n//2 odd numbers\nwhich n//2 square\nand vice versa\n\n# Complexity\n- Time complexity:\nI think it will be o(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minOperations(self, n: i... | 2 | You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive.
The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same nu... | Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ? |
[Python] O(1) solution using math | minimum-operations-to-make-array-equal | 0 | 1 | # Code\n```python []\nclass Solution:\n def minOperations(self, n: int) -> int:\n return (n ** 2) // 4\n```\n# Approach\nIf we look attentively, we\'ll discover that the array arr is a sequence of odd numbers.\nFirst, I tried to find any rule or regularity in answers, and I nociced that we should do all opera... | 10 | You have an array `arr` of length `n` where `arr[i] = (2 * i) + 1` for all valid values of `i` (i.e., `0 <= i < n`).
In one operation, you can select two indices `x` and `y` where `0 <= x, y < n` and subtract `1` from `arr[x]` and add `1` to `arr[y]` (i.e., perform `arr[x] -=1` and `arr[y] += 1`). The goal is to make ... | null |
[Python] O(1) solution using math | minimum-operations-to-make-array-equal | 0 | 1 | # Code\n```python []\nclass Solution:\n def minOperations(self, n: int) -> int:\n return (n ** 2) // 4\n```\n# Approach\nIf we look attentively, we\'ll discover that the array arr is a sequence of odd numbers.\nFirst, I tried to find any rule or regularity in answers, and I nociced that we should do all opera... | 10 | You are given an integer array `nums` of **even** length `n` and an integer `limit`. In one move, you can replace any integer from `nums` with another integer between `1` and `limit`, inclusive.
The array `nums` is **complementary** if for all indices `i` (**0-indexed**), `nums[i] + nums[n - 1 - i]` equals the same nu... | Build the array arr using the given formula, define target = sum(arr) / n What is the number of operations needed to convert arr so that all elements equal target ? |
Binary search approach with explanation | magnetic-force-between-two-balls | 0 | 1 | Please upvote if you like my solution. Let me know in the comments if you have any suggestions to increase performance or readability.\n# Code\n```\nclass Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n # Sort the position array in ascending order\n position.sort()\n \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. |
Binary search approach with explanation | magnetic-force-between-two-balls | 0 | 1 | Please upvote if you like my solution. Let me know in the comments if you have any suggestions to increase performance or readability.\n# Code\n```\nclass Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n # Sort the position array in ascending order\n position.sort()\n \n ... | 1 | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array wil... | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. |
Python binary search with Explanation. | magnetic-force-between-two-balls | 0 | 1 | # Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n position.sort()\n\n # To ch... | 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. |
Python binary search with Explanation. | magnetic-force-between-two-balls | 0 | 1 | # Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n position.sort()\n\n # To ch... | 1 | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array wil... | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. |
99.8% SC and 68% TC easy python solution | magnetic-force-between-two-balls | 0 | 1 | Feel free to ask... :)\n```\ndef maxDistance(self, position: List[int], m: int) -> int:\n\tposition.sort()\n\tn = len(position)\n\tdef isValid(force):\n\t\tstart = position[0]\n\t\tcount = 1\n\t\twhile(count < m):\n\t\t\tstart += force\n\t\t\ti = bisect_left(position, start)\n\t\t\tif(i == n):\n\t\t\t\treturn False\n\t... | 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. |
99.8% SC and 68% TC easy python solution | magnetic-force-between-two-balls | 0 | 1 | Feel free to ask... :)\n```\ndef maxDistance(self, position: List[int], m: int) -> int:\n\tposition.sort()\n\tn = len(position)\n\tdef isValid(force):\n\t\tstart = position[0]\n\t\tcount = 1\n\t\twhile(count < m):\n\t\t\tstart += force\n\t\t\ti = bisect_left(position, start)\n\t\t\tif(i == n):\n\t\t\t\treturn False\n\t... | 1 | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array wil... | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. |
[Python3] bfs | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | Think of this problem as a tree in which we start from the root `n`. At any node, it connects to up to 3 childrens `n-1`, `n//2` if `n%2 == 0`, `n//3` if `n%3 == 0`. Then we can level order traverse the tree and find the first occurrence of `0` and return its level. \n\n```\nclass Solution:\n def minDays(self, n: in... | 27 | 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... |
[Python3] bfs | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | Think of this problem as a tree in which we start from the root `n`. At any node, it connects to up to 3 childrens `n-1`, `n//2` if `n%2 == 0`, `n//3` if `n%3 == 0`. Then we can level order traverse the tree and find the first occurrence of `0` and return its level. \n\n```\nclass Solution:\n def minDays(self, n: in... | 27 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
Simple DP - beats 97 % of the submitted solutions. | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n memo = {}\n\n def dp(remaining):\n if remaining <= 1:\n return remaining\n if remaining not in memo:\n memo[remaining] = 1 + min(\n remaining % 2 + dp(remaining // 2... | 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... |
Simple DP - beats 97 % of the submitted solutions. | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n memo = {}\n\n def dp(remaining):\n if remaining <= 1:\n return remaining\n if remaining not in memo:\n memo[remaining] = 1 + min(\n remaining % 2 + dp(remaining // 2... | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
O(logn) time | O(n) space | solution explained | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe max days can be n if we eat one orange a day. \n\nWe will start with n oranges and eat oranges every day to reduce n to 0 or 1. For each day, we have two options/paths: eat n/2 oranges a day or n/3 oranges\n\nDo DFS to explore all pat... | 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... |
O(logn) time | O(n) space | solution explained | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe max days can be n if we eat one orange a day. \n\nWe will start with n oranges and eat oranges every day to reduce n to 0 or 1. For each day, we have two options/paths: eat n/2 oranges a day or n/3 oranges\n\nDo DFS to explore all pat... | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
Python3 BFS approach with Visited Set for Decision Tree Trimming | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs many people know, using a __BFS__ is often used as a fastest path algorithm because we know that no matter how many paths we take, whatever node\'s path reaches our solution first will have by definition been the fastest.\n\nKnowing th... | 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... |
Python3 BFS approach with Visited Set for Decision Tree Trimming | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs many people know, using a __BFS__ is often used as a fastest path algorithm because we know that no matter how many paths we take, whatever node\'s path reaches our solution first will have by definition been the fastest.\n\nKnowing th... | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
logn time | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n dp = {0:0,1:1} # base case\n\n def dfs(n):\n if n in dp:\n return dp[n]\n\n one = 1 + (n % 2) + dfs(n // 2)\n two = 1 + (n % 3) + dfs(n // 3)\n\n dp[n] = min(one,two)\n ... | 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... |
logn time | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n dp = {0:0,1:1} # base case\n\n def dfs(n):\n if n in dp:\n return dp[n]\n\n one = 1 + (n % 2) + dfs(n // 2)\n two = 1 + (n % 3) + dfs(n // 3)\n\n dp[n] = min(one,two)\n ... | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
[Python] Simple BFS | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n\n seen = set()\n\n heap = [(0,n)]\n\n while heap:\n count, node = heapq.heappop(heap)\n\n if node == 0: return count\n\n if node % 2 == 0 and node - (node // 2) not in seen:\n h... | 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... |
[Python] Simple BFS | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n\n seen = set()\n\n heap = [(0,n)]\n\n while heap:\n count, node = heapq.heappop(heap)\n\n if node == 0: return count\n\n if node % 2 == 0 and node - (node // 2) not in seen:\n h... | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
Python - one line | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Code\n```\nclass Solution:\n @cache\n def minDays(self, n: int) -> int: \n return n if n < 2 else 1 + min(n%2 + self.minDays(n//2), n%3 + self.minDays(n//3))\n \n``` | 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... |
Python - one line | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Code\n```\nclass Solution:\n @cache\n def minDays(self, n: int) -> int: \n return n if n < 2 else 1 + min(n%2 + self.minDays(n//2), n%3 + self.minDays(n//3))\n \n``` | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
Concise solution on Python3 | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n \n q = deque([n])\n s = set([n])\n cnt = 0\n\n while q:\n sz = len(q)\n for _ in range(sz):\n cur = q.popleft()\n if cur <= 1:\n return cnt + cu... | 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... |
Concise solution on Python3 | minimum-number-of-days-to-eat-n-oranges | 0 | 1 | # Code\n```\nclass Solution:\n def minDays(self, n: int) -> int:\n \n q = deque([n])\n s = set([n])\n cnt = 0\n\n while q:\n sz = len(q)\n for _ in range(sz):\n cur = q.popleft()\n if cur <= 1:\n return cnt + cu... | 0 | Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**.
Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wik... | In each step, choose between 2 options:
minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) )
where f(n) is the minimum number of days to eat n oranges. |
Simple code using join( ) string method | thousand-separator | 0 | 1 | # Approach\n- convert n to string and reverse the string\n- iterate through the string and select 3 items at a time and also join \'.\' with after 3 items.\n\n# Code\n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n s=str(n)\n s=s[::-1]\n res = \'.\'.join(s[i:i + 3] for i in... | 1 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
Simple code using join( ) string method | thousand-separator | 0 | 1 | # Approach\n- convert n to string and reverse the string\n- iterate through the string and select 3 items at a time and also join \'.\' with after 3 items.\n\n# Code\n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n s=str(n)\n s=s[::-1]\n res = \'.\'.join(s[i:i + 3] for i in... | 1 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
Python 3 by reversing | thousand-separator | 0 | 1 | ```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n s=str(n)\n s=s[::-1]\n res = \'.\'.join(s[i:i + 3] for i in range(0, len(s), 3))\n return res[::-1]\n``` | 39 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
Python 3 by reversing | thousand-separator | 0 | 1 | ```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n s=str(n)\n s=s[::-1]\n res = \'.\'.join(s[i:i + 3] for i in range(0, len(s), 3))\n return res[::-1]\n``` | 39 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
[Python3] 1-line | thousand-separator | 0 | 1 | \n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n return f"{n:,}".replace(",", ".")\n```\n\nAlternatively, \n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n ans = deque()\n while n: \n n, d = divmod(n, 1000)\n ans.appendleft(f"{d... | 28 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
[Python3] 1-line | thousand-separator | 0 | 1 | \n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n return f"{n:,}".replace(",", ".")\n```\n\nAlternatively, \n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n ans = deque()\n while n: \n n, d = divmod(n, 1000)\n ans.appendleft(f"{d... | 28 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
Python simple join solution | thousand-separator | 0 | 1 | **Python :**\n\n```\ndef thousandSeparator(self, n: int) -> str:\n\tres = str(n)[::-1]\n\tres = \'.\'.join(res[i:i + 3] for i in range(0, len(res), 3))\n\n\treturn res[::-1]\n```\n\n**Like it ? please upvote !** | 4 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
Python simple join solution | thousand-separator | 0 | 1 | **Python :**\n\n```\ndef thousandSeparator(self, n: int) -> str:\n\tres = str(n)[::-1]\n\tres = \'.\'.join(res[i:i + 3] for i in range(0, len(res), 3))\n\n\treturn res[::-1]\n```\n\n**Like it ? please upvote !** | 4 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
Python Solution | thousand-separator | 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`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
Python Solution | thousand-separator | 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 have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
🔥O(N) SOLVE! 🔥97% BEAT RUNTIME!!!🔥 UPVOTE IF I HELP, PLS:)📈📈📈 | thousand-separator | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n**O(N)**\n\n- Sp... | 0 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
🔥O(N) SOLVE! 🔥97% BEAT RUNTIME!!!🔥 UPVOTE IF I HELP, PLS:)📈📈📈 | thousand-separator | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n**O(N)**\n\n- Sp... | 0 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
python | thousand-separator | 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`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
python | thousand-separator | 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 have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
My simple solution! Beats 100.00% of users with Python 3 | thousand-separator | 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)$$ --\nhttps://leetcode.com/problems/thousand-separator/submissions/1108574073>\nhtt... | 0 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
My simple solution! Beats 100.00% of users with Python 3 | thousand-separator | 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)$$ --\nhttps://leetcode.com/problems/thousand-separator/submissions/1108574073>\nhtt... | 0 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
Python O(N) | thousand-separator | 0 | 1 | \n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n```\nclass Solution(object):\n def thousandSeparator(self, n):\n if n == 0:\n return \'0\'\n top, count = \'\', 0\n while n:\n top = str(n%10) + top\n count += 1\n n //= 1... | 0 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
Python O(N) | thousand-separator | 0 | 1 | \n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n```\nclass Solution(object):\n def thousandSeparator(self, n):\n if n == 0:\n return \'0\'\n top, count = \'\', 0\n while n:\n top = str(n%10) + top\n count += 1\n n //= 1... | 0 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
another solution from my side......nd its pretty fast | thousand-separator | 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`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
another solution from my side......nd its pretty fast | thousand-separator | 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 have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
Simple solution for beginer | thousand-separator | 0 | 1 | # Code\n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n # using regex style\n # 38ms\n # Beats 54.37% of users with Python3\n """\n import re\n return re.sub("(\\d)(?=(\\d{3})+(?!\\d))", r"\\1.", "%d" % n)\n """\n\n # python built in functi... | 0 | Given an integer `n`, add a dot ( ". ") as the thousands separator and return it in string format.
**Example 1:**
**Input:** n = 987
**Output:** "987 "
**Example 2:**
**Input:** n = 1234
**Output:** "1.234 "
**Constraints:**
* `0 <= n <= 231 - 1` | Each element of target should have a corresponding element in arr, and if it doesn't have a corresponding element, return false. To solve it easiely you can sort the two arrays and check if they are equal. |
Simple solution for beginer | thousand-separator | 0 | 1 | # Code\n```\nclass Solution:\n def thousandSeparator(self, n: int) -> str:\n # using regex style\n # 38ms\n # Beats 54.37% of users with Python3\n """\n import re\n return re.sub("(\\d)(?=(\\d{3})+(?!\\d))", r"\\1.", "%d" % n)\n """\n\n # python built in functi... | 0 | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... | Scan from the back of the integer and use dots to connect blocks with length 3 except the last block. |
Python 2-Line Simple Solution | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | # Intuition\nAll nodes with no indegrees must be in the final list. All other nodes can be reached since they have indegrees, and therefore should not be in the final list.\n\n# Approach\nAdd the "to" node in each edge to a "connected" set. Then iterate through all nodes n and add them to the final list if they are not... | 3 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Efficient DFS solution | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def dfs(self, vertex, first=False):\n if vertex in self.reachable:\n return\n if not first:\n self.reachable.add(vertex)\n first = False\n for _vertex in s... | 2 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Python3 Solution | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | \n```\nclass Solution:\n def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n parent=[False]*n\n for u,v in edges:\n parent[v]=True\n\n ans=[]\n for u in range(n):\n if not parent[u]:\n ans.append(u)\n\n return ans... | 1 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Indegree Aapproach || Python || O(n) Approach | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n visited=[0]*n\n res=[]\n for i in range(len(edges)):\n visited[edges[i][1]]+=1\n for i in ra... | 1 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
[Python] | O(E)/O(V) | One-liner | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | # Intuition\nIf a node doesn\'t have an inbound edge - we must to include it. All other nodes are reachable, starting from some other node.\n\n# Complexity\n- Time complexity:\n$O(e)$, where $e$ - `len(edges)`\n\n- Space complexity:\n$O(n)$\n\n# Code\n```\nclass Solution:\n def findSmallestSetOfVertices(self, n: int... | 1 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Python/Union Find/Easy | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n l=[i for i in range(n)]\n ans=[]\n for i,j in edges:\n if(l[j]==j):\n l[j]=l[i]\n for i in range(n):\n if(l[i]==i):\n ... | 1 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
🐇 Fast and stupid | Java, C++, Python | minimum-number-of-vertices-to-reach-all-nodes | 1 | 1 | # TL;DR\n``` java []\nclass Solution {\n public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) {\n var nonRoots = new boolean[n];\n for (var edge: edges) {\n nonRoots[edge.get(1)] = true;\n }\n var result = new LinkedList<Integer>();\n for (int... | 1 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Easily undestandable Python3 solution | minimum-number-of-vertices-to-reach-all-nodes | 0 | 1 | # Intuition\nIn this problem, we only have to find the nodes that cannot be reached by any other node. This is the case as if a node has an incoming edge, it will be found. Therefore, the problem reduces to finding the nodes without any any incoming edges. \n# Approach\n<!-- Describe your approach to solving the proble... | 1 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ... | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Easy python solution, with 90% SC | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | ```\ndef minOperations(self, nums: List[int]) -> int:\n\tn = len(nums)\n\tans = 0\n\tnums.sort()\n\twhile(nums[-1] > 0):\n\t\tfor i in range(n):\n\t\t\tif(nums[i] % 2):\n\t\t\t\tnums[i] -= 1\n\t\t\t\tans += 1\n\t\tif(nums[-1] > 0):\n\t\t\tfor i in range(n):\n\t\t\t\tnums[i] //= 2\n\t\t\tans += 1\n\treturn ans\n``` | 3 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls t... | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Easy python solution, with 90% SC | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | ```\ndef minOperations(self, nums: List[int]) -> int:\n\tn = len(nums)\n\tans = 0\n\tnums.sort()\n\twhile(nums[-1] > 0):\n\t\tfor i in range(n):\n\t\t\tif(nums[i] % 2):\n\t\t\t\tnums[i] -= 1\n\t\t\t\tans += 1\n\t\tif(nums[-1] > 0):\n\t\t\tfor i in range(n):\n\t\t\t\tnums[i] //= 2\n\t\t\tans += 1\n\treturn ans\n``` | 3 | Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "... | Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even. |
[Python3] Simple intuition without bitwise operations | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | - For any element in an array, consider it a sequence of addition of 1 and multiplication by 2. eg (`2 = +1, *2`) (`5 = +1, *2, +1`)\n- Each addition operation will be done separately, so we need to simply count all of them\n- But when it comes to the multiplication, we can simply find what is the maximum number of mul... | 28 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls t... | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
[Python3] Simple intuition without bitwise operations | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | - For any element in an array, consider it a sequence of addition of 1 and multiplication by 2. eg (`2 = +1, *2`) (`5 = +1, *2, +1`)\n- Each addition operation will be done separately, so we need to simply count all of them\n- But when it comes to the multiplication, we can simply find what is the maximum number of mul... | 28 | Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "... | Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even. |
Python3・9 lines・T/S: O(n), O(1)・T: 100% | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRephrase the two operations: \n```op == 0```: increment 1; i.e. set rightmost bit to 1 if it is 0\n```op == 1```: multiply all by 2; i.e. left bitshift on all ```nums``` by 1\n\nThen, the minimum number of operations is equal to the minim... | 0 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls t... | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Python3・9 lines・T/S: O(n), O(1)・T: 100% | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRephrase the two operations: \n```op == 0```: increment 1; i.e. set rightmost bit to 1 if it is 0\n```op == 1```: multiply all by 2; i.e. left bitshift on all ```nums``` by 1\n\nThen, the minimum number of operations is equal to the minim... | 0 | Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "... | Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even. |
Minimum Numbers of Function Calls to Make Target Array | minimum-numbers-of-function-calls-to-make-target-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)$$ --... | 0 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls t... | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Minimum Numbers of Function Calls to Make Target Array | minimum-numbers-of-function-calls-to-make-target-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)$$ --... | 0 | Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "... | Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even. |
Subtracting or dividing backwards | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | # Intuition\nIt\'s hard to me that how to determine at which step we should add 1 or multiply by two. Since the number of steps remain unchanged, starting from arr to [0 .. 0] is easier.\n\n# Approach\nIf there is an odd in arr, minus one.\nElse divide it by two.\nRepeat the process until [0 .. 0] is obtained.\n\n# Com... | 0 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls t... | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Subtracting or dividing backwards | minimum-numbers-of-function-calls-to-make-target-array | 0 | 1 | # Intuition\nIt\'s hard to me that how to determine at which step we should add 1 or multiply by two. Since the number of steps remain unchanged, starting from arr to [0 .. 0] is easier.\n\n# Approach\nIf there is an odd in arr, minus one.\nElse divide it by two.\nRepeat the process until [0 .. 0] is obtained.\n\n# Com... | 0 | Given two string arrays `word1` and `word2`, return `true` _if the two arrays **represent** the same string, and_ `false` _otherwise._
A string is **represented** by an array if the array elements concatenated **in order** forms the string.
**Example 1:**
**Input:** word1 = \[ "ab ", "c "\], word2 = \[ "a ", "bc "... | Work backwards: try to go from nums to arr. You should try to divide by 2 as much as possible, but you can only divide by 2 if everything is even. |
67% Tc and 56% SC easy python solution | detect-cycles-in-2d-grid | 0 | 1 | ```\ndef containsCycle(self, grid: List[List[str]]) -> bool:\n\tm, n = len(grid), len(grid[0])\n\tdir = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\t@lru_cache(None)\n\tdef isCycle(i, j, par_i, par_j):\n\t\tif (i, j) in vis:\n\t\t\treturn True\n\t\tvis.add((i, j))\n\t\tfor x, y in dir:\n\t\t\tif(0<=i+x<m and 0<=j+y<n and grid... | 2 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f... | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
67% Tc and 56% SC easy python solution | detect-cycles-in-2d-grid | 0 | 1 | ```\ndef containsCycle(self, grid: List[List[str]]) -> bool:\n\tm, n = len(grid), len(grid[0])\n\tdir = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\t@lru_cache(None)\n\tdef isCycle(i, j, par_i, par_j):\n\t\tif (i, j) in vis:\n\t\t\treturn True\n\t\tvis.add((i, j))\n\t\tfor x, y in dir:\n\t\t\tif(0<=i+x<m and 0<=j+y<n and grid... | 2 | The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of... | Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle. |
[Python3] DFS concise code | detect-cycles-in-2d-grid | 0 | 1 | - The trick was to keep track of the previous element so that you don\'t go back there wihle doing dfs (took me a long time to figure out)\n- We just check that while doing dfs we reach a node that we have already seen or not\n```python\nclass Solution:\n def containsCycle(self, A: List[List[str]]) -> bool:\n ... | 10 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f... | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
[Python3] DFS concise code | detect-cycles-in-2d-grid | 0 | 1 | - The trick was to keep track of the previous element so that you don\'t go back there wihle doing dfs (took me a long time to figure out)\n- We just check that while doing dfs we reach a node that we have already seen or not\n```python\nclass Solution:\n def containsCycle(self, A: List[List[str]]) -> bool:\n ... | 10 | The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of... | Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle. |
Python Solution | detect-cycles-in-2d-grid | 0 | 1 | # Code\n```\nclass Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n rows, cols = len(grid), len(grid[0])\n seen = set()\n\n def dfs(row, col, prev):\n if (row < 0 or row >= rows or\n col < 0 or col >= cols or\n grid[row][col] != grid[... | 0 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f... | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
Python Solution | detect-cycles-in-2d-grid | 0 | 1 | # Code\n```\nclass Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n rows, cols = len(grid), len(grid[0])\n seen = set()\n\n def dfs(row, col, prev):\n if (row < 0 or row >= rows or\n col < 0 or col >= cols or\n grid[row][col] != grid[... | 0 | The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of... | Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle. |
BEATS 90%! Python3 BFS | detect-cycles-in-2d-grid | 0 | 1 | # Code\n```\nimport collections\n\n\nclass Solution:\n\n def containsCycle(self, grid: List[List[str]]) -> bool:\n ht = dict()\n q = collections.deque()\n x = y = 0\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] not in ht:\n ... | 0 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f... | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
BEATS 90%! Python3 BFS | detect-cycles-in-2d-grid | 0 | 1 | # Code\n```\nimport collections\n\n\nclass Solution:\n\n def containsCycle(self, grid: List[List[str]]) -> bool:\n ht = dict()\n q = collections.deque()\n x = y = 0\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] not in ht:\n ... | 0 | The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of... | Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle. |
98%-Faster Union-Find Approach | detect-cycles-in-2d-grid | 0 | 1 | # Complexity\n- Time complexity: $$O(m*n*log(m*n))$$.\n\n- Space complexity: $$O(m*n)$$.\n\n# Code\n```\nclass UnionFind:\n def __init__(self):\n self.par = {}\n \n def union(self, el1, el2):\n self.par[self.find(el2)] = self.find(el1)\n\n def find(self, el):\n p = self.par.get(el, el)\... | 0 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f... | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
98%-Faster Union-Find Approach | detect-cycles-in-2d-grid | 0 | 1 | # Complexity\n- Time complexity: $$O(m*n*log(m*n))$$.\n\n- Space complexity: $$O(m*n)$$.\n\n# Code\n```\nclass UnionFind:\n def __init__(self):\n self.par = {}\n \n def union(self, el1, el2):\n self.par[self.find(el2)] = self.find(el1)\n\n def find(self, el):\n p = self.par.get(el, el)\... | 0 | The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of... | Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle. |
Python 3: UnionFind / Two-Set DFS Solution | detect-cycles-in-2d-grid | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f... | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
Python 3: UnionFind / Two-Set DFS Solution | detect-cycles-in-2d-grid | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on.
The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of... | Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle. |
[Python3] 2-line | most-visited-sector-in-a-circular-track | 0 | 1 | \n```\nclass Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n x, xx = rounds[0], rounds[-1]\n return list(range(x, xx+1)) if x <= xx else list(range(1, xx+1)) + list(range(x, n+1))\n``` | 10 | Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ... | Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals. |
✅✅✅ 98% faster solution | easy to understand | less code | most-visited-sector-in-a-circular-track | 0 | 1 | \n\n```\nclass Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n a, b = rounds[0], rounds[-1]\n if a<=b: return [i for i in range(a, b... | 2 | Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ... | Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals. |
[PYTHON] simple solution with explanation. | most-visited-sector-in-a-circular-track | 0 | 1 | I spent 45 mins in this question one, so sad...\n\nExplanation:\nif n = 4, rounds = [1,3,1,2]\nthan [1,2,3,4,**1,2**]\noutput is [1,2]\n\nif n = 3 rounds = [3,1,2,3,1]\nthan [3,1,2,**3,1**]\noutput is [1,3]\n\nif n = 4 rounds = [1,4,2,3]\nthan [1,2,3,4,**1,2,3**]\noutput is [1,2,3]\n\nwhich means all steps moved in the... | 11 | Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ... | Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.