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 |
|---|---|---|---|---|---|---|---|
Unhappy Friends: T=O(n^2), S=O(n^2) | count-unhappy-friends | 0 | 1 | # Intuition\n#iterate over pairs (partners)\n#identify the list of friends that each person prefers over their partner\n#check whether the prefered person also prefers me backwards\n#if yes, increment the count as I am unhappy\n#break the inner loop to avoid double counting my unhappiness\n\n# Complexity\n#T=O(n^2),S=O... | 0 | You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denot... | Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j. |
Unhappy Friends: T=O(n^2), S=O(n^2) | count-unhappy-friends | 0 | 1 | # Intuition\n#iterate over pairs (partners)\n#identify the list of friends that each person prefers over their partner\n#check whether the prefered person also prefers me backwards\n#if yes, increment the count as I am unhappy\n#break the inner loop to avoid double counting my unhappiness\n\n# Complexity\n#T=O(n^2),S=O... | 0 | There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by ... | Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people |
Python Intuitive | count-unhappy-friends | 0 | 1 | # Code\n```\nclass Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n\n partner = {}\n\n for a, b in pairs:\n partner[a] = b\n partner[b] = a\n\n table = collections.defaultdict(dict)\n\n for person, p in enum... | 0 | You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denot... | Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j. |
Python Intuitive | count-unhappy-friends | 0 | 1 | # Code\n```\nclass Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n\n partner = {}\n\n for a, b in pairs:\n partner[a] = b\n partner[b] = a\n\n table = collections.defaultdict(dict)\n\n for person, p in enum... | 0 | There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by ... | Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people |
Python Slower but Easier to Understand Solution | count-unhappy-friends | 0 | 1 | # Code\n```\nclass Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n lookup = defaultdict(dict)\n for idx, preference in enumerate(preferences):\n for idx2, friend in enumerate(preference):\n lookup[idx][friend] = idx2... | 0 | You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denot... | Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j. |
Python Slower but Easier to Understand Solution | count-unhappy-friends | 0 | 1 | # Code\n```\nclass Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n lookup = defaultdict(dict)\n for idx, preference in enumerate(preferences):\n for idx2, friend in enumerate(preference):\n lookup[idx][friend] = idx2... | 0 | There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by ... | Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people |
Prime's Algorithm || Beats 97% | min-cost-to-connect-all-points | 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)$$ --... | 2 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Prime's Algorithm || Beats 97% | min-cost-to-connect-all-points | 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)$$ --... | 2 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Python3 Solution | min-cost-to-connect-all-points | 0 | 1 | \n```\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n n=len(points)\n def find(parent,x):\n if parent[x]==x:\n return x\n parent[x]=find(parent,parent[x])\n return parent[x]\n\n def union(parent,x,y):\n ... | 2 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Python3 Solution | min-cost-to-connect-all-points | 0 | 1 | \n```\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n n=len(points)\n def find(parent,x):\n if parent[x]==x:\n return x\n parent[x]=find(parent,parent[x])\n return parent[x]\n\n def union(parent,x,y):\n ... | 2 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
✅ 94.85% Prim & Kruskal with Min-Heap | min-cost-to-connect-all-points | 1 | 1 | # Comprehensive Guide to Solving "Min Cost to Connect All Points": Bridging the Gap Efficiently\n\n## Introduction & Problem Statement\n\nHello, algorithmic explorers! Today, we\'re diving into a problem that\'s a fascinating blend of computational geometry and graph theory: "Min Cost to Connect All Points." Imagine yo... | 97 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
✅ 94.85% Prim & Kruskal with Min-Heap | min-cost-to-connect-all-points | 1 | 1 | # Comprehensive Guide to Solving "Min Cost to Connect All Points": Bridging the Gap Efficiently\n\n## Introduction & Problem Statement\n\nHello, algorithmic explorers! Today, we\'re diving into a problem that\'s a fascinating blend of computational geometry and graph theory: "Min Cost to Connect All Points." Imagine yo... | 97 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Easiest py solution using kruskals | min-cost-to-connect-all-points | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can think of the given points as nodes of a graph. The weight of an edge between two nodes is the Manhattan distance between the corresponding points. The goal is to find the minimum cost to connect all these points.\n# Approach\n<!-- ... | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Easiest py solution using kruskals | min-cost-to-connect-all-points | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can think of the given points as nodes of a graph. The weight of an edge between two nodes is the Manhattan distance between the corresponding points. The goal is to find the minimum cost to connect all these points.\n# Approach\n<!-- ... | 1 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
【Video】Improved Prim's algorithm solution - Python, JavaScript, Java and C++ | min-cost-to-connect-all-points | 1 | 1 | # Intuition\nThe main idea of this algorithm is to find the minimum cost to connect all points in a set using a greedy approach based on Prim\'s algorithm. It starts by selecting an arbitrary point as the initial vertex and maintains a priority queue to keep track of the minimum-cost edges to connect the vertices. The ... | 33 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
【Video】Improved Prim's algorithm solution - Python, JavaScript, Java and C++ | min-cost-to-connect-all-points | 1 | 1 | # Intuition\nThe main idea of this algorithm is to find the minimum cost to connect all points in a set using a greedy approach based on Prim\'s algorithm. It starts by selecting an arbitrary point as the initial vertex and maintains a priority queue to keep track of the minimum-cost edges to connect the vertices. The ... | 33 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Insanely efficient Prim's implementation, beats 99.68% runtime, 99.96% memory | min-cost-to-connect-all-points | 0 | 1 | # Code\n```\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n distances = [[0, 0]] + [[float(\'inf\'), i] for i in range(1, len(points))]\n result = 0\n while distances:\n closest = min(distances)\n result += closest[0]\n x, y =... | 0 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Insanely efficient Prim's implementation, beats 99.68% runtime, 99.96% memory | min-cost-to-connect-all-points | 0 | 1 | # Code\n```\nclass Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n distances = [[0, 0]] + [[float(\'inf\'), i] for i in range(1, len(points))]\n result = 0\n while distances:\n closest = min(distances)\n result += closest[0]\n x, y =... | 0 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
✔Graph || Prims Algorithm✨💎 || Kruskal's Algorithm👀|| Easy to Understand😉😎 | min-cost-to-connect-all-points | 1 | 1 | # Intuition\n- The problem involves finding the minimum cost to connect a set of points using Prim\'s Algorithm, which is a greedy algorithm used for finding the minimum spanning tree (MST) of a graph. \n- In this case, the graph represents the distances between points, and the goal is to connect all points with edges ... | 6 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
✔Graph || Prims Algorithm✨💎 || Kruskal's Algorithm👀|| Easy to Understand😉😎 | min-cost-to-connect-all-points | 1 | 1 | # Intuition\n- The problem involves finding the minimum cost to connect a set of points using Prim\'s Algorithm, which is a greedy algorithm used for finding the minimum spanning tree (MST) of a graph. \n- In this case, the graph represents the distances between points, and the goal is to connect all points with edges ... | 6 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
[Python] Simple and Concise MST with Explanation | min-cost-to-connect-all-points | 0 | 1 | ### Introduction\n\nWe need to connect all given `points` in a graph such that the sum of the Manhattan distances between every pair of points connected is the absolute minimum. This is equivalent to finding the total weight of the minimum spanning tree (MST) which connects these `points`.\n\n---\n\n### Implementation\... | 78 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
[Python] Simple and Concise MST with Explanation | min-cost-to-connect-all-points | 0 | 1 | ### Introduction\n\nWe need to connect all given `points` in a graph such that the sum of the Manhattan distances between every pair of points connected is the absolute minimum. This is equivalent to finding the total weight of the minimum spanning tree (MST) which connects these `points`.\n\n---\n\n### Implementation\... | 78 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Purely Kruskal's algorithm. | min-cost-to-connect-all-points | 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)$$ --... | 2 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Purely Kruskal's algorithm. | min-cost-to-connect-all-points | 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)$$ --... | 2 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Python 95.74% two minimum spanning tree algorithms Clean Code ✅ | min-cost-to-connect-all-points | 0 | 1 | # Prim\'s algorithm\n\n```python []\nclass Solution:\n def minCostConnectPoints(self, points: list[list[int]]) -> int:\n n = len(points)\n visited = [False] * n\n adj_list = [[] for _ in range(n)]\n for i in range(n):\n for j in range(i + 1, n):\n dis = abs(point... | 4 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Python 95.74% two minimum spanning tree algorithms Clean Code ✅ | min-cost-to-connect-all-points | 0 | 1 | # Prim\'s algorithm\n\n```python []\nclass Solution:\n def minCostConnectPoints(self, points: list[list[int]]) -> int:\n n = len(points)\n visited = [False] * n\n adj_list = [[] for _ in range(n)]\n for i in range(n):\n for j in range(i + 1, n):\n dis = abs(point... | 4 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Python 3 | Min Spanning Tree | Prim's Algorithm | min-cost-to-connect-all-points | 0 | 1 | ### Explanation\n- This is a typical **minimum spanning tree** question, it can be solved using either *Kruskal* or *Prim*\'s algorithm\n- Below is a **Prim**\'s algorithm implementation\n- Here is a wiki for Pirm\'s algorithm https://en.wikipedia.org/wiki/Prim%27s_algorithm\n- Time Complexity: Prim\'s Algorithm takes ... | 111 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the m... | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Python 3 | Min Spanning Tree | Prim's Algorithm | min-cost-to-connect-all-points | 0 | 1 | ### Explanation\n- This is a typical **minimum spanning tree** question, it can be solved using either *Kruskal* or *Prim*\'s algorithm\n- Below is a **Prim**\'s algorithm implementation\n- Here is a wiki for Pirm\'s algorithm https://en.wikipedia.org/wiki/Prim%27s_algorithm\n- Time Complexity: Prim\'s Algorithm takes ... | 111 | You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top... | Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges. |
Logical Order Elimination | Modified Kahn's Algorithm | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\nFaced with any substring sorting problems, I\'m drawn to maps and graphs for ease of search space. As such, we can consider this one with not too much of a stretch of the mind. \n\nEach integer value in our selected string has a list of indices at which it appears. IF we make a mapping of these list of ind... | 0 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Logical Order Elimination | Modified Kahn's Algorithm | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\nFaced with any substring sorting problems, I\'m drawn to maps and graphs for ease of search space. As such, we can consider this one with not too much of a stretch of the mind. \n\nEach integer value in our selected string has a list of indices at which it appears. IF we make a mapping of these list of ind... | 0 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
Check If String Is Transformable With Substring Sort Operations. Souvik Hazra | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Check If String Is Transformable With Substring Sort Operations. Souvik Hazra | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
Inversions BIT | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass BIT():\n def __init__(self, n):\n self.n = n\n self.tree = [0] * (n + 1)\n\n def sum(self, i):\n ans = 0\n i += 1\n while i > 0:\n ans += self.tree[i]\n i -= (i & (-i))\n ... | 0 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Inversions BIT | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass BIT():\n def __init__(self, n):\n self.n = n\n self.tree = [0] * (n + 1)\n\n def sum(self, i):\n ans = 0\n i += 1\n while i > 0:\n ans += self.tree[i]\n i -= (i & (-i))\n ... | 0 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
Python (Simple Hashmap) | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Python (Simple Hashmap) | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
Python 3 solution with explanation | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\nIf we have an s[i] in i index we see from what index to what index it can be moved i.e s[i] can be placed at any index in range **lower_index, upper_index** in s\n\n# Approach\nthe intuition is to check where each digit at index i in string s can go upto \nfor example let s = \'3158581\' here 5 at index 2 ... | 0 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Python 3 solution with explanation | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\nIf we have an s[i] in i index we see from what index to what index it can be moved i.e s[i] can be placed at any index in range **lower_index, upper_index** in s\n\n# Approach\nthe intuition is to check where each digit at index i in string s can go upto \nfor example let s = \'3158581\' here 5 at index 2 ... | 0 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
With deques, beats 98% time, 96 space (not sure why though) | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\nPb can be nicely reduced to: \'for each digit of t, check if its first occurence in s is only preceded by bigger numbers\'\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe keep track of the the order of appearance in s via a collection of deque representing the ascendi... | 1 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
With deques, beats 98% time, 96 space (not sure why though) | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | # Intuition\nPb can be nicely reduced to: \'for each digit of t, check if its first occurence in s is only preceded by bigger numbers\'\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe keep track of the the order of appearance in s via a collection of deque representing the ascendi... | 1 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
[Python3] 8-line deque | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | \n```\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n if sorted(s) != sorted(t): return False # edge case \n \n pos = [deque() for _ in range(10)]\n for i, ss in enumerate(s): pos[int(ss)].append(i)\n \n for tt in t: \n i = pos[int(tt)]... | 2 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` res... | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
[Python3] 8-line deque | check-if-string-is-transformable-with-substring-sort-operations | 0 | 1 | \n```\nclass Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n if sorted(s) != sorted(t): return False # edge case \n \n pos = [deque() for _ in range(10)]\n for i, ss in enumerate(s): pos[int(ss)].append(i)\n \n for tt in t: \n i = pos[int(tt)]... | 2 | You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`.
The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for a... | Suppose the first digit you need is 'd'. How can you determine if it's possible to get that digit there? Consider swapping adjacent characters to maintain relative ordering. |
python 3 99.78% faster and 100% less space | sum-of-all-odd-length-subarrays | 0 | 1 | The idea is to count the frequency of each element in `arr` appearing in the sub array, then sum up `arr[i]*freq[i]`. The key is how to count the `freq[i]` of each element `arr[i]`. Actually, `freq[i] = freq[i-1]-(i+1)//2+(n-i+1)//2`. `n` is the `arr` length.\n\nfor example `arr = [1,4,2,5,3]`, element `arr[0] = 1`. Th... | 127 | Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4... | null |
🚩Easy C++ O(N) Soln. [ FAANG😱 Interview Optimized code ] | sum-of-all-odd-length-subarrays | 1 | 1 | Well, this problem is not as easy as it looks. A bit tricky tbh! \nBut here\'s a simple explaination :\n* No. of even subarrays = Total/2\n* No. of odd subarrays = (Total+1)/2\nTotal subarrays can be found by considering an element and taking all subarrays to its left and right.\nSubarrays to the left = i+1\nSubarrays ... | 40 | Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4... | null |
4 lines of code beats 99.94% see code with proof very easy | sum-of-all-odd-length-subarrays | 0 | 1 | # Beats 99.94% image for proof:\n\n\n# Code\n```\nclass Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n n=len(arr)\n s=0\n for i in range(n):\n s+=... | 1 | Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4... | null |
very easy approach | sum-of-all-odd-length-subarrays | 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 of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4... | null |
Python Simple Solution | sum-of-all-odd-length-subarrays | 0 | 1 | ```\nclass Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n s=0\n for i in range(len(arr)):\n for j in range(i,len(arr),2):\n s+=sum(arr[i:j+1])\n return s\n``` | 63 | Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4... | null |
44ms, Python (with comments and detailed walkthrough) | sum-of-all-odd-length-subarrays | 0 | 1 | If you find this post helpful, please **Upvote** :)\n```\nclass Solution(object):\n def sumOddLengthSubarrays(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n\t\t#We declare our output variable with the initial value as the sum of all elements as this is the 1st iteration of... | 33 | Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4... | null |
simple python solution || greedy || prefix sum || nlog(n) | maximum-sum-obtained-of-any-permutation | 0 | 1 | # Intuition and approach\n**since we can use any permutation of list.so we will use greedy approach for purmutation selection of list. we will place the maximum element at the index which is included in most intervals.\n\n**now we have to find the index which occured in most interval. this can be done using "PREFIX SUM... | 1 | We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_.
Return _the maximum total sum of all requests **among all permuta... | null |
simple python solution || greedy || prefix sum || nlog(n) | maximum-sum-obtained-of-any-permutation | 0 | 1 | # Intuition and approach\n**since we can use any permutation of list.so we will use greedy approach for purmutation selection of list. we will place the maximum element at the index which is included in most intervals.\n\n**now we have to find the index which occured in most interval. this can be done using "PREFIX SUM... | 1 | You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray... | Indexes with higher frequencies should be bound with larger values |
[Python 3] Sweep line Algorithm | maximum-sum-obtained-of-any-permutation | 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)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here... | 1 | We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_.
Return _the maximum total sum of all requests **among all permuta... | null |
[Python 3] Sweep line Algorithm | maximum-sum-obtained-of-any-permutation | 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)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here... | 1 | You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray... | Indexes with higher frequencies should be bound with larger values |
Python 3: Simple Sweep Line Solution | maximum-sum-obtained-of-any-permutation | 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 | We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_.
Return _the maximum total sum of all requests **among all permuta... | null |
Python 3: Simple Sweep Line Solution | maximum-sum-obtained-of-any-permutation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray... | Indexes with higher frequencies should be bound with larger values |
Explaining the frequency array | An integral | maximum-sum-obtained-of-any-permutation | 0 | 1 | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\nCameras contains the number of cameras at each intersection where cameras[i] = the number of cameras at intersection $i$. Requests contains all the intesection ranges where you used a boost to speed up temporarily.\n\nYour sus score, me... | 0 | We have an array of integers, `nums`, and an array of `requests` where `requests[i] = [starti, endi]`. The `ith` request asks for the sum of `nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]`. Both `starti` and `endi` are _0-indexed_.
Return _the maximum total sum of all requests **among all permuta... | null |
Explaining the frequency array | An integral | maximum-sum-obtained-of-any-permutation | 0 | 1 | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\nCameras contains the number of cameras at each intersection where cameras[i] = the number of cameras at intersection $i$. Requests contains all the intesection ranges where you used a boost to speed up temporarily.\n\nYour sus score, me... | 0 | You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray... | Indexes with higher frequencies should be bound with larger values |
How to approach this kind of problem - mind map | make-sum-divisible-by-p | 0 | 1 | If you are new to this kind of problems, you would probably get confused. No worries! Here are list of some prior knowledge you may want to go through before touching it.\n\n- [Leetcode 560. Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/)\nso that you know how to use prefix sum and hashmap ... | 138 | Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A ... | null |
How to approach this kind of problem - mind map | make-sum-divisible-by-p | 0 | 1 | If you are new to this kind of problems, you would probably get confused. No worries! Here are list of some prior knowledge you may want to go through before touching it.\n\n- [Leetcode 560. Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/)\nso that you know how to use prefix sum and hashmap ... | 138 | You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f... | Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i... |
WEEB DOES PYTHON/C++ | make-sum-divisible-by-p | 0 | 1 | **Python 3**\n\n\tclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n dp = defaultdict(int)\n dp[0] = -1\n target = sum(nums) % p\n curSum = 0\n result = len(nums)\n \n if sum(nums) % p == 0: return 0\n \n for i in range(len(nums))... | 2 | Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A ... | null |
WEEB DOES PYTHON/C++ | make-sum-divisible-by-p | 0 | 1 | **Python 3**\n\n\tclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n dp = defaultdict(int)\n dp[0] = -1\n target = sum(nums) % p\n curSum = 0\n result = len(nums)\n \n if sum(nums) % p == 0: return 0\n \n for i in range(len(nums))... | 2 | You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f... | Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i... |
solution | make-sum-divisible-by-p | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A ... | null |
solution | make-sum-divisible-by-p | 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 phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f... | Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i... |
Hashtable with py3 beating 98.80% | make-sum-divisible-by-p | 0 | 1 | \n# Code\n```\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n n = len(nums)\n totalrem = sum(nums) % p\n if totalrem == 0:\n return 0\n dp = {} // you have to use a dict rather than list to avoid MLE\n presum = 0\n res = float(\'inf\')\... | 0 | Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A ... | null |
Hashtable with py3 beating 98.80% | make-sum-divisible-by-p | 0 | 1 | \n# Code\n```\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n n = len(nums)\n totalrem = sum(nums) % p\n if totalrem == 0:\n return 0\n dp = {} // you have to use a dict rather than list to avoid MLE\n presum = 0\n res = float(\'inf\')\... | 0 | You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f... | Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i... |
google interview | make-sum-divisible-by-p | 0 | 1 | thanks to @lee215\n\n# Intuition\n\n\n# Code\n```\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n\n d = {0:-1}\n size = len(nums)\n need = sum(nums)%p\n cur = 0\n res = len(nums)\n\n\n \n for key, val in enumerate(nums):\n cur = (... | 0 | Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A ... | null |
google interview | make-sum-divisible-by-p | 0 | 1 | thanks to @lee215\n\n# Intuition\n\n\n# Code\n```\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n\n d = {0:-1}\n size = len(nums)\n need = sum(nums)%p\n cur = 0\n res = len(nums)\n\n\n \n for key, val in enumerate(nums):\n cur = (... | 0 | You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f... | Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i... |
[Python] Prefix Sum + Hashmap O(n)/O(n) | make-sum-divisible-by-p | 0 | 1 | # Complexity\n\n* Time: O(n)\n* Space: O(n)\n\nn = size of `nums`\n\n# Code\n```\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n \n S = sum(nums)\n R = S % p\n\n if R == 0:\n return 0\n\n pfxrem = 0\n rightmost_rem = {0: -1}\n an... | 0 | Given an array of positive integers `nums`, remove the **smallest** subarray (possibly **empty**) such that the **sum** of the remaining elements is divisible by `p`. It is **not** allowed to remove the whole array.
Return _the length of the smallest subarray that you need to remove, or_ `-1` _if it's impossible_.
A ... | null |
[Python] Prefix Sum + Hashmap O(n)/O(n) | make-sum-divisible-by-p | 0 | 1 | # Complexity\n\n* Time: O(n)\n* Space: O(n)\n\nn = size of `nums`\n\n# Code\n```\nclass Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n \n S = sum(nums)\n R = S % p\n\n if R == 0:\n return 0\n\n pfxrem = 0\n rightmost_rem = {0: -1}\n an... | 0 | You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`.
You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f... | Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i... |
SOLID Principles | 100% Memory | Commented and Explained | strange-printer-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is actually similar to whether or not we have edge collisions in polygon coloring for computer graphics. As such, we take the idea of a color bounding box as a polygon of that color, where we are trying to see if we can get to the ba... | 1 | There is a strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
SOLID Principles | 100% Memory | Commented and Explained | strange-printer-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is actually similar to whether or not we have edge collisions in polygon coloring for computer graphics. As such, we take the idea of a color bounding box as a polygon of that color, where we are trying to see if we can get to the ba... | 1 | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
python graph + topological sort cycle detection | strange-printer-ii | 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 strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
python graph + topological sort cycle detection | strange-printer-ii | 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 **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
Python - rectangle overlap graph | strange-printer-ii | 0 | 1 | # Intuition\nKey observation, filling color is on full rectangle only, if one rectangle has other color within its borders, then it has to be painted before that color. This way it can be constructed precedence graph, in another words problem becomes detecting is there cycle or not. More precisely for problem to be sol... | 0 | There is a strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
Python - rectangle overlap graph | strange-printer-ii | 0 | 1 | # Intuition\nKey observation, filling color is on full rectangle only, if one rectangle has other color within its borders, then it has to be painted before that color. This way it can be constructed precedence graph, in another words problem becomes detecting is there cycle or not. More precisely for problem to be sol... | 0 | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
Python || Clean and Simple Solution using Topological Sorting | strange-printer-ii | 0 | 1 | ```\nfrom collections import defaultdict\nfrom graphlib import CycleError, TopologicalSorter\nfrom itertools import product\n\nMAX_COLOR = 60\n\n\nclass Solution:\n def isPrintable(self, M: list[list[int]]) -> bool:\n g = self.create_graph(M)\n\n try:\n TopologicalSorter(g).prepare()\n ... | 0 | There is a strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
Python || Clean and Simple Solution using Topological Sorting | strange-printer-ii | 0 | 1 | ```\nfrom collections import defaultdict\nfrom graphlib import CycleError, TopologicalSorter\nfrom itertools import product\n\nMAX_COLOR = 60\n\n\nclass Solution:\n def isPrintable(self, M: list[list[int]]) -> bool:\n g = self.create_graph(M)\n\n try:\n TopologicalSorter(g).prepare()\n ... | 0 | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
Python (Simple DFS) | strange-printer-ii | 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 strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
Python (Simple DFS) | strange-printer-ii | 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 **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
Python 3 | Very fast (beats 100 %) | Implicit directed graph | Search cycle with DFS | strange-printer-ii | 0 | 1 | \n\n# Complexity\n- Time complexity:\n$$O(n*m)$$ to find limits of rectangle of each color.\n$$O(n*m*c)$$ to construct the graph ; $$c$$ is the number of colors.\n$$O(c)$... | 0 | There is a strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
Python 3 | Very fast (beats 100 %) | Implicit directed graph | Search cycle with DFS | strange-printer-ii | 0 | 1 | \n\n# Complexity\n- Time complexity:\n$$O(n*m)$$ to find limits of rectangle of each color.\n$$O(n*m*c)$$ to construct the graph ; $$c$$ is the number of colors.\n$$O(c)$... | 0 | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
[Python] Construct Graph and Detect Cycle in the Directed Graph | Easy implementation | strange-printer-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n minRow, maxRow = defaultdict(lambda: math.inf), defaultdict(lambda:-math.inf)\n minCol, maxCol = defaultdict(lambda: math.inf), defaultdict(lambda:-math.inf)\n\n # Part 1 - Finding left/right/top/botto... | 0 | There is a strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
[Python] Construct Graph and Detect Cycle in the Directed Graph | Easy implementation | strange-printer-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n minRow, maxRow = defaultdict(lambda: math.inf), defaultdict(lambda:-math.inf)\n minCol, maxCol = defaultdict(lambda: math.inf), defaultdict(lambda:-math.inf)\n\n # Part 1 - Finding left/right/top/botto... | 0 | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
Python | Keep unpaint untill canvas is blank | strange-printer-ii | 0 | 1 | # Code\r\n``` python\r\nclass Solution:\r\n def isPrintable(self, targetGrid):\r\n R, C, limits = len(mat), len(mat[0]), dict()\r\n\r\n for i in range(R): # using corners of color dict as color\'s set as well\r\n for j in range(C):\r\n color = mat[i][j]\r\n if ... | 0 | There is a strange printer with the following two special requirements:
* On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.
* Once the printer has used a color for the above operation, **the same color cannot be ... | null |
Python | Keep unpaint untill canvas is blank | strange-printer-ii | 0 | 1 | # Code\r\n``` python\r\nclass Solution:\r\n def isPrintable(self, targetGrid):\r\n R, C, limits = len(mat), len(mat[0]), dict()\r\n\r\n for i in range(R): # using corners of color dict as color\'s set as well\r\n for j in range(C):\r\n color = mat[i][j]\r\n if ... | 0 | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*... | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? |
Python solution | rearrange-spaces-between-words | 0 | 1 | ```\nclass Solution:\n def reorderSpaces(self, text: str) -> str:\n words: list[str] = findall(r"(\\w+)", text)\n len_words, spaces = len(words), text.count(" ")\n reorder_text: str = ""\n\n if len_words == 1: return words[0] + " " * spaces\n\n new_spaces: int = spaces // (len_word... | 1 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
98.99% Python Straight Forward Solution | rearrange-spaces-between-words | 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)$$ --... | 2 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python - simple and elegant | rearrange-spaces-between-words | 0 | 1 | **Multiple returns**:\n```\nclass Solution(object):\n def reorderSpaces(self, text):\n word_list = text.split()\n words, spaces = len(word_list), text.count(" ")\n \n if words > 1:\n q, r = spaces//(words-1), spaces%(words-1)\n return (" " * q).join(word_list) + " " ... | 5 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python3 simple solution based on built-in functions | rearrange-spaces-between-words | 0 | 1 | class Solution:\n def reorderSpaces(self, text: str) -> str:\n \n # \n words_list = text.split()\n num_spaces = text.count(\' \')\n num_words = len(words_list)\n # \n if num_words == 1:\n return(words_list[0] + \' \' * num_spaces)\n else:\n ... | 8 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Clean solution in Python | rearrange-spaces-between-words | 0 | 1 | ```\nclass Solution:\n def reorderSpaces(self, text: str) -> str:\n spaces = sum(c.isspace() for c in text)\n if not spaces:\n return text\n words = text.split()\n if len(words) > 1:\n q, r = divmod(spaces, (len(words) - 1))\n else:\n q, r = 0, spac... | 2 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
messy but worked ~ | rearrange-spaces-between-words | 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 string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python One Line Solution O(n) | rearrange-spaces-between-words | 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$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python3 - Intuitive Approach | rearrange-spaces-between-words | 0 | 1 | # Approach\n1. We iterate through the whole text, in one pass count the number of spaces and part out individual words and add them to words list. \n\n2. We calculate the normalized space amount by dividing number of spaces by number of words (be careful, in case we have only one word we will divide by zero here).\n\n3... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Straight forward solutions | rearrange-spaces-between-words | 0 | 1 | # Code\n```\nclass Solution:\n def reorderSpaces(self, text: str) -> str:\n # bruteforce solutions\n # 37ms\n # Beats 62.02% of users with Python3\n space = text.count(" ")\n if space == 0:\n return text\n \n words = text.split()\n n = len(words)\n\n... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Simple Python code | rearrange-spaces-between-words | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Count the number of spaces\n- Calculate the number of spaces between words and at the end of the line\n- Join the words with spaces and add trailing spaces\n# Complexi... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Easy Python|Solution|Clear | rearrange-spaces-between-words | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def reorderSpaces(self, text: str) -> str:\n \n words = text.split()\n num_words = len(words)\n count_space = text.count(" ")\n\n if num_words <= 1 and count_space >0:\n return words[0]+" "*count_space \n elif count_space == 0:\n... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python || Easy | rearrange-spaces-between-words | 0 | 1 | # Code\n```\nclass Solution:\n def reorderSpaces(self, text: str) -> str:\n count_space = text.count(\' \')\n words = text.split()\n\n delimeter, rest = 0, count_space\n\n if len(words) > 1:\n delimeter, rest = divmod(count_space, (len(words) - 1))\n\n return (delimeter ... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python solution | rearrange-spaces-between-words | 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 string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Python Solution - Easy To Read | rearrange-spaces-between-words | 0 | 1 | \n# Code\n```\nclass Solution:\n def reorderSpaces(self, text: str) -> str:\n \n words: list = [word for word in text.split(" ") if word != ""] \n text_spaces_count: int = text.count(" ")\n \n if len(words) == 1: \n return words[0] + " " * text_spaces_count\n \n ... | 0 | You are given a string `text` of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that `text` **contains at least one word**.
Rearrange the spaces so that there is an **equal** number of spaces betwee... | null |
Economical backtracking solution, commented and explained | split-a-string-into-the-max-number-of-unique-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis optimization problem will involve backtracking. The maximum length of s is 16, so there shouldn\'t be too much of a problem with execution time, even though a more general (unlimited length) solution wouldn\'t scale well at all, appr... | 2 | Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_.
You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **uniqu... | null |
Python 3 | Backtracking, DFS, clean | Explanations | split-a-string-into-the-max-number-of-unique-substrings | 0 | 1 | ### Explanation\n- The length of `s` is only up to 16, so it won\'t hurt if we exhaustively try out all possibility\n- And intuitively backtracking + DFS is very good at doing job like this\n- Check comment for more detail, pretty standard backtracking problem\n### Implementation\n```\nclass Solution:\n def maxUniqu... | 5 | Given a string `s`, return _the maximum number of unique substrings that the given string can be split into_.
You can split string `s` into any list of **non-empty substrings**, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are **uniqu... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.