title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
Python 95.67% faster | Simplest solution with explanation | Beg to Adv | Greedy | broken-calculator | 0 | 1 | ```python\nclass Solution:\n def brokenCalc(self, startValue: int, target: int) -> int:\n res = 0 # taking a counter. \n while target > startValue: # checking if target value is greater then startValue. \n res += 1 # as if target is greater implies we`ll be having atleast one operation. \n ... | 3 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ... | null |
Python 95.67% faster | Simplest solution with explanation | Beg to Adv | Greedy | broken-calculator | 0 | 1 | ```python\nclass Solution:\n def brokenCalc(self, startValue: int, target: int) -> int:\n res = 0 # taking a counter. \n while target > startValue: # checking if target value is greater then startValue. \n res += 1 # as if target is greater implies we`ll be having atleast one operation. \n ... | 3 | There are three stones in different positions on the X-axis. You are given three integers `a`, `b`, and `c`, the positions of the stones.
In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's s... | null |
[Python] O(logn) solution starting from startValue with detailed explanation | broken-calculator | 0 | 1 | ## 991 Broken Calculator\n\n[https://leetcode.com/problems/broken-calculator/](https://leetcode.com/problems/broken-calculator/)\n\nInstead of doing the smart thing and thinking about the problem from the target backwards as explained [here](https://leetcode.com/problems/broken-calculator/discuss/1076042/Python-C%2B%2B... | 3 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `targ... | null |
[Python] O(logn) solution starting from startValue with detailed explanation | broken-calculator | 0 | 1 | ## 991 Broken Calculator\n\n[https://leetcode.com/problems/broken-calculator/](https://leetcode.com/problems/broken-calculator/)\n\nInstead of doing the smart thing and thinking about the problem from the target backwards as explained [here](https://leetcode.com/problems/broken-calculator/discuss/1076042/Python-C%2B%2B... | 3 | There are three stones in different positions on the X-axis. You are given three integers `a`, `b`, and `c`, the positions of the stones.
In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's s... | null |
Longest - Shortest | subarrays-with-k-different-integers | 1 | 1 | If the problem talks about continuous subarrays or substrings, the sliding window technique may help solve it in a linear time. Such problems are tricky, though the solution is simple once you get it. No wonder I am seeing such problems in almost every interview!\n\nHere, we will take a look at [Subarrays with K Differ... | 462 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** par... | null |
Longest - Shortest | subarrays-with-k-different-integers | 1 | 1 | If the problem talks about continuous subarrays or substrings, the sliding window technique may help solve it in a linear time. Such problems are tricky, though the solution is simple once you get it. No wonder I am seeing such problems in almost every interview!\n\nHere, we will take a look at [Subarrays with K Differ... | 462 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Dictionary Method -With Comments- Beats 79.59% In Runtime | subarrays-with-k-different-integers | 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)$$ --... | 9 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** par... | null |
Dictionary Method -With Comments- Beats 79.59% In Runtime | subarrays-with-k-different-integers | 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)$$ --... | 9 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Python Easy Solution | subarrays-with-k-different-integers | 0 | 1 | \n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def atmostk(self,n,k,nums):\n l=0\n r=0\n map=defaultdict(int)\n ans=0\n while r<n:\n map[nums[r]]+=1\n while len(map)>k:\n map[nums[l]]-=1\n if map[nums[l]]=... | 6 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** par... | null |
Python Easy Solution | subarrays-with-k-different-integers | 0 | 1 | \n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def atmostk(self,n,k,nums):\n l=0\n r=0\n map=defaultdict(int)\n ans=0\n while r<n:\n map[nums[r]]+=1\n while len(map)>k:\n map[nums[l]]-=1\n if map[nums[l]]=... | 6 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
Solution | subarrays-with-k-different-integers | 1 | 1 | ```C++ []\nclass Solution {\nprivate:\n int atmostk(vector<int>& nums, int k){\n int left = 0;\n int right = 0;\n int count = 0;\n int n = nums.size();\n int freq[20005] = {0};\n while(right < n){\n if(freq[nums[right]]++ == 0){\n k--;\n ... | 2 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** par... | null |
Solution | subarrays-with-k-different-integers | 1 | 1 | ```C++ []\nclass Solution {\nprivate:\n int atmostk(vector<int>& nums, int k){\n int left = 0;\n int right = 0;\n int count = 0;\n int n = nums.size();\n int freq[20005] = {0};\n while(right < n){\n if(freq[nums[right]]++ == 0){\n k--;\n ... | 2 | You are given an `m x n` integer matrix `grid`, and three integers `row`, `col`, and `color`. Each value in the grid represents the color of the grid square at that location.
Two squares belong to the same **connected component** if they have the same color and are next to each other in any of the 4 directions.
The *... | null |
✅Python3 33ms🔥🔥 easiest explanation | cousins-in-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Travel by level and storing root of x, y and level will solve this.**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- travel in left to right manner.\n- if current node is None return.\n- if not then if it\'s e... | 4 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with d... | null |
✅Python3 33ms🔥🔥 easiest explanation | cousins-in-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Travel by level and storing root of x, y and level will solve this.**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- travel in left to right manner.\n- if current node is None return.\n- if not then if it\'s e... | 4 | You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we d... | null |
Iterative + Dictionary | cousins-in-binary-tree | 0 | 1 | # Intuition\nThere are two conditions that make nodes X and Y cousins. They are - \n(a) The nodes X and Y should be in the same level of the binary tree.\n(b) Provided that the levels of the nodes X and Y are the same, the parent nodes of X and Y should not be the same.\n\n# Approach\n- Using a dictionary to store the ... | 1 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with d... | null |
Iterative + Dictionary | cousins-in-binary-tree | 0 | 1 | # Intuition\nThere are two conditions that make nodes X and Y cousins. They are - \n(a) The nodes X and Y should be in the same level of the binary tree.\n(b) Provided that the levels of the nodes X and Y are the same, the parent nodes of X and Y should not be the same.\n\n# Approach\n- Using a dictionary to store the ... | 1 | You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we d... | null |
Simplest Code to understand with commentssssss!! | cousins-in-binary-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:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(... | 1 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with d... | null |
Simplest Code to understand with commentssssss!! | cousins-in-binary-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:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(... | 1 | You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we d... | null |
BFS solution | cousins-in-binary-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:\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 the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with d... | null |
BFS solution | cousins-in-binary-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:\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 two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we d... | null |
Python Straight Forward BFS and DFS Solutions | cousins-in-binary-tree | 0 | 1 | Two solutions have the same idea:\n* Iterate the whole tree looking for the target(x and y) - either BFS or DFS\n\t* once found, store `(parent, depth)` as a tuple\n* Compare the parents and depth of two nodes found and get result\n\n**BFS**\n```python\nclass Solution:\n def isCousins(self, root: TreeNode, x: int, y... | 82 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with d... | null |
Python Straight Forward BFS and DFS Solutions | cousins-in-binary-tree | 0 | 1 | Two solutions have the same idea:\n* Iterate the whole tree looking for the target(x and y) - either BFS or DFS\n\t* once found, store `(parent, depth)` as a tuple\n* Compare the parents and depth of two nodes found and get result\n\n**BFS**\n```python\nclass Solution:\n def isCousins(self, root: TreeNode, x: int, y... | 82 | You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that:
* `nums1[i] == nums2[j]`, and
* the line we d... | null |
Click this if you're confused. | rotting-oranges | 0 | 1 | # Intuition\nAt each minute, we can only convert adjacent fresh oranges to rotten once. This is simply level-by-level BFS traversal. Each level we convert fresh to rotten and increment minutes by 1. Implementing this iteratively, we initialize our queue with all initial rotten oranges, then loop till queue is empty by ... | 1 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum nu... | null |
Click this if you're confused. | rotting-oranges | 0 | 1 | # Intuition\nAt each minute, we can only convert adjacent fresh oranges to rotten once. This is simply level-by-level BFS traversal. Each level we convert fresh to rotten and increment minutes by 1. Implementing this iteratively, we initialize our queue with all initial rotten oranges, then loop till queue is empty by ... | 1 | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coor... | null |
Python Clean & Well Explained (faster than > 90%) | rotting-oranges | 0 | 1 | ```\nfrom collections import deque\n\n# Time complexity: O(rows * cols) -> each cell is visited at least once\n# Space complexity: O(rows * cols) -> in the worst case if all the oranges are rotten they will be added to the queue\n\nclass Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n \n... | 811 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum nu... | null |
Python Clean & Well Explained (faster than > 90%) | rotting-oranges | 0 | 1 | ```\nfrom collections import deque\n\n# Time complexity: O(rows * cols) -> each cell is visited at least once\n# Space complexity: O(rows * cols) -> in the worst case if all the oranges are rotten they will be added to the queue\n\nclass Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n \n... | 811 | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coor... | null |
C++ || BFS || Easiest Beginner Friendly Sol || O(n^2) time and O(n^2) space | rotting-oranges | 1 | 1 | # Intuition of this Problem:\nSame type of bfs approach will work as shown in below picture.\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THE... | 137 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum nu... | null |
C++ || BFS || Easiest Beginner Friendly Sol || O(n^2) time and O(n^2) space | rotting-oranges | 1 | 1 | # Intuition of this Problem:\nSame type of bfs approach will work as shown in below picture.\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THE... | 137 | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coor... | null |
BFS | Iterative | Beats 99.8% | Python | rotting-oranges | 0 | 1 | # Intuition\nThe intuition of the solution is to perform a BFS on the rotten oranges at the same time and increment the counter.\n\nThe neighbors are added only if they are good oranges and their value is set to 2 "rotten".\n# Complexity\n- Time complexity: O(N*M) (BFS visits all the values once)\n<!-- Add your time co... | 2 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum nu... | null |
BFS | Iterative | Beats 99.8% | Python | rotting-oranges | 0 | 1 | # Intuition\nThe intuition of the solution is to perform a BFS on the rotten oranges at the same time and increment the counter.\n\nThe neighbors are added only if they are good oranges and their value is set to 2 "rotten".\n# Complexity\n- Time complexity: O(N*M) (BFS visits all the values once)\n<!-- Add your time co... | 2 | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coor... | null |
DFS Solution | Explained in figures | Python | rotting-oranges | 0 | 1 | # Approach\nCreate a 2D array called `rotten_time` that holds the numebr of minutes that a orange will be rotted.\n\n\n<table align="center">\n <tr align="center"><td colspan="5">grid</td></tr>\n <tr>\n <td align="center">1</td>\n <td align="center">1</td>\n <td align="center">1</td>\n ... | 1 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum nu... | null |
DFS Solution | Explained in figures | Python | rotting-oranges | 0 | 1 | # Approach\nCreate a 2D array called `rotten_time` that holds the numebr of minutes that a orange will be rotted.\n\n\n<table align="center">\n <tr align="center"><td colspan="5">grid</td></tr>\n <tr>\n <td align="center">1</td>\n <td align="center">1</td>\n <td align="center">1</td>\n ... | 1 | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coor... | null |
✅[Python] Simple and Clean, beats 88%✅ | rotting-oranges | 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*This is an NFT*\n\n# Intuition\nThe problem asks us to find the minimum number of minutes that must e... | 1 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum nu... | null |
✅[Python] Simple and Clean, beats 88%✅ | rotting-oranges | 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*This is an NFT*\n\n# Intuition\nThe problem asks us to find the minimum number of minutes that must e... | 1 | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coor... | null |
Solution | minimum-number-of-k-consecutive-bit-flips | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minKBitFlips(vector<int>& A, int K) {\n int cur = 0, res = 0, n = A.size();\n for (int i = 0; i < n; ++i) {\n if (i >= K && A[i - K] > 1) {\n cur--;\n A[i - K] -= 2;\n }\n if (cur % 2 == A[i]) {\n ... | 1 | You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
Solution | minimum-number-of-k-consecutive-bit-flips | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minKBitFlips(vector<int>& A, int K) {\n int cur = 0, res = 0, n = A.size();\n for (int i = 0; i < n; ++i) {\n if (i >= K && A[i - K] > 1) {\n cur--;\n A[i - K] -= 2;\n }\n if (cur % 2 == A[i]) {\n ... | 1 | Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
Python 3 || 8 lines, accumulate, w/ explanation || T/M: 98% / 100% | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | Here\'s the plan:\n\nAs we iterate`nums`, we want to change zeros to ones and leave ones unchanged. Let\'s call zero the *change-digit* in this case.\n\nWhen we flip digits in the *flip interval*`nums[i:i+k]`, those digits that were initially one are now zero, and or equivalently, if we treat one as the change-digit ... | 5 | You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
Python 3 || 8 lines, accumulate, w/ explanation || T/M: 98% / 100% | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | Here\'s the plan:\n\nAs we iterate`nums`, we want to change zeros to ones and leave ones unchanged. Let\'s call zero the *change-digit* in this case.\n\nWhen we flip digits in the *flip interval*`nums[i:i+k]`, those digits that were initially one are now zero, and or equivalently, if we treat one as the change-digit ... | 5 | Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
sliding windows + greedy | minimum-number-of-k-consecutive-bit-flips | 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 a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
sliding windows + greedy | minimum-number-of-k-consecutive-bit-flips | 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 `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
✅sliding window || prefix || python | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | \n# Code\n```\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n n=len(nums)\n ans=0\n arr=[0 for i in range(n)]\n for i in range(n):\n if(i>n-k):\n arr[i]=(arr[i]+arr[i-1])%2\n if((nums[i]==0 and arr[i]==0)or(nums[i]==1 a... | 0 | You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
✅sliding window || prefix || python | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | \n# Code\n```\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n n=len(nums)\n ans=0\n arr=[0 for i in range(n)]\n for i in range(n):\n if(i>n-k):\n arr[i]=(arr[i]+arr[i-1])%2\n if((nums[i]==0 and arr[i]==0)or(nums[i]==1 a... | 0 | Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
Python O(n) Solution | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n f = [0] * len(nums)\n psum = 0\n for i in range(len(nums)-k+1):\n if (psum + nums[i])%2 == 0:\n f[i] = 1\n psum += f[i]\n if i-k+1 >= 0:\n p... | 0 | You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
Python O(n) Solution | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n f = [0] * len(nums)\n psum = 0\n for i in range(len(nums)-k+1):\n if (psum + nums[i])%2 == 0:\n f[i] = 1\n psum += f[i]\n if i-k+1 >= 0:\n p... | 0 | Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
Python | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n n = len(nums)\n flips = 0\n if nums[0] == 0:\n for i in range(k):\n nums[i] = 1 - nums[i]\n flips += 1\n \n diff = [abs(nums[i+1] - nums[i]) for i in ra... | 0 | You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
Python | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n n = len(nums)\n flips = 0\n if nums[0] == 0:\n for i in range(k):\n nums[i] = 1 - nums[i]\n flips += 1\n \n diff = [abs(nums[i+1] - nums[i]) for i in ra... | 0 | Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
python | minimum-number-of-k-consecutive-bit-flips | 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 a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
python | minimum-number-of-k-consecutive-bit-flips | 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 `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
Simulation got TLE; so I redefined what is One | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of toggling `k` elements every time, I chose to toggle `one` and set a reminder to untoggle it `k - 1` steps later.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGreedy \xD7 { Simulation, Bit Manipulation... | 0 | You are given a binary array `nums` and an integer `k`.
A **k-bit flip** is choosing a **subarray** of length `k` from `nums` and simultaneously changing every `0` in the subarray to `1`, and every `1` in the subarray to `0`.
Return _the minimum number of **k-bit flips** required so that there is no_ `0` _in the arra... | null |
Simulation got TLE; so I redefined what is One | minimum-number-of-k-consecutive-bit-flips | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of toggling `k` elements every time, I chose to toggle `one` and set a reminder to untoggle it `k - 1` steps later.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGreedy \xD7 { Simulation, Bit Manipulation... | 0 | Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_.
A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\]
**Output... | null |
Solution | number-of-squareful-arrays | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int count=0;\n bool check(int a,int b){\n int temp = sqrt(a+b);\n return ((temp*temp) == (a+b));\n }\n void help(int curr,vector<int> arr){\n if(curr>= arr.size()){\n count++;\n return ;\n }\n for(int i= curr;i<a... | 438 | An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`.
**Examp... | null |
Solution | number-of-squareful-arrays | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int count=0;\n bool check(int a,int b){\n int temp = sqrt(a+b);\n return ((temp*temp) == (a+b));\n }\n void help(int curr,vector<int> arr){\n if(curr>= arr.size()){\n count++;\n return ;\n }\n for(int i= curr;i<a... | 438 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Concise solution on python3 | number-of-squareful-arrays | 0 | 1 | \n# Code\n```\nfrom math import sqrt\n\n\nclass Solution:\n def numSquarefulPerms(self, nums: List[int]) -> int:\n\n n = len(nums)\n ans = 0\n\n def ps(n):\n root = int(sqrt(n))\n return root * root == n\n \n def go(mask, prev):\n nonlocal ans\n ... | 0 | An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`.
**Examp... | null |
Concise solution on python3 | number-of-squareful-arrays | 0 | 1 | \n# Code\n```\nfrom math import sqrt\n\n\nclass Solution:\n def numSquarefulPerms(self, nums: List[int]) -> int:\n\n n = len(nums)\n ans = 0\n\n def ps(n):\n root = int(sqrt(n))\n return root * root == n\n \n def go(mask, prev):\n nonlocal ans\n ... | 0 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
[Python3] Bitmask DP | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are a few approaches for this problem:\n1. Backtracking\nGenerate all possible permutations - `O(n!)`\nCheck if a permutation is squareful - `O(n)`\n=> `O(n! * n)`\n2. Backtracking but just generate squareful permutations\n`O(n! * n... | 0 | An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`.
**Examp... | null |
[Python3] Bitmask DP | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are a few approaches for this problem:\n1. Backtracking\nGenerate all possible permutations - `O(n!)`\nCheck if a permutation is squareful - `O(n)`\n=> `O(n! * n)`\n2. Backtracking but just generate squareful permutations\n`O(n! * n... | 0 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Fast and clean Python implementation with explaination | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBase on the input constraint, we can see it is a backtracking problem\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each position, try different value. I use an dictionary to maintain different value. \n# Compl... | 0 | An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`.
**Examp... | null |
Fast and clean Python implementation with explaination | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBase on the input constraint, we can see it is a backtracking problem\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each position, try different value. I use an dictionary to maintain different value. \n# Compl... | 0 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Number of Squareful Arrays | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`.
**Examp... | null |
Number of Squareful Arrays | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
same as permutationsII | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n### 47. Permutations II\n```python\nclass Solution:\n def permuteUnique(self, nums):\n def backtrack(nums, ans, res):\n if not nums:\n res.append(ans[::])\n s = set()\n for i in ra... | 0 | An array is **squareful** if the sum of every pair of adjacent elements is a **perfect square**.
Given an integer array nums, return _the number of permutations of_ `nums` _that are **squareful**_.
Two permutations `perm1` and `perm2` are different if there is some index `i` such that `perm1[i] != perm2[i]`.
**Examp... | null |
same as permutationsII | number-of-squareful-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n### 47. Permutations II\n```python\nclass Solution:\n def permuteUnique(self, nums):\n def backtrack(nums, ans, res):\n if not nums:\n res.append(ans[::])\n s = set()\n for i in ra... | 0 | Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a _binary search tree_ is a tree that satisfies these constraints:
* The left subtree of a... | null |
Solution | find-the-town-judge | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findJudge(int n, vector<vector<int>>& trust) {\n vector<int> trusting(n+1,0);\n vector<int> trusted(n+1,0);\n\n for(int i=0; i<trust.size();i++){\n trusting[trust[i][0]]++;\n trusted[trust[i][1]]++;\n } \n int ans = -1;\n ... | 1 | In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **... | null |
Solution | find-the-town-judge | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findJudge(int n, vector<vector<int>>& trust) {\n vector<int> trusting(n+1,0);\n vector<int> trusted(n+1,0);\n\n for(int i=0; i<trust.size();i++){\n trusting[trust[i][0]]++;\n trusted[trust[i][1]]++;\n } \n int ans = -1;\n ... | 1 | You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the `ith` vertex (i.e., **clockwise order**).
You will **triangulate** the polygon into `n - 2` triangles. For each triangle, the value of that triangle is the product ... | null |
O(N) Super [EASY] PYTHON 3 | find-the-town-judge | 0 | 1 | # Intuition and Approach\nWe have 2 maps, map 1 keeps track of the arrary[i][0] (think of it as **a** ) and we count how many people **a** trusts and map 2 keeps track of array[i][1] (**b**) we count how many times **b** was trusted we know that a --trusts--> b. We want to return those **b**s whose values == n - 1 so... | 1 | In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **... | null |
O(N) Super [EASY] PYTHON 3 | find-the-town-judge | 0 | 1 | # Intuition and Approach\nWe have 2 maps, map 1 keeps track of the arrary[i][0] (think of it as **a** ) and we count how many people **a** trusts and map 2 keeps track of array[i][1] (**b**) we count how many times **b** was trusted we know that a --trusts--> b. We want to return those **b**s whose values == n - 1 so... | 1 | You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the `ith` vertex (i.e., **clockwise order**).
You will **triangulate** the polygon into `n - 2` triangles. For each triangle, the value of that triangle is the product ... | null |
Java | O(N) O(N) | Easy | find-the-town-judge | 1 | 1 | # Intuition\n1. Create a directed graph from ai to bi where trust[i] = [ai, bi].\n2. Find the one node with in-degree as n-1 & out-degree -1.\n3. Also check that there is only one such node as specified in (2).\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n ... | 1 | In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **... | null |
Java | O(N) O(N) | Easy | find-the-town-judge | 1 | 1 | # Intuition\n1. Create a directed graph from ai to bi where trust[i] = [ai, bi].\n2. Find the one node with in-degree as n-1 & out-degree -1.\n3. Also check that there is only one such node as specified in (2).\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n ... | 1 | You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the `ith` vertex (i.e., **clockwise order**).
You will **triangulate** the polygon into `n - 2` triangles. For each triangle, the value of that triangle is the product ... | null |
Easy Python solution for Beginners in O(n+m) Time Complexity | find-the-town-judge | 0 | 1 | APPROACH 1:\n```\nclass Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n # Sum of n terms\n Town_judge = (n*(n+1))//2\n\n # Hash map for storing judge and their trusted judges\n judge_trust = dict()\n\n\n for i in trust:\n judge = i[0]\n ... | 1 | In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **... | null |
Easy Python solution for Beginners in O(n+m) Time Complexity | find-the-town-judge | 0 | 1 | APPROACH 1:\n```\nclass Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n # Sum of n terms\n Town_judge = (n*(n+1))//2\n\n # Hash map for storing judge and their trusted judges\n judge_trust = dict()\n\n\n for i in trust:\n judge = i[0]\n ... | 1 | You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the `ith` vertex (i.e., **clockwise order**).
You will **triangulate** the polygon into `n - 2` triangles. For each triangle, the value of that triangle is the product ... | null |
C++ | Easy to understand | find-the-town-judge | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
1. The town judge trusts nobody.
2. Everybody (except for the town judge) trusts the town judge.
3. There is exactly one person that satisfies properties **... | null |
C++ | Easy to understand | find-the-town-judge | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You have a convex `n`\-sided polygon where each vertex has an integer value. You are given an integer array `values` where `values[i]` is the value of the `ith` vertex (i.e., **clockwise order**).
You will **triangulate** the polygon into `n - 2` triangles. For each triangle, the value of that triangle is the product ... | null |
Solution | maximum-binary-tree-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n TreeNode* check(vector<int>&nums,int s,int e){\n stack<TreeNode*> st;\n\n for(int i=s;i<=e;i++){\n TreeNode* node=new TreeNode( nums[i]);\n while(!st.empty() && nums[i]>st.top()->val){\n node->left=st.top();\n st... | 2 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ... | null |
Solution | maximum-binary-tree-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n TreeNode* check(vector<int>&nums,int s,int e){\n stack<TreeNode*> st;\n\n for(int i=s;i<=e;i++){\n TreeNode* node=new TreeNode( nums[i]);\n while(!st.empty() && nums[i]>st.top()->val){\n node->left=st.top();\n st... | 2 | There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones.
Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoint stone** and move it to an unoccupied position so that it is no longer a... | null |
✅ Beats 100% | Very easy to understand | Inserting a Node into a Maximum Binary Tree | maximum-binary-tree-ii | 0 | 1 | # Intuition\nWe need to insert a new node with a value `val` into a maximum binary tree. One way we can do it is to traverse the tree recursively comparing the value of the current node with `val` to determine the appropriate placement of the new node.\n\n# Approach\n1. Create a new ndoe with the value `val`.\n2. If th... | 0 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ... | null |
✅ Beats 100% | Very easy to understand | Inserting a Node into a Maximum Binary Tree | maximum-binary-tree-ii | 0 | 1 | # Intuition\nWe need to insert a new node with a value `val` into a maximum binary tree. One way we can do it is to traverse the tree recursively comparing the value of the current node with `val` to determine the appropriate placement of the new node.\n\n# Approach\n1. Create a new ndoe with the value `val`.\n2. If th... | 0 | There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones.
Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoint stone** and move it to an unoccupied position so that it is no longer a... | null |
[Python3] Using 654. Maximum Binary Tree Solution | maximum-binary-tree-ii | 0 | 1 | # Code\n```\nclass Solution:\n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n self.lst = []\n def dfs(root):\n if not root:\n return \n dfs(root.left)\n self.lst.append(root.val)\n dfs(root.right... | 0 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = ... | null |
[Python3] Using 654. Maximum Binary Tree Solution | maximum-binary-tree-ii | 0 | 1 | # Code\n```\nclass Solution:\n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n self.lst = []\n def dfs(root):\n if not root:\n return \n dfs(root.left)\n self.lst.append(root.val)\n dfs(root.right... | 0 | There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones.
Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoint stone** and move it to an unoccupied position so that it is no longer a... | null |
Solution | available-captures-for-rook | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int numRookCaptures(vector<vector<char>>& board) {\n static vector<pair<int, int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n int r = -1, c = -1;\n for (int i = 0; i < 8 && r == -1; ++i) {\n for (int j = 0; j < 8; ++j) {\n i... | 1 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ... | null |
Solution | available-captures-for-rook | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int numRookCaptures(vector<vector<char>>& board) {\n static vector<pair<int, int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n int r = -1, c = -1;\n for (int i = 0; i < 8 && r == -1; ++i) {\n for (int j = 0; j < 8; ++j) {\n i... | 1 | On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction**... | null |
✅ Beats 98.87% solutions,✅ Easy to understand Python Code with explanation by ✅ BOLT CODING ✅ | available-captures-for-rook | 0 | 1 | # Explanation:\nFirst we try to find the position of Rook.\nOnce we get that we already know that Rook always attacks in straight line i.e. Rows or Columns (not diagonals). So rather than traversing through the whole list we will only traverse through the rows and columns where Rook can attack. So we right 4 different ... | 1 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ... | null |
✅ Beats 98.87% solutions,✅ Easy to understand Python Code with explanation by ✅ BOLT CODING ✅ | available-captures-for-rook | 0 | 1 | # Explanation:\nFirst we try to find the position of Rook.\nOnce we get that we already know that Rook always attacks in straight line i.e. Rows or Columns (not diagonals). So rather than traversing through the whole list we will only traverse through the rows and columns where Rook can attack. So we right 4 different ... | 1 | On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction**... | null |
Python 3. Not the shortest but Neat and Easy to Understand | available-captures-for-rook | 0 | 1 | The idea is to find the Rook location and then start looking at 4 directions to find nearest piece. Check if the nearest piece is friend or foe using `isupper()`, `islower()`. \nRuntime varies from 48 ms (14%) to 32 ms (96%) so i guess it\'s good enough. Anyways, the most important thing is it\'s easy to understand\n``... | 9 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ... | null |
Python 3. Not the shortest but Neat and Easy to Understand | available-captures-for-rook | 0 | 1 | The idea is to find the Rook location and then start looking at 4 directions to find nearest piece. Check if the nearest piece is friend or foe using `isupper()`, `islower()`. \nRuntime varies from 48 ms (14%) to 32 ms (96%) so i guess it\'s good enough. Anyways, the most important thing is it\'s easy to understand\n``... | 9 | On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction**... | null |
🐍🐍🐍 Solution in 3 lines 🐍🐍🐍 with explanation | available-captures-for-rook | 0 | 1 | # Code\n```\nclass Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n # dictionary with coordinate {row:column in matrix(board)} of \'Rock\' \n d = {i:x.index(\'R\') for i, x in enumerate(board) if \'R\' in x}\n # making list of 2 string without \'.\', first - row of \'Rock\... | 0 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ... | null |
🐍🐍🐍 Solution in 3 lines 🐍🐍🐍 with explanation | available-captures-for-rook | 0 | 1 | # Code\n```\nclass Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n # dictionary with coordinate {row:column in matrix(board)} of \'Rock\' \n d = {i:x.index(\'R\') for i, x in enumerate(board) if \'R\' in x}\n # making list of 2 string without \'.\', first - row of \'Rock\... | 0 | On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction**... | null |
Best Approach using 2 while loops | available-captures-for-rook | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n# Complexity\n- Time complexity:\n- O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n ... | 0 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ... | null |
Best Approach using 2 while loops | available-captures-for-rook | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n# Complexity\n- Time complexity:\n- O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n ... | 0 | On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction**... | null |
Python solution - Regex | available-captures-for-rook | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif the pattern shows as "p\\.*R" or \'R\\.*p\' then the Rook captures the pawn.\nCheck the row and column separatively.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add y... | 0 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge ... | null |
Python solution - Regex | available-captures-for-rook | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif the pattern shows as "p\\.*R" or \'R\\.*p\' then the Rook captures the pawn.\nCheck the row and column separatively.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add y... | 0 | On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that:
* The **north direction** is the positive direction of the y-axis.
* The **south direction** is the negative direction of the y-axis.
* The **east direction** is the positive direction of the x-axis.
* The **west direction**... | null |
Python (Simple DP) | minimum-cost-to-merge-stones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile... | null |
Python (Simple DP) | minimum-cost-to-merge-stones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flowe... | null |
Why DP solution splits (K-1) AND a bonus problem (bottom-up) | minimum-cost-to-merge-stones | 0 | 1 | This took me weeks of intermittent thinking to arrive to! Hoping it would help someone.\nFirst, it\'s a good idea to glean some info from a book and other posts:\n- This problem is almost the same as Matrix-Chain Multiplication in [Cormen](https://edutechlearners.com/download/Introduction_to_algorithms-3rd%20Edition.... | 18 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile... | null |
Why DP solution splits (K-1) AND a bonus problem (bottom-up) | minimum-cost-to-merge-stones | 0 | 1 | This took me weeks of intermittent thinking to arrive to! Hoping it would help someone.\nFirst, it\'s a good idea to glean some info from a book and other posts:\n- This problem is almost the same as Matrix-Chain Multiplication in [Cormen](https://edutechlearners.com/download/Introduction_to_algorithms-3rd%20Edition.... | 18 | You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flowe... | null |
Solution | minimum-cost-to-merge-stones | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int find(int i, int j, vector<int>& prefix, int pile, vector<vector<int>>& dp) {\n if(i >= j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int ans = INT_MAX;\n for(int k = i; k < j; k += pile-1) {\n int sum = find(i, k, prefix, pile, ... | 2 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile... | null |
Solution | minimum-cost-to-merge-stones | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int find(int i, int j, vector<int>& prefix, int pile, vector<vector<int>>& dp) {\n if(i >= j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int ans = INT_MAX;\n for(int k = i; k < j; k += pile-1) {\n int sum = find(i, k, prefix, pile, ... | 2 | You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flowe... | null |
Python 3: Short Top-Down DFS, More Comments Than Code | minimum-cost-to-merge-stones | 0 | 1 | **If anyone has questions, I\'ll try to answer. Just leave a comment below! Please upvote if you find this helpful - takes a lot of time to write these.**\n\nHere\'s yet another top-down DFS solution. It\'s very similar to [@cappuccinuo\'s solution](https://leetcode.com/problems/minimum-cost-to-merge-stones/solutions/2... | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile... | null |
Python 3: Short Top-Down DFS, More Comments Than Code | minimum-cost-to-merge-stones | 0 | 1 | **If anyone has questions, I\'ll try to answer. Just leave a comment below! Please upvote if you find this helpful - takes a lot of time to write these.**\n\nHere\'s yet another top-down DFS solution. It\'s very similar to [@cappuccinuo\'s solution](https://leetcode.com/problems/minimum-cost-to-merge-stones/solutions/2... | 0 | You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flowe... | null |
DP | minimum-cost-to-merge-stones | 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 spa... | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile... | null |
DP | minimum-cost-to-merge-stones | 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 spa... | 0 | You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers.
All gardens have **at most 3** paths coming into or leaving it.
Your task is to choose a flowe... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.