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 |
|---|---|---|---|---|---|---|---|
Simple DFS solution | coloring-a-border | 0 | 1 | ```\nclass Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n old_color, n, m = grid[row][col], len(grid)-1, len(grid[0])-1\n stack = [(row, col)]\n visited = set(stack)\n while stack: \n i, j = stack.pop()\n ... | 0 | 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] barebones DFS, code also explains the requirements | coloring-a-border | 0 | 1 | ```\n# border: < 4 neighbors\nclass Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n def in_bounds(r, c):\n return 0 <= r < len(grid) and 0 <= c < len(grid[0])\n\n\n def neighbors(r, c):\n nbrs = []\n if in_b... | 0 | 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 DFS | coloring-a-border | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n+v) where v is the linear operation for checking visited list and n is for checking through n points.\n<!-- Add your time complex... | 0 | 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 solution BFS | coloring-a-border | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nApplying Breadth First Search. The idea is we will take a point and then we will find out if this point is our point of interest. After that, we will look points which is \'one\' distance from the first point. We can say this layer 1. In ... | 0 | 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 top down dp | uncrossed-lines | 0 | 1 | # Intuition\nBasically attempt to join the string in each steps, then try out not joining\n\n# Code\n```\nclass Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n @lru_cache(None)\n def max_lines(i, j):\n if i == len(nums1) or j == len(nums2):\n ... | 3 | 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 |
Dynamic Programming || beginner friendly | uncrossed-lines | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n```\n 0 1 2 3\n0 0 0 0 0\n1 0 1 1 1\n2 0 1 1 2\n3 0 1 2 2\n```\n# Approach\n<!-- Describe your approach to solving the problem. -->\n```\n 0 1 2 3\n0 +--+--+--+\n | | | |\n1 +--+--+--+\n | |\u2196 |\u2196 |\n2 +--+\u2196 | + |\n ... | 3 | 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 |
Clean Python DP | uncrossed-lines | 0 | 1 | # Code\n```\nclass Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n\n n = len(nums1)\n dic = defaultdict(list)\n for i,num in enumerate(nums2):\n dic[num].append(i)\n \n @lru_cache(None)\n def rec(i=0, i_max=-1):\n\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 |
Solution | escape-a-large-maze | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; \n \n bool isEscapePossible(vector<vector<int>>& blocked, vector<int>& source, vector<int>& target) {\n unordered_set<long long> visited_s;\n unordered_set<long long> visited_t;\n for (auto& bloc... | 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 |
Clean Python | High Speed | O(n) time, O(1) space | Beats 96.9% | escape-a-large-maze | 0 | 1 | # Code\n\n```\nclass Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n blocked = set(map(tuple, blocked))\n \n def fn(x, y, tx, ty): \n """Return True if (x, y) is not looped from (tx, ty)."""\n seen = {(x, y)}... | 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 |
Faster than 99.22% | escape-a-large-maze | 0 | 1 | # Approach\nsee code comments - it\'s tweaked depth-first search\n\nThe basic heuristic is: there are at most 200 blocks. If I can get 200 steps away from the start/source then there must be a hole where we can slip through and reach the target.\n\nThe only tricky part is that you have to run the search in both directi... | 0 | 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 A*, early return for circumventing blockade | escape-a-large-maze | 0 | 1 | # Intuition\nUse A* to search for the target starting from the source.\n\nFor A*, we use a priority-queue/min-heap to determine when to visit nodes. The value to compare against in the priority-queue should be the actual cost so far to reach plus the estimated cost.\n\nThe estimated cost needs to be admissible, so we\'... | 0 | 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 3 FT 100%: TC O(B log(B)), SC O(B): "Detour" Union-Find | escape-a-large-maze | 0 | 1 | After seeing some other solutions, there are definitely simpler ones that will let you succeed without TLE, but with worse $O(B^2)$ complexity for $B$ blocked cells\n1. "escape region:" \n * if we can\'t reach target from source, that means a wall of blocked cells separates them.\n * a wall of B cells can contain o... | 0 | 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 3: Simple BFS Solution | escape-a-large-maze | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is 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] O(N) Easy Explanation | escape-a-large-maze | 0 | 1 | Since maximum length of square is 200, we just check if we can visit that far without being blocked.\n\n# Code\n```\nclass Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n dx = [0,0,-1,1]\n dy = [1,-1,0,0]\n MAX = 200\n N =... | 0 | 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 |
Optimized DFS Approach | Escape Distance | O(B^2) T and S | Commented and Explained | escape-a-large-maze | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe two ways to phrase the question are if a route is blocked or if a route is open. We can check this with one function using alternate styles of return, which is a focus in this implementation for those still learning that style of retu... | 0 | 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 Python | escape-a-large-maze | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking to determine if it\'s possible to escape a blocked grid by starting at the source point and reaching the target point. The approach I\'m thinking of using is using breadth-first search (BFS) to check if the source po... | 0 | 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 from source and target to see if we can reach a point > 200 unit | escape-a-large-maze | 0 | 1 | ```\nclass Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n """\n the blocked is only of length 200\n we cannot reach from source to target if either the source is bounded/completely \n isolated by points in blocked or the t... | 0 | 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 BFS) | escape-a-large-maze | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is 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 |
Layz guy only explore as much as needed with BFS algorithm | escape-a-large-maze | 0 | 1 | # Intuition\nLayz guy only explore as much as needed with BFS algorithm\n\n# Approach\nBFS\n\n\n\n# Code\n```\n#https://leetcode.com/problems/escape-a-large-maze/solutions/282849/python-bfs-and-dfs-the-whole-problem-is-broken/?orderBy=most_votes\nclass Solution: \n def isEscapePossible(self, blocked, source, tar... | 0 | 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 Super Easy | valid-boomerang | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given an 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] Triangle Area | valid-boomerang | 0 | 1 | **Concept:** We need to check if the 3 points are in a straight line or not.\nMath: We can find the area of the triangle formed by the three points and check if the area is non-zero.\n**DO UPVOTE IF YOU FOUND IT HELPFUL.**\n\n\n```\nclass Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n x... | 18 | 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 |
Compare slopes python | valid-boomerang | 0 | 1 | To avoid division by zero instead of comparing (delta y1)/(delta x1) != (delta y2)/(delta x2), cross multiply: (delta y1) * (delta x2) != (delta y2) * (delta x1)\n\n```\nclass Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n a,b,c=points\n return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[... | 3 | 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, math solution, checking slopes | valid-boomerang | 0 | 1 | ```\nclass Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n (x0, y0), (x1, y1), (x2, y2) = points\n return (y2 - y1) * (x0 - x1) != (x2 - x1) * (y0 - y1)\n``` | 8 | 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 |
Production code. | valid-boomerang | 0 | 1 | # Code\n```\nimport dataclasses\nimport typing as tp\nfrom math import isclose\n\n\n@dataclasses.dataclass\nclass Point:\n x: int\n y: int\n\n\nclass Solution:\n def isBoomerang(self, points: tp.List[tp.List[int]]) -> bool:\n return self._is_boomerang(points)\n\n @staticmethod\n def _get_area_unde... | 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 Geometry Solution | valid-boomerang | 0 | 1 | \n\n\n# Complexity\n- Time complexity: O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution(object):\n def isBoomerang(self, p):\n x1, y1, x2, y2, x3, y3 = p[0][0], p[0][1], p[1][0], 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 SIMPLE | valid-boomerang | 0 | 1 | # Code\n```\nclass Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n a,b,c=points\n return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0])\n \n \n \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 |
area of triangle in coordinate geometry | valid-boomerang | 0 | 1 | # Intuition\nCheck if area of the triangle is greater than 0\n\n# Approach\nhttps://www.cuemath.com/geometry/area-of-triangle-in-coordinate-geometry/\n\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\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 |
Python3 DFS/ Recursive DFS | binary-search-tree-to-greater-sum-tree | 0 | 1 | \n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n - DFS - \n```\n# Definition for a binary tree node.\n# class TreeNode:\... | 1 | 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 |
Python || 91.95% Faster || DP || 3 solutions | minimum-score-triangulation-of-polygon | 0 | 1 | ```\n#Recursive\n#Time Complexity: Exponential\n#Space Complexity: O(n)\nclass Solution1:\n def minScoreTriangulation(self, values: List[int]) -> int:\n def solve(i, j):\n if i+1 == j:\n return 0\n m = float(\'inf\')\n for k in range(i+1, j):\n m ... | 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 |
[Python] Sliding window with detailed expalanation | moving-stones-until-consecutive-ii | 0 | 1 | ```python\nclass Solution:\n def numMovesStonesII(self, stones: list[int]) -> list[int]:\n """\n 1. For the higher bound, it is determined by either moving the leftmost\n to the right side, or by moving the rightmost to the left side:\n 1.1 If moving leftmost to the right side, th... | 4 | 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 |
100 T and S | Commented and Explained With Examples | moving-stones-until-consecutive-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt the base of this problem is a linear scan. This is because we are trying to achieve the pairing of minimum number of moves and maximum number of moves. As such, we are trying to sort the move value space and scan over it linearly. This... | 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 | moving-stones-until-consecutive-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> numMovesStonesII(vector<int>& A) {\n sort(A.begin(), A.end());\n int i = 0, n = A.size(), low = n;\n int high = max(A[n - 1] - n + 2 - A[1], A[n - 2] - A[0] - n + 2);\n for (int j = 0; j < n; ++j) {\n while (A[j] - A[i] >= n) +... | 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 |
Clean Python | 8 Lines | High Speed | O(n) time, O(1) space | Beats 96.9% | With Explanation | moving-stones-until-consecutive-ii | 0 | 1 | # Intuition & Approach\n\n## Lower Bound\nAs I mentioned in my video last week,\nin case of `n` stones,\nwe need to find a consecutive `n` positions and move the stones in.\n\nThis idea led the solution with sliding windows.\n\nSlide a window of size `N`, and find how many stones are already in this window.\nWe want mo... | 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] sliding window | moving-stones-until-consecutive-ii | 0 | 1 | \n```\nclass Solution:\n def numMovesStonesII(self, stones: List[int]) -> List[int]:\n stones.sort()\n high = max(stones[-1] - stones[1], stones[-2] - stones[0]) - (len(stones) - 2)\n \n ii, low = 0, inf\n for i in range(len(stones)): \n while stones[i] - stones[ii] >= l... | 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 |
Python Solution. Pretty intuitive. | robot-bounded-in-circle | 0 | 1 | My first time posting a solution on Leetcode and I think the solution was unique so really proud of it.\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst of sorry for bad English.\nPretty Intuitive Solution.\nTook help from the hint given for the question to check if the circle is... | 6 | 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 Fastest Solution Explained (video + code) | robot-bounded-in-circle | 0 | 1 | [](https://www.youtube.com/watch?v=xgJh5HPCi3A)\nhttps://www.youtube.com/watch?v=xgJh5HPCi3A\n```\nclass Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n direction = (0,1)\n start = [0,0]\n \n for x in instructions:\n if x == \'G\':\n start[0] +... | 37 | 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 Solution using Dict | No Maths | robot-bounded-in-circle | 0 | 1 | Hello, I have a simpler solution that involves less of maths and more of logical thinking. \n\n```\n\tdef isRobotBounded(self, instructions: str) -> bool:\n curr_dir = \'N\'\n curr_pos = [0,0]\n directions = {\'N\':[0,1], \'E\':[1,0], \'W\':[-1,0], \'S\':[0,-1]}\n change_dir = {\n ... | 3 | 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 |
Python3 | robot-bounded-in-circle | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n x, y, dx, dy = 0, 0, 0, 1\n for ins in instructions:\n if ins == \'G\':\n x, y = x + dx, y + dy\n elif ins == \'L\':\n dx, dy = -dy, dx\n elif ins == ... | 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 |
⬆️✅🔥 100% | 0 MS | EASY | CONCISE | PROOF 🔥⬆️✅ | robot-bounded-in-circle | 1 | 1 | # UPVOTE PLS\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O... | 2 | 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 solution with explanation; O(N) | robot-bounded-in-circle | 0 | 1 | # Approach\nOne naive solution would be to run the instruction infinite time to see if there is a cycle. But obviously, it is not efficient.\n\nLet\'s look carefully! The robot always goes back to the initial point unless it looks towards north at the end of the movement and that point is not the initial point. That\'s... | 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 |
✔️ [Python3] LINEAR (≧∇≦)/❤, Explained | robot-bounded-in-circle | 0 | 1 | The robot stays in the circle only if at the end of instructions the angle between the final heading vector and the initial vector is not equal to 0. Only one exclusion is the case when the final position is the initial position. In this case, the final heading is not important, because it doesn\'t matter where the rob... | 2 | 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 |
SIMPLE PYTHON SOLUTION | flower-planting-with-no-adjacent | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBFS TRAVERSAL\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... | 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 |
Python || 94.80% Faster || Backtracking || Easy | flower-planting-with-no-adjacent | 0 | 1 | ```\nclass Solution:\n def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n graph=defaultdict(list)\n for u,v in paths:\n graph[u].append(v)\n graph[v].append(u)\n color=[0]*(n+1)\n self.solve(1,n,graph,color)\n return color[1:]\n \n def... | 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 |
Python 3 || 5 lines, sets, w/ with comments || T/M: 97% / 95% | flower-planting-with-no-adjacent | 0 | 1 | ```\nclass Solution:\n def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n\n d, ans = defaultdict(list), [0]*(n+1)\n \n for a, b in paths: d[a].append(b) ; d[b].append(a) # construct graph\n \n for i in range(1,n+1): # ... | 7 | 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 |
Linear solution, 93% speed | flower-planting-with-no-adjacent | 0 | 1 | \n```\nclass Solution:\n def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n neighbors = defaultdict(set)\n for a, b in paths:\n neighbors[a].add(b)\n ne... | 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 |
6-9 | flower-planting-with-no-adjacent | 0 | 1 | # Code\n```\nclass Solution:\n def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n graph = [[] for _ in range(n)]\n for x, y in paths:\n graph[x - 1].append(y - 1)\n graph[y - 1].append(x - 1)\n\n res = [0] * n\n\n for i in range(n):\n us... | 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 |
project6-9 | flower-planting-with-no-adjacent | 0 | 1 | # Code\n```\nclass Solution:\n def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n graph = [[] for _ in range(n)]\n for x, y in paths:\n graph[x - 1].append(y - 1)\n graph[y - 1].append(x - 1)\n\n res = [0] * n\n\n for i in range(n):\n us... | 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 |
[Python] Easy DP with Visualization and examples | partition-array-for-maximum-sum | 0 | 1 | \nHow to approach:\n\nAssume we only look ***back*** for dividing groups\n\nTake an example to see how to calculate and roll over:\n\n\nThen the states and transition function is as below:\n-\tFirst is to calcul... | 74 | Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fi... | null |
Python || 91.42% Faster || DP || Memo + Tabulation | partition-array-for-maximum-sum | 0 | 1 | ```\n#Recursion \n#Time Complexity: O(Exponential)\n#Space Complexity: O(n)\nclass Solution1:\n def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:\n def solve(ind):\n if ind==n:\n return 0\n l=0\n maxi=-maxsize\n maxAns=-maxsize\n ... | 2 | Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fi... | null |
Minimal explanation, 2 approaches | partition-array-for-maximum-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is intuitively a recursion and dynamic programming based problem.\nYou have to check for all possible cases with common sub-problems.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust read the recursive code,... | 1 | Given an integer array `arr`, partition the array into (contiguous) subarrays of length **at most** `k`. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return _the largest sum of the given array after partitioning. Test cases are generated so that the answer fi... | null |
双指针slide window | longest-duplicate-substring | 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. -->\nDefine left and right double pointers, treat the area of double pointers as a sliding window, at first the sliding window contains only the leftmost element in the str... | 2 | Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`.
**Example 1:**
**Input:** s = "ba... | null |
Simplest Python Solution || Easily Understandable | last-stone-weight | 0 | 1 | \n# Code\n```\nclass Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n \n while len(stones) > 1:\n stones.sort()\n m1=max(stones)\n stones.remove(m1)\n m2=max(stones)\n stones.remove(m2)\n \n if m1 < m2:\n ... | 1 | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* I... | One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we c... |
Easiest Solution || One Pass || O(1) memory | remove-all-adjacent-duplicates-in-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def removeDuplicates(self, s: str) -> str:\n idx =0\n while(idx+1<len(s)):\n if(s[idx]==s[idx+1]):\n s= s[:idx]+s[idx+2:]\n if idx > 0:\n idx -= 1\n else:\n idx += 1\n return ... | 1 | You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_... | null |
Python || Easy Solution || Stack | remove-all-adjacent-duplicates-in-string | 0 | 1 | # Code\n```\nclass Solution:\n def removeDuplicates(self, s: str) -> str:\n lis=[s[0]]\n for i in range(1,len(s)):\n if len(lis)==0 or lis[len(lis)-1]!=s[i]:\n lis.append(s[i])\n else:\n lis=lis[:len(lis)-1] \n s="".join(lis)\n re... | 1 | You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_... | null |
Python 3 || 8 lines, w/comments || T/S: 97% / 94% | longest-string-chain | 0 | 1 | \n```\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n \n d = defaultdict(int) # The keys for d are words. The values \n # are the # of predecessors of that word\n for word in sorted(words,key = len):\n ... | 6 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
Well commented Python code. Sort + dp | longest-string-chain | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n # store { word : maxlen } in dp\n # word will be used to track predecessor later on\n dp = {}\n W = sorted(words, key = len) \n # sorting based on length\n\n for w in W:\n dp[... | 2 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
Python3 | DP | Sorting | Time -> 96.22% | Space -> 93.85% | Solution | longest-string-chain | 0 | 1 | # Code\n```\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n res = 1\n words.sort(key=lambda x:len(x))\n dp = {word:1 for word in words}\n\n for i in range(1,len(words)):\n w = words[i]\n for j in range(len(w)):\n if w[:j]+w[j+1... | 2 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
Python3 Solution | longest-string-chain | 0 | 1 | \n```\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n dp={}\n for word in sorted(words,key=len):\n temp=[0]\n n=len(word)\n for i in range(n):\n if word[:i]+word[i+1:] in dp:\n temp.append(dp[word[:i]+word[i+1:]... | 2 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
Easy Top Down Approach (Commented Code) with Examples | longest-string-chain | 1 | 1 | \n# Code\n```\nclass Solution:\n def isSubsequence(self,s,t):\n n1=len(s)\n n2=len(t)\n i=n1-1\n j=n2-1\n while i>=0 and j>=0:\n if s[i]==t[j]:\n i-=1\n j-=1\n else:\n j-=1\n return True if i==-1 else False \... | 2 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
【Video】How we think about a solution - Beats 97.49% - Python, JavaScript, Java, C++ | longest-string-chain | 1 | 1 | This artcle starts with "How we think about a solution". In other words, that is my thought process to solve the question. This article explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope this aricle is helpful for someone.\n\n# Intuition\nSort all words by length ... | 32 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
LIS type solution and DFS solution with memo | longest-string-chain | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nSame as Longest common subsequence. We sort the list of words by length. If we can include the previous word then we add the longest chain at that previous word to current word.\n\nWe can check longest chain (backwards) for each word\n#... | 1 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
longestStrChain is Solution in Python3 | longest-string-chain | 0 | 1 | \n# Approach\n\nlet\'s break down the longestStrChain function step by step:\n\n1. dp = {}: We initialize an empty dictionary called dp to store information about the longest chain for each word.\n\n2. for w in sorted(words, key=len):: We loop through the input list words, but we process them in sorted order by their l... | 1 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
DFS tree traversal using Reg-Ex || Python ✅ | longest-string-chain | 0 | 1 | # Intuition\nA simple DFS approach.\n\n---\n\n\n# Approach\n- Building a DFS tree for every word in `words` array. \n\n- And storing the maximum no of elements for every word in words in `ma` if the number of elements is greater than the count `c`.\n\n---\n> Not an optimal approach as it contains regex comparisions and... | 1 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
✅ 95.46% DP & Memo | longest-string-chain | 1 | 1 | # Interview Guide: "Longest String Chain" Problem\n\n## Problem Understanding\n\nThe "Longest String Chain" problem presents you with an array of words. The objective is to identify the lengthiest chain of words where every word in the chain acts as a predecessor to the subsequent word. A word, say `A`, stands as a pre... | 85 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
[Python] LIS Variation | Easy to Understand | Tabulation Approach | longest-string-chain | 0 | 1 | ```\nclass Solution:\n def longestStrChain(self, words: List[str]) -> int:\n words = sorted(list(set(words)), key=len)\n dp = [1] * len(words)\n \n for i in range(0, len(words)):\n for j in range(0, i):\n \n wordA = words[i]\n wordB ... | 1 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
longest possible word chain | longest-string-chain | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nMy initial thoughts on how to solve this problem were to:\n\n1. Sort the words by length to consider shorter words first.\n2. Use dynamic programming to iteratively calculate the longest chain length for each word by considering its pos... | 1 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
Rabin-Karp rolling hash algo [Optimized complexity][O(W * L)] | longest-string-chain | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing of Rabin-Karp algorithm can reduce generation all hashes of predecessors for linear time.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOriginal Rabin-Karp Rolling Hash formula:\n$$hash(S) = S_1 \\cdot P^{k... | 1 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
🚀 97.50% || DP Recursive & Iterative || Commented Code🚀 | longest-string-chain | 1 | 1 | # Problem Description\nGiven an **array** of words, each composed of **lowercase** English letters.\n\nA word `wordA` is considered a **predecessor** of another word `wordB` if and only if we can **insert** exactly **one** letter anywhere in `wordA`, **without changing** the **order** of the other characters, to make i... | 33 | You are given an array of `words` where each word consists of lowercase English letters.
`wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`.
* For example, `"abc "` is a **... | null |
easisest python solution, beats 87/93% | height-checker | 0 | 1 | \n# Code\n```\nclass Solution:\n def heightChecker(self, heights: List[int]) -> int:\n h = sorted(heights)\n ans = 0\n for i in range(0, len(heights)):\n if h[i] != heights[i]:\n ans += 1\n return ans\n``` | 1 | A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line.
You are given an integer... | Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assur... |
Python simple and easy to understand code. Faster than 92.67% 39ms runtime | height-checker | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nsimply sort heights in increasing order and store in expected, then use list comprehension for get a list when heights[i] != expected[i], after that just return the length of that list.\n\n\n# Code\n```\nclass Solution:\n def heightChecker(self, ... | 4 | A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line.
You are given an integer... | Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assur... |
Python | Sort | Faster than 98.86% | height-checker | 0 | 1 | The idea here is to sort the given array and then compare the sorted array with the given array. \n\n```\nclass Solution:\n def heightChecker(self, heights: List[int]) -> int:\n sort_heights = sorted(heights)\n return sum([0 if heights[i] == sort_heights[i] else 1 for i in range(len(heights))])\n```\n\... | 10 | A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line.
You are given an integer... | Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assur... |
Python with explanation. Rolling sum. | grumpy-bookstore-owner | 0 | 1 | The way I approached this problem was to split it into 2 smaller problems. \n\nThe first involves counting how many customers are already satisfied, i.e. those where the shopkeeper is not grumpy. I also set any slots with already satisfied customers to 0, so that we will be left with only the currently unsatisfied cust... | 153 | There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the `ith` minute and all those customers leave after... | Sort the elements by distance. In case of a tie, sort them by the index of the worker. After that, if there are still ties, sort them by the index of the bike.
Can you do this in less than O(nlogn) time, where n is the total number of pairs between workers and bikes? Loop the sorted elements and match each pair of wor... |
Sliding window + Explaination | grumpy-bookstore-owner | 1 | 1 | The code starts by calculating the total number of customers satisfied when the owner is not grumpy.\n\nNext, a sliding window approach is used to iterate through all possible time periods of length "minutes". For each window, the total number of satisfied customers is calculated by subtracting the unsatisfied customer... | 2 | There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the `ith` minute and all those customers leave after... | Sort the elements by distance. In case of a tie, sort them by the index of the worker. After that, if there are still ties, sort them by the index of the bike.
Can you do this in less than O(nlogn) time, where n is the total number of pairs between workers and bikes? Loop the sorted elements and match each pair of wor... |
Python 3 || 6 lines, w/example || T/M: 100% /88% | grumpy-bookstore-owner | 0 | 1 | ```\nclass Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n\n # Example: customers = [1,0,2,7,5]\n # grumpy = [0,1,1,0,1]\n ... | 4 | There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the `ith` minute and all those customers leave after... | Sort the elements by distance. In case of a tie, sort them by the index of the worker. After that, if there are still ties, sort them by the index of the bike.
Can you do this in less than O(nlogn) time, where n is the total number of pairs between workers and bikes? Loop the sorted elements and match each pair of wor... |
Sliding Window Rolling sum Python 3 | grumpy-bookstore-owner | 0 | 1 | ```\nclass Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n satisfied=0\n n=len(grumpy)\n satisfied=sum([customers[i]*(1-grumpy[i]) for i in range(n)])\n max_satisfied=satisfied\n for i in range(n):\n if grumpy[i]==1: sa... | 2 | There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the `ith` minute and all those customers leave after... | Sort the elements by distance. In case of a tie, sort them by the index of the worker. After that, if there are still ties, sort them by the index of the bike.
Can you do this in less than O(nlogn) time, where n is the total number of pairs between workers and bikes? Loop the sorted elements and match each pair of wor... |
AC readable Python, 9 lines | grumpy-bookstore-owner | 0 | 1 | ```\ndef maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:\n\tm = s = tmp = 0\n\tfor i in range(len(customers)):\n\t\tif not grumpy[i]: \n\t\t\ts += customers[i] # sum of satisfied customers\n\t\t\tcustomers[i] = 0 \n\t\telse: tmp += customers[i] # sum of grumpy custo... | 12 | There is a bookstore owner that has a store open for `n` minutes. Every minute, some number of customers enter the store. You are given an integer array `customers` of length `n` where `customers[i]` is the number of the customer that enters the store at the start of the `ith` minute and all those customers leave after... | Sort the elements by distance. In case of a tie, sort them by the index of the worker. After that, if there are still ties, sort them by the index of the bike.
Can you do this in less than O(nlogn) time, where n is the total number of pairs between workers and bikes? Loop the sorted elements and match each pair of wor... |
PYTHON SOL | GREEDY | WELL EXPLAINED | SIMPLE | EFFICIENT APPROACH | | previous-permutation-with-one-swap | 0 | 1 | # EXPLANATION\n```\nWe need to find the next smaller permutation of arr is exists \n\nSo for this we think greedily i.e. we must replace the index having value x such that there exists a smaller value y having index > index of x and index of x must be as right as possible\n\nWhat I mean is say arr = [3,1,9,3,4,5,6]\nHe... | 2 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
python O(n) time, O(1) space with explanation | previous-permutation-with-one-swap | 0 | 1 | I would suggest doing this question first:\n\n[31. Next Permutation](/https://leetcode.com/problems/next-permutation/ )\n\n[this will help understand what a next permutatin even is](https://www.nayuki.io/page/next-lexicographical-permutation-algorithmttp://)\n\nalso a note about the word "non-decreasing" and why I didn... | 3 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Python3 easy O(N) solution explained | previous-permutation-with-one-swap | 0 | 1 | ```\nclass Solution:\n def prevPermOpt1(self, arr: List[int]) -> List[int]:\n # find the first pair of values that is NOT in increasing order\n i = len(arr) - 1\n while i > 0 and arr[i-1] <= arr[i]:\n i -= 1\n if i > 0:\n # if you find such a pair\n # find... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Python easy sol... | previous-permutation-with-one-swap | 0 | 1 | # Code\n```\nclass Solution:\n def prevPermOpt1(self, arr: List[int]) -> List[int]:\n for i in range(len(arr)-1,0,-1):\n if arr[i]<arr[i-1]:\n ind=i-1\n break\n else:\n return arr\n m=ind+1\n for i in range(ind+1,len(arr)):\n ... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
[Python] Greedy + priority queue | previous-permutation-with-one-swap | 0 | 1 | # Intuition\n- Find the last index `i with (0 <= i < arr.length -1)` where `arr[i] > arr[i + 1]` (That mean where the array is not sorted non-decreasinly).\n- Swap it with `max(arr[i + 1 ~ arr.length - 1])` that is less than `arr[i]`.\n\n\n# Code\n```\nclass Solution:\n def prevPermOpt1(self, arr: List[int]) -> List... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
PYTHON SOLUTION USING STACK | previous-permutation-with-one-swap | 0 | 1 | ```\nclass Solution:\n def prevPermOpt1(self, arr: List[int]) -> List[int]:\n stack=[len(arr)-1]\n for i in range(len(arr)-2,-1,-1):\n if stack and arr[stack[-1]]<arr[i]:\n while stack and arr[stack[-1]]<arr[i]:\n popped_index=stack.pop()\n ar... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Solution | previous-permutation-with-one-swap | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> prevPermOpt1(vector<int>& A) {\n int n = A.size();\n int i = n - 2;\n while (i >= 0 && A[i] <= A[i+1]) i--;\n if (i < 0) return A;\n int j = n - 1;\n while (j > i && A[j] >= A[i]) j--;\n while (A[j] == A[j-1]) j--;\n ... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Fix first violation of ordering | previous-permutation-with-one-swap | 0 | 1 | # Intuition\nThink it as an integer, where each digit can be arbitrary large.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo find the predecessor of the given number with ordering constraint, we\'d like to tweak the left digit of first violation from right to left with the rightm... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
[Python3] 7 - Lines (Beats 100%, Binary Search, O(n+log(n))) | previous-permutation-with-one-swap | 0 | 1 | 1) Find the first decreasing number from the end\n2) Since up to this point all numbers are non-decreasing we can binary search the closest number\n3) If the number repeats, find the left-most one\n# Code\n```\nclass Solution:\n def prevPermOpt1(self, arr: List[int]) -> List[int]:\n for i in range(len(arr)-2,... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Greedy and Two Pointers | dpm07 | previous-permutation-with-one-swap | 0 | 1 | """\nSImple Strarigy:\n\nif left side of array (last 2 ele are NOT sorted) make them sort,\nif already sorted cycle the array to right ie. big_elememt to last and shift rest accordingly \n"""\n\n\n\n```\n\nclass Solution:\n\t"""\n\tGreedy Algo O(n)\n\n\twe start by finding the largest index i such that arr[i] > arr[i +... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Clean Python | High Speed | O(n) time, O(1) space | Beats 98.9% | previous-permutation-with-one-swap | 0 | 1 | # Code\n```\nclass Solution: \n def prevPermOpt1(self, A: List[int]) -> List[int]:\n end_A = [A.pop()]\n length = len(A)\n while A:\n a = A.pop()\n # find if the largest number less than a in end_A\n next_largest = float("-Infinity")\n next_large... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
Python 3 step solution, Rise, Replacement and Swap! | previous-permutation-with-one-swap | 0 | 1 | # Intuition\nOnce you have solved next largest permutation, this one would strike immediately\n# Approach\n1) find the last fall as you u traverse from left to right or first rise when traversing from right to left. \n2) Once you got the rise, find the index and value of the next smallest integer to the rise.\n3) swap ... | 0 | Given an array of positive integers `arr` (not necessarily distinct), return _the_ _lexicographically_ _largest permutation that is smaller than_ `arr`, that can be **made with exactly one swap**. If it cannot be done, then return the same array.
**Note** that a _swap_ exchanges the positions of two numbers `arr[i]` a... | If we have integer values in the array then we just need to subtract the target those integer values, so we reduced the problem. Similarly if we have non integer values we have two options to put them flor(value) or ceil(value) = floor(value) + 1, so the idea is to just subtract floor(value). Now the problem is differe... |
82% TC easy python solution | distant-barcodes | 0 | 1 | ```\ndef rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n\tc = Counter(barcodes)\n\theap = []\n\tfor i in c:\n\t\theappush(heap, (-c[i], i))\n\tans = []\n\tprev = -1\n\twhile(heap):\n\t\tcount, t = heappop(heap)\n\t\tif(prev != t):\n\t\t\tans.append(t)\n\t\t\tprev = t\n\t\t\tif(count+1): heappush(heap, (cou... | 2 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
[Python] Counter & Heap Solution with detailed comments! | distant-barcodes | 0 | 1 | ```python\ndef rearrangeBarcodes(barcodes):\n\n\t# Our result to return\n\tresult = []\n\t\n\t# Get the counts\n\tcounts = collections.Counter(barcodes)\n\t\n\t# Create a max-heap based on count\n\theap = [[-v, k] for k, v in counts.items()]\n\t\n\t# Heapify the heap\n\theapq.heapify(heap)\n\t\n\t# Get the first item\n... | 8 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
[Python] O(n) using Dictionary | distant-barcodes | 0 | 1 | Approach:\nInspired from the method proposed by [rock](https://leetcode.com/problems/distant-barcodes/discuss/300394/JavaPython-3-2-easy-codes-w-comments-O(nlogn)-and-O(n)-respectively.)\n1. Obtain the frequencies of the barcodes\n2. Fill the alternative indices of the result array with the code with maximum frequency\... | 9 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
Easy python solution using heap (priority queue) | distant-barcodes | 0 | 1 | # Intuition\nCount the freq of each type of bar and store in a `dict`. next push the items of the dict into a `heap`. finally pop from the max heap and append to an output list. if the popped element is same as the last element of the `output` then pop again and append that element. after popping change the counter to ... | 0 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
Simpe python3 solution | Heap + Greedy | distant-barcodes | 0 | 1 | # Complexity\n- Time complexity: $$O(n \\cdot \\log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nimport heapq\n\nclass Solution:\n def rearrangeBarcodes(self, barcodes: List[int]) -> Lis... | 0 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
Explained in Detail and With Unit Tests | distant-barcodes | 0 | 1 | ## Follow Vaclav Kosar for more software and machine learning at https://vaclavkosar.com/\n\n\n```\nfrom collections import Counter\nfrom heapq import heappush, heappop\nfrom typing import List\n\n\nclass Solution:\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n """\n The barcodes is... | 0 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
✅heap solution || Python | distant-barcodes | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n d={}\n for i in barcodes:\n d[i]=d.get(i,0)+1\n l=[]\n for a,b in d.items():\n l.append([-1*b,a])\n heapify(l)\n # print(l)\n ans=[]\n whil... | 0 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
[Python3] Good enough | distant-barcodes | 0 | 1 | ``` Python3 []\nclass Solution:\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n mapping = Counter(barcodes)\n heap = []\n\n for k,v in mapping.items():\n heapq.heappush(heap, (-v, k))\n \n final = []\n\n while heap:\n temp = None\n ... | 0 | In a warehouse, there is a row of barcodes, where the `ith` barcode is `barcodes[i]`.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
**Example 1:**
**Input:** barcodes = \[1,1,1,2,2,2\]
**Output:** \[2,1,2,1,2,1\]
**Example 2:**
... | A binary number plus its complement will equal 111....111 in binary. Also, N = 0 is a corner case. |
Simple Python Solution with explanation 🔥 || beats 96.5% | lexicographically-smallest-equivalent-string | 0 | 1 | # Approach\n\n* Create two maps `char_group` and `char_map` to track characters which are equivalent:\n \n \n\n `char_group` is a map of groups of characters which are equiva... | 8 | You are given two strings of the same length `s1` and `s2` and a string `baseStr`.
We say `s1[i]` and `s2[i]` are equivalent characters.
* For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`.
Equivalent characters follow the usual rules of any equivalence rela... | Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position. |
MOST OPTIMIZED PYTHON SOLUTION || CLASS BASED STRUCTURE | lexicographically-smallest-equivalent-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 5 | You are given two strings of the same length `s1` and `s2` and a string `baseStr`.
We say `s1[i]` and `s2[i]` are equivalent characters.
* For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`.
Equivalent characters follow the usual rules of any equivalence rela... | Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position. |
Python3 Simple Depth-First Search | lexicographically-smallest-equivalent-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is obviously an undirected graph question at first glance, so we will connect the characters first. Also, to avoid repeating search when constructing smallest ```baseStr```, we will find the smallest character for each character firs... | 7 | You are given two strings of the same length `s1` and `s2` and a string `baseStr`.
We say `s1[i]` and `s2[i]` are equivalent characters.
* For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`.
Equivalent characters follow the usual rules of any equivalence rela... | Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position. |
Python | Union Find | Easy and Simple Solution | lexicographically-smallest-equivalent-string | 0 | 1 | \n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:\n parent = defaultdict(str)\n for c in \'abcdefghijklmnopqrstuvwxyz\':\n parent[c] = c \n def find(v):\n if parent[v] != v:\n ... | 2 | You are given two strings of the same length `s1` and `s2` and a string `baseStr`.
We say `s1[i]` and `s2[i]` are equivalent characters.
* For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`.
Equivalent characters follow the usual rules of any equivalence rela... | Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.