problem_title
stringlengths
3
77
python_solutions
stringlengths
81
8.45k
post_href
stringlengths
64
213
upvotes
int64
0
1.2k
question
stringlengths
0
3.6k
post_title
stringlengths
2
100
views
int64
1
60.9k
slug
stringlengths
3
77
acceptance
float64
0.14
0.91
user
stringlengths
3
26
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
number
int64
1
2.48k
remove outermost parentheses
class Solution: def removeOuterParentheses(self, S: str) -> str: stack=[] counter=0 for i in S: if i=='(': counter=counter+1 if counter==1: pass else: stack.append(i) else: counter=counter-1 if counter == 0: pass else: stack.append(i) return (''.join(stack))
https://leetcode.com/problems/remove-outermost-parentheses/discuss/1162269/Python-Simplest-Solution
5
A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings. Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings. Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s. Example 1: Input: s = "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". Example 2: Input: s = "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". Example 3: Input: s = "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "". Constraints: 1 <= s.length <= 105 s[i] is either '(' or ')'. s is a valid parentheses string.
Python Simplest Solution
164
remove-outermost-parentheses
0.802
aishwaryanathanii
Easy
16,696
1,021
sum of root to leaf binary numbers
class Solution: def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: def dfs(node, path): if not node: return 0 path = (path << 1) + node.val if not node.left and not node.right: return path return dfs(node.left, path) + dfs(node.right, path) return dfs(root, 0)
https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1681647/Python3-5-LINES-(-)-Explained
19
You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers. The test cases are generated so that the answer fits in a 32-bits integer. Example 1: Input: root = [1,0,1,0,1,0,1] Output: 22 Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 Example 2: Input: root = [0] Output: 0 Constraints: The number of nodes in the tree is in the range [1, 1000]. Node.val is 0 or 1.
✔️ [Python3] 5-LINES ☜ ( ͡❛ 👅 ͡❛), Explained
876
sum-of-root-to-leaf-binary-numbers
0.737
artod
Easy
16,731
1,022
camelcase matching
class Solution: def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: def match(p, q): i = 0 for j, c in enumerate(q): if i < len(p) and p[i] == q[j]: i += 1 elif q[j].isupper(): return False return i == len(p) return [True if match(pattern, s) else False for s in queries]
https://leetcode.com/problems/camelcase-matching/discuss/488216/Python-Two-Pointer-Memory-usage-less-than-100
8
Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters. Example 1: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB" Output: [true,false,true,true,false] Explanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar". "FootBall" can be generated like this "F" + "oot" + "B" + "all". "FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer". Example 2: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa" Output: [true,false,true,false,false] Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r". "FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll". Example 3: Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT" Output: [false,true,false,false,false] Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est". Constraints: 1 <= pattern.length, queries.length <= 100 1 <= queries[i].length <= 100 queries[i] and pattern consist of English letters.
Python - Two Pointer - Memory usage less than 100%
638
camelcase-matching
0.602
mmbhatk
Medium
16,756
1,023
video stitching
class Solution: def videoStitching(self, clips: List[List[int]], T: int) -> int: end, end2, res = -1, 0, 0 for i, j in sorted(clips): if end2 >= T or i > end2: break elif end < i <= end2: res, end = res + 1, end2 end2 = max(end2, j) return res if end2 >= T else -1
https://leetcode.com/problems/video-stitching/discuss/2773366/greedy
0
You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths. Each video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi. We can cut these clips into segments freely. For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7]. Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1. Example 1: Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 Output: 3 Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10]. Example 2: Input: clips = [[0,1],[1,2]], time = 5 Output: -1 Explanation: We cannot cover [0,5] with only [0,1] and [1,2]. Example 3: Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9 Output: 3 Explanation: We can take clips [0,4], [4,7], and [6,9]. Constraints: 1 <= clips.length <= 100 0 <= starti <= endi <= 100 1 <= time <= 100
greedy
1
video-stitching
0.505
yhu415
Medium
16,767
1,024
divisor game
class Solution: def divisorGame(self, N: int) -> bool: return N % 2 == 0 - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/divisor-game/discuss/382233/Solution-in-Python-3-(With-Detailed-Proof)
150
Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < n and n % x == 0. Replacing the number n on the chalkboard with n - x. Also, if a player cannot make a move, they lose the game. Return true if and only if Alice wins the game, assuming both players play optimally. Example 1: Input: n = 2 Output: true Explanation: Alice chooses 1, and Bob has no more moves. Example 2: Input: n = 3 Output: false Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves. Constraints: 1 <= n <= 1000
Solution in Python 3 (With Detailed Proof)
6,100
divisor-game
0.672
junaidmansuri
Easy
16,773
1,025
maximum difference between node and ancestor
class Solution: def maxAncestorDiff(self, root: Optional[TreeNode]) -> int: def dfs(root, mn, mx): # Base Case: If we reach None, just return 0 in order not to affect the result if not root: return 0 # The best difference we can do using the current node can be found: res = max(abs(root.val - mn), abs(root.val - mx)) # Recompute the new minimum and maximum taking into account the current node mn, mx = min(mn, root.val), max(mx, root.val) # Recurse left and right using the newly computated minimum and maximum return max(res, dfs(root.left, mn, mx), dfs(root.right, mn, mx)) # Initialize minimum `mn` and maximum `mx` equals value of given root return dfs(root, root.val, root.val)
https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1657537/Python3-Simplifying-Tree-to-Arrays-oror-Detailed-Explanation-%2B-Intuition-oror-Preorder-DFS
10
Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b. A node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b. Example 1: Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] Output: 7 Explanation: We have various ancestor-node differences, some of which are given below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7. Example 2: Input: root = [1,null,2,null,0,3] Output: 3 Constraints: The number of nodes in the tree is in the range [2, 5000]. 0 <= Node.val <= 105
✅ [Python3] Simplifying Tree to Arrays || Detailed Explanation + Intuition || Preorder DFS
509
maximum-difference-between-node-and-ancestor
0.734
PatrickOweijane
Medium
16,791
1,026
longest arithmetic subsequence
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = {} for i, a2 in enumerate(A[1:], start=1): for j, a1 in enumerate(A[:i]): d = a2 - a1 if (j, d) in dp: dp[i, d] = dp[j, d] + 1 else: dp[i, d] = 2 return max(dp.values())
https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/415281/Python-DP-solution
53
Given an array nums of integers, return the length of the longest arithmetic subsequence in nums. Note that: A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1). Example 1: Input: nums = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: nums = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: nums = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5]. Constraints: 2 <= nums.length <= 1000 0 <= nums[i] <= 500
Python DP solution
5,200
longest-arithmetic-subsequence
0.47
yasufumy
Medium
16,805
1,027
recover a tree from preorder traversal
class Solution: def recoverFromPreorder(self, S: str) -> TreeNode: stack = [] depth, val = 0, "" for i, x in enumerate(S): if x == "-": depth += 1 val = "" else: val += S[i] if i+1 == len(S) or S[i+1] == "-": node = TreeNode(int(val)) while len(stack) > depth: stack.pop() if stack: if not stack[-1].left: stack[-1].left = node else: stack[-1].right = node stack.append(node) depth = 0 return stack[0]
https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/discuss/1179506/Python3-stack
3
We run a preorder depth-first search (DFS) on the root of a binary tree. At each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0. If a node has only one child, that child is guaranteed to be the left child. Given the output traversal of this traversal, recover the tree and return its root. Example 1: Input: traversal = "1-2--3--4-5--6--7" Output: [1,2,5,3,4,6,7] Example 2: Input: traversal = "1-2--3---4-5--6---7" Output: [1,2,5,3,null,6,null,4,null,7] Example 3: Input: traversal = "1-401--349---90--88" Output: [1,401,null,349,88,90] Constraints: The number of nodes in the original tree is in the range [1, 1000]. 1 <= Node.val <= 109
[Python3] stack
116
recover-a-tree-from-preorder-traversal
0.73
ye15
Hard
16,816
1,028
two city scheduling
class Solution(object): def twoCitySchedCost(self, costs): """ :type costs: List[List[int]] :rtype: int """ a = sorted(costs, key=lambda x: x[0]-x[1]) Sa = 0 Sb = 0 for i in range(len(a)//2): Sa += a[i][0] for i in range(len(a)//2, len(a)): Sb += a[i][1] return Sa + Sb
https://leetcode.com/problems/two-city-scheduling/discuss/297143/Python-faster-than-93-28-ms
17
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti. Return the minimum cost to fly every person to a city such that exactly n people arrive in each city. Example 1: Input: costs = [[10,20],[30,200],[400,50],[30,20]] Output: 110 Explanation: The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. Example 2: Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] Output: 1859 Example 3: Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]] Output: 3086 Constraints: 2 * n == costs.length 2 <= costs.length <= 100 costs.length is even. 1 <= aCosti, bCosti <= 1000
Python - faster than 93%, 28 ms
1,900
two-city-scheduling
0.648
il_buono
Medium
16,819
1,029
matrix cells in distance order
class Solution: def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]: d = {} for i in range(R): for j in range(C): d[(i,j)] = d.get((i,j),0) + abs(r0-i) + abs(c0-j) return [list(i) for i,j in sorted(d.items(), key = lambda x : x[1])]
https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1202122/Python3-simple-solution-using-dictionary
3
You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition. The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. Example 1: Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 Output: [[0,0],[0,1]] Explanation: The distances from (0, 0) to other cells are: [0,1] Example 2: Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Explanation: The distances from (0, 1) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. Example 3: Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2 Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3] There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]. Constraints: 1 <= rows, cols <= 100 0 <= rCenter < rows 0 <= cCenter < cols
Python3 simple solution using dictionary
95
matrix-cells-in-distance-order
0.693
EklavyaJoshi
Easy
16,855
1,030
maximum sum of two non overlapping subarrays
class Solution: def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int: prefix = [0] for x in A: prefix.append(prefix[-1] + x) # prefix sum w/ leading 0 ans = lmx = mmx = -inf for i in range(M+L, len(A)+1): lmx = max(lmx, prefix[i-M] - prefix[i-L-M]) mmx = max(mmx, prefix[i-L] - prefix[i-L-M]) ans = max(ans, lmx + prefix[i] - prefix[i-M], mmx + prefix[i] - prefix[i-L]) return ans
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/1012572/Python3-dp-(prefix-sum)
3
Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen. The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping. A subarray is a contiguous part of an array. Example 1: Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2 Output: 20 Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2. Example 2: Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2 Output: 29 Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2. Example 3: Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3 Output: 31 Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3. Constraints: 1 <= firstLen, secondLen <= 1000 2 <= firstLen + secondLen <= 1000 firstLen + secondLen <= nums.length <= 1000 0 <= nums[i] <= 1000
[Python3] dp (prefix sum)
294
maximum-sum-of-two-non-overlapping-subarrays
0.595
ye15
Medium
16,869
1,031
moving stones until consecutive
class Solution: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: x, y, z = sorted([a, b, c]) if x + 1 == y == z - 1: min_steps = 0 elif y - x > 2 and z - y > 2: min_steps = 2 else: min_steps = 1 max_steps = z - x - 2 return [min_steps, max_steps]
https://leetcode.com/problems/moving-stones-until-consecutive/discuss/283466/Clean-Python-beats-100
29
There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones. In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play. Example 1: Input: a = 1, b = 2, c = 5 Output: [1,2] Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3. Example 2: Input: a = 4, b = 3, c = 2 Output: [0,0] Explanation: We cannot make any moves. Example 3: Input: a = 3, b = 5, c = 1 Output: [1,2] Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4. Constraints: 1 <= a, b, c <= 100 a, b, and c have different values.
Clean Python, beats 100%
1,100
moving-stones-until-consecutive
0.457
aquafie
Medium
16,877
1,033
coloring a border
class Solution: def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]: rows, cols = len(grid), len(grid[0]) border_color = grid[row][col] border = [] # Check if a node is a border node or not def is_border(r, c): if r == 0 or r == rows - 1 or c == 0 or c == cols - 1: return True for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]: nr, nc = r + dr, c + dc if grid[nr][nc] != border_color: return True return False def dfs(r, c): if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color: return visited.add((r, c)) if is_border(r, c): border.append((r, c)) dfs(r + 1, c) dfs(r - 1, c) dfs(r, c + 1) dfs(r, c - 1) visited = set() dfs(row, col) for r, c in border: grid[r][c] = color return grid
https://leetcode.com/problems/coloring-a-border/discuss/2329163/Python-DFS-and-Border-Co-ordinates
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 are called adjacent if they are next to each other in any of the 4 directions. Two squares belong to the same connected component if they have the same color and they are adjacent. The border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column). You should color the border of the connected component that contains the square grid[row][col] with color. Return the final grid. Example 1: Input: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3 Output: [[3,3],[3,2]] Example 2: Input: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3 Output: [[1,3,3],[2,3,3]] Example 3: Input: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2 Output: [[2,2,2],[2,1,2],[2,2,2]] Constraints: m == grid.length n == grid[i].length 1 <= m, n <= 50 1 <= grid[i][j], color <= 1000 0 <= row < m 0 <= col < n
[Python] DFS and Border Co-ordinates
47
coloring-a-border
0.489
tejeshreddy111
Medium
16,882
1,034
uncrossed lines
class Solution: def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int: e1=len(nums1) e2=len(nums2) @lru_cache(None,None) def dfs(s1,s2): best=-float('inf') if s1>=e1 or s2>=e2: return 0 temp=[] op1=0 #finding element in array2 which is equal to element in array1 from where we want to draw line for idx in range(s2,e2): if nums2[idx]==nums1[s1]: temp.append(idx) #drawing line to all those element and checking which gives maximum value for j in temp: op1=1+dfs(s1+1,j+1) best=max(op1,best) #choosing to not draw line from current element of array1 op2=dfs(s1+1,s2) #returning max of both options. return max(op2,best) return dfs(0,0)
https://leetcode.com/problems/uncrossed-lines/discuss/1502848/Python3-or-Memoization%2BRecursion
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 draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return the maximum number of connecting lines we can draw in this way. Example 1: Input: nums1 = [1,4,2], nums2 = [1,2,4] Output: 2 Explanation: We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2. Example 2: Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2] Output: 3 Example 3: Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1] Output: 2 Constraints: 1 <= nums1.length, nums2.length <= 500 1 <= nums1[i], nums2[j] <= 2000
[Python3] | Memoization+Recursion
59
uncrossed-lines
0.587
swapnilsingh421
Medium
16,890
1,035
escape a large maze
class Solution: def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool: blocked = set(map(tuple, blocked)) def fn(x, y, tx, ty): """Return True if (x, y) is not looped from (tx, ty).""" seen = {(x, y)} queue = [(x, y)] level = 0 while queue: level += 1 if level > 200: return True newq = [] for x, y in queue: if (x, y) == (tx, ty): return True for xx, yy in (x-1, y), (x, y-1), (x, y+1), (x+1, y): if 0 <= xx < 1e6 and 0 <= yy < 1e6 and (xx, yy) not in blocked and (xx, yy) not in seen: seen.add((xx, yy)) newq.append((xx, yy)) queue = newq return False return fn(*source, *target) and fn(*target, *source)
https://leetcode.com/problems/escape-a-large-maze/discuss/1292945/Python3-bfs-and-dfs
3
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 coordinates (xi, yi). Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid. Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves. Example 1: Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2] Output: false Explanation: The target square is inaccessible starting from the source square because we cannot move. We cannot move north or east because those squares are blocked. We cannot move south or west because we cannot go outside of the grid. Example 2: Input: blocked = [], source = [0,0], target = [999999,999999] Output: true Explanation: Because there are no blocked cells, it is possible to reach the target square. Constraints: 0 <= blocked.length <= 200 blocked[i].length == 2 0 <= xi, yi < 106 source.length == target.length == 2 0 <= sx, sy, tx, ty < 106 source != target It is guaranteed that source and target are not blocked.
[Python3] bfs & dfs
373
escape-a-large-maze
0.341
ye15
Hard
16,900
1,036
valid boomerang
class Solution: def isBoomerang(self, points: List[List[int]]) -> bool: x1, y1 = points[0] x2, y2 = points[1] x3, y3 = points[2] area = abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))/2 return area != 0
https://leetcode.com/problems/valid-boomerang/discuss/1985698/Python-3-Triangle-Area
9
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: true Example 2: Input: points = [[1,1],[2,2],[3,3]] Output: false Constraints: points.length == 3 points[i].length == 2 0 <= xi, yi <= 100
[Python 3] Triangle Area
679
valid-boomerang
0.374
hari19041
Easy
16,902
1,037
binary search tree to greater sum tree
class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: s = 0 def f(root): if root is None: return nonlocal s f(root.right) #print(s,root.val) s = s + root.val root.val = s f(root.left) f(root) return root
https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1270148/Recursive-approch-99.88-accuracy-Python
5
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 node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Example 2: Input: root = [0,null,1] Output: [1,null,1] Constraints: The number of nodes in the tree is in the range [1, 100]. 0 <= Node.val <= 100 All the values in the tree are unique. Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/
Recursive approch 99.88% accuracy[ Python ]
238
binary-search-tree-to-greater-sum-tree
0.854
rstudy211
Medium
16,918
1,038
minimum score triangulation of polygon
class Solution: def minScoreTriangulation(self, A: List[int]) -> int: SP, LA = [[0]*50 for i in range(50)], len(A) def MinPoly(a,b): L, m = b - a + 1, math.inf; if SP[a][b] != 0 or L < 3: return SP[a][b] for i in range(a+1,b): m = min(m, A[a]*A[i]*A[b] + MinPoly(a,i) + MinPoly(i,b)) SP[a][b] = m; return SP[a][b] return MinPoly(0,LA-1)
https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/391440/Two-Solutions-in-Python-3-(DP)-(Top-Down-and-Bottom-Up)
2
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 of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation. Return the smallest possible total score that you can achieve with some triangulation of the polygon. Example 1: Input: values = [1,2,3] Output: 6 Explanation: The polygon is already triangulated, and the score of the only triangle is 6. Example 2: Input: values = [3,7,4,5] Output: 144 Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144. The minimum score is 144. Example 3: Input: values = [1,3,1,4,1,5] Output: 13 Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13. Constraints: n == values.length 3 <= n <= 50 1 <= values[i] <= 100
Two Solutions in Python 3 (DP) (Top Down and Bottom Up)
791
minimum-score-triangulation-of-polygon
0.547
junaidmansuri
Medium
16,930
1,039
moving stones until consecutive ii
class Solution: def numMovesStonesII(self, stones: list[int]) -> list[int]: """ 1. For the higher bound, it is determined by either moving the leftmost to the right side, or by moving the rightmost to the left side: 1.1 If moving leftmost to the right side, the available moving positions are A[n - 1] - A[1] + 1 - (n - 1) = A[n - 1] - A[1] - n + 2 1.2 If moving rightmost to the left side, the available moving positions are A[n - 2] - A[0] + 1 - (n - 1) = A[n - 2] - A[0] - n + 2. 2. For the lower bound, we could use sliding window to find a window that contains the most consecutive stones (A[i] - A[i - 1] = 1): 2.1 Generally the moves we need are the same as the number of missing stones in the current window. 2.3 When the window is already consecutive and contains all the n - 1 stones, we need at least 2 steps to move the last stone into the current window. For example, 1,2,3,4,10: 2.3.1 We need to move 1 to 6 first as we are not allowed to move 10 to 5 as it will still be an endpoint stone. 2.3.2 Then we need to move 10 to 5 and now the window becomes 2,3,4,5,6. """ A, N = sorted(stones), len(stones) maxMoves = max(A[N - 1] - A[1] - N + 2, A[N - 2] - A[0] - N + 2) minMoves = N # Calculate minimum moves through sliding window. start = 0 for end in range(N): while A[end] - A[start] + 1 > N: start += 1 if end - start + 1 == N - 1 and A[end] - A[start] + 1 == N - 1: # Case: N - 1 stones with N - 1 positions. minMoves = min(minMoves, 2) else: minMoves = min(minMoves, N - (end - start + 1)) return [minMoves, maxMoves]
https://leetcode.com/problems/moving-stones-until-consecutive-ii/discuss/1488487/Python-Sliding-window-with-detailed-expalanation
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 an endpoint stone. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play. Example 1: Input: stones = [7,4,9] Output: [1,2] Explanation: We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. Example 2: Input: stones = [6,5,4,3,10] Output: [2,3] Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move. Constraints: 3 <= stones.length <= 104 1 <= stones[i] <= 109 All the values of stones are unique.
[Python] Sliding window with detailed expalanation
390
moving-stones-until-consecutive-ii
0.557
eroneko
Medium
16,936
1,040
robot bounded in circle
class Solution: def isRobotBounded(self, instructions: str) -> bool: x = y = 0 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] i = 0 while True: for do in instructions: if do == 'G': x += directions[i][0] y += directions[i][1] elif do == 'R': i = (i + 1) % 4 else: i = (i - 1) % 4 if i == 0: return x == 0 and y == 0
https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676693/Python3-Simple-4-Loops-or-O(n)-Time-or-O(1)-Space
5
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 is the negative direction of the x-axis. The robot can receive one of three instructions: "G": go straight 1 unit. "L": turn 90 degrees to the left (i.e., anti-clockwise direction). "R": turn 90 degrees to the right (i.e., clockwise direction). The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle. Example 1: Input: instructions = "GGLLGG" Output: true Explanation: The robot is initially at (0, 0) facing the north direction. "G": move one step. Position: (0, 1). Direction: North. "G": move one step. Position: (0, 2). Direction: North. "L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G": move one step. Position: (0, 1). Direction: South. "G": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. Example 2: Input: instructions = "GG" Output: false Explanation: The robot is initially at (0, 0) facing the north direction. "G": move one step. Position: (0, 1). Direction: North. "G": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. Example 3: Input: instructions = "GL" Output: true Explanation: The robot is initially at (0, 0) facing the north direction. "G": move one step. Position: (0, 1). Direction: North. "L": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G": move one step. Position: (-1, 1). Direction: West. "L": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G": move one step. Position: (-1, 0). Direction: South. "L": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G": move one step. Position: (0, 0). Direction: East. "L": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. Constraints: 1 <= instructions.length <= 100 instructions[i] is 'G', 'L' or, 'R'.
✅ [Python3] Simple 4 Loops | O(n) Time | O(1) Space
623
robot-bounded-in-circle
0.553
PatrickOweijane
Medium
16,938
1,041
flower planting with no adjacent
class Solution: def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]: G = defaultdict(list) for path in paths: G[path[0]].append(path[1]) G[path[1]].append((path[0])) colored = defaultdict() def dfs(G, V, colored): colors = [1, 2, 3, 4] for neighbour in G[V]: if neighbour in colored: if colored[neighbour] in colors: colors.remove(colored[neighbour]) colored[V] = colors[0] for V in range(1, N + 1): dfs(G, V, colored) ans = [] for V in range(len(colored)): ans.append(colored[V + 1]) return ans
https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/557619/**Python-Simple-DFS-solution-70-80-**
6
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 flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists. Example 1: Input: n = 3, paths = [[1,2],[2,3],[3,1]] Output: [1,2,3] Explanation: Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1]. Example 2: Input: n = 4, paths = [[1,2],[3,4]] Output: [1,2,1,2] Example 3: Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]] Output: [1,2,3,4] Constraints: 1 <= n <= 104 0 <= paths.length <= 2 * 104 paths[i].length == 2 1 <= xi, yi <= n xi != yi Every garden has at most 3 paths coming into or leaving it.
**Python Simple DFS solution 70 - 80 %**
846
flower-planting-with-no-adjacent
0.504
art35part2
Medium
16,965
1,042
partition array for maximum sum
class Solution: def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int: n = len(arr) dp = [0]*n # handle the first k indexes differently for j in range(k): dp[j]=max(arr[:j+1])*(j+1) # we can get rid of index i by running i times for j in range(k,n): curr = [] for m in range(k): curr.append(dp[j-m-1] + max(arr[(j-m):(j+1)]) * (m+1)) dp[j] = max(curr) return dp[-1]
https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/1621079/Python-Easy-DP-with-Visualization-and-examples
56
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 fits in a 32-bit integer. Example 1: Input: arr = [1,15,7,9,2,5,10], k = 3 Output: 84 Explanation: arr becomes [15,15,15,9,10,10,10] Example 2: Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4 Output: 83 Example 3: Input: arr = [1], k = 1 Output: 1 Constraints: 1 <= arr.length <= 500 0 <= arr[i] <= 109 1 <= k <= arr.length
[Python] Easy DP with Visualization and examples
1,300
partition-array-for-maximum-sum
0.712
sashaxx
Medium
16,972
1,043
longest duplicate substring
class Solution: def longestDupSubstring(self, s: str) -> str: length = len(s) l,r = 0, length-1 result = [] while l<r: mid = (l+r)//2 d = {} max_string = "" for i in range(length-mid): if d.get(s[i:i+mid+1],0): max_string = s[i:i+mid+1] break d[s[i:i+mid+1]] = 1 if max_string: l = mid+1 result.append(max_string) else: r = mid return max(result,key=len) if result else ""
https://leetcode.com/problems/longest-duplicate-substring/discuss/2806471/Python-Easy-or-Simple-or-Binary-Solution
0
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 = "banana" Output: "ana" Example 2: Input: s = "abcd" Output: "" Constraints: 2 <= s.length <= 3 * 104 s consists of lowercase English letters.
Python Easy | Simple | Binary Solution
2
longest-duplicate-substring
0.307
girraj_14581
Hard
16,982
1,044
last stone weight
class Solution: def lastStoneWeight(self, stones: List[int]) -> int: stones.sort() while stones: s1 = stones.pop() # the heaviest stone if not stones: # s1 is the remaining stone return s1 s2 = stones.pop() # the second-heaviest stone; s2 <= s1 if s1 > s2: # we need to insert the remaining stone (s1-s2) into the list pass # else s1 == s2; both stones are destroyed return 0 # if no more stones remain
https://leetcode.com/problems/last-stone-weight/discuss/1921241/Python-Beginner-friendly-Optimisation-Process-with-Explanation
91
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: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the weight of the last remaining stone. If there are no stones left, return 0. Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. Example 2: Input: stones = [1] Output: 1 Constraints: 1 <= stones.length <= 30 1 <= stones[i] <= 1000
[Python] Beginner-friendly Optimisation Process with Explanation
5,800
last-stone-weight
0.647
zayne-siew
Easy
16,988
1,046
remove all adjacent duplicates in string
class Solution: def removeDuplicates(self, s: str) -> str: stack=[s[0]] for i in range(1,len(s)): if(stack and stack[-1]==s[i]): stack.pop() else: stack.append(s[i]) return "".join(stack)
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/1291694/Easy-Python-Solution(89.05)
11
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. It can be proven that the answer is unique. Example 1: Input: s = "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". Example 2: Input: s = "azxxzy" Output: "ay" Constraints: 1 <= s.length <= 105 s consists of lowercase English letters.
Easy Python Solution(89.05%)
807
remove-all-adjacent-duplicates-in-string
0.703
Sneh17029
Easy
17,023
1,047
longest string chain
class Solution: def longestStrChain(self, words: List[str]) -> int: words.sort(key=len) dic = {} for i in words: dic[ i ] = 1 for j in range(len(i)): # creating words by deleting a letter successor = i[:j] + i[j+1:] if successor in dic: dic[ i ] = max (dic[i], 1 + dic[successor]) res = max(dic.values()) return res
https://leetcode.com/problems/longest-string-chain/discuss/2152864/PYTHON-oror-EXPLAINED-oror
27
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 predecessor of "abac", while "cba" is not a predecessor of "bcad". A word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1. Return the length of the longest possible word chain with words chosen from the given list of words. Example 1: Input: words = ["a","b","ba","bca","bda","bdca"] Output: 4 Explanation: One of the longest word chains is ["a","ba","bda","bdca"]. Example 2: Input: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"] Output: 5 Explanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"]. Example 3: Input: words = ["abcd","dbqca"] Output: 1 Explanation: The trivial word chain ["abcd"] is one of the longest word chains. ["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed. Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 16 words[i] only consists of lowercase English letters.
✔️ PYTHON || EXPLAINED || ;]
1,500
longest-string-chain
0.591
karan_8082
Medium
17,083
1,048
last stone weight ii
class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: @lru_cache(None) def fn(i, v): """Return minimum weight of stones[i:] given existing weight.""" if i == len(stones): return abs(v) return min(fn(i+1, v - stones[i]), fn(i+1, v + stones[i])) return fn(0, 0)
https://leetcode.com/problems/last-stone-weight-ii/discuss/1013873/Python3-top-down-dp
2
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 any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone. If there are no stones left, return 0. Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then, we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then, we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then, we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value. Example 2: Input: stones = [31,26,33,21,40] Output: 5 Constraints: 1 <= stones.length <= 30 1 <= stones[i] <= 100
[Python3] top-down dp
153
last-stone-weight-ii
0.526
ye15
Medium
17,126
1,049
height checker
class Solution: def heightChecker(self, heights: List[int]) -> int: max_val = max(heights) # Create frequency table freq = [0] * (max_val + 1) for num in heights: freq[num] += 1 for num in range(1, len(freq)): freq[num] += freq[num-1] # Create places table places = [0] * len(heights) for num in heights: places[freq[num]-1] = num freq[num] -= 1 return sum([a!=b for a, b in zip(heights, places)])
https://leetcode.com/problems/height-checker/discuss/429670/Python-3-O(n)-Faster-than-100-Memory-usage-less-than-100
24
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 array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). Return the number of indices where heights[i] != expected[i]. Example 1: Input: heights = [1,1,4,2,1,3] Output: 3 Explanation: heights: [1,1,4,2,1,3] expected: [1,1,1,2,3,4] Indices 2, 4, and 5 do not match. Example 2: Input: heights = [5,1,2,3,4] Output: 5 Explanation: heights: [5,1,2,3,4] expected: [1,2,3,4,5] All indices do not match. Example 3: Input: heights = [1,2,3,4,5] Output: 0 Explanation: heights: [1,2,3,4,5] expected: [1,2,3,4,5] All indices match. Constraints: 1 <= heights.length <= 100 1 <= heights[i] <= 100
Python 3 - O(n) - Faster than 100%, Memory usage less than 100%
4,800
height-checker
0.751
mmbhatk
Easy
17,132
1,051
grumpy bookstore owner
class Solution: def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int: # a sliding window approach currsum = 0 # first store the sum as if the owner has no super power for i in range(len(grumpy)): if not grumpy[i]: currsum += customers[i] # now assuming he has the power, take the first window # and add to the previous sum for i in range(X): if grumpy[i]: currsum += customers[i] maxsum = currsum # Now the sliding window starts # i and j are the two opposite ends of the window i = 0 j = X while j < len(customers): if grumpy[j]: currsum += customers[j] if grumpy[i]: currsum -= customers[i] # we subtract above as the window has already passed over that customer if currsum > maxsum: maxsum = currsum i += 1 j += 1 return maxsum
https://leetcode.com/problems/grumpy-bookstore-owner/discuss/441491/Python-(97)-Easy-to-understand-Sliding-Window-with-comments
3
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 the end of that minute. On some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise. When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied. The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once. Return the maximum number of customers that can be satisfied throughout the day. Example 1: Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3 Output: 16 Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16. Example 2: Input: customers = [1], grumpy = [0], minutes = 1 Output: 1 Constraints: n == customers.length == grumpy.length 1 <= minutes <= n <= 2 * 104 0 <= customers[i] <= 1000 grumpy[i] is either 0 or 1.
Python (97%) - Easy to understand Sliding Window with comments
315
grumpy-bookstore-owner
0.571
vdhyani96
Medium
17,167
1,052
previous permutation with one swap
class Solution: def prevPermOpt1(self, nums: List[int]) -> List[int]: n = len(nums)-1 left = n // find first non-decreasing number while left >= 0 and nums[left] >= nums[left-1]: left -= 1 // if this hits, it means we have the smallest possible perm if left <= 0: return nums // the while loop above lands us at +1, so k is the actual value k = left - 1 // find the largest number that's smaller than k // while skipping duplicates right = n while right >= left: if nums[right] < nums[k] and nums[right] != nums[right-1]: nums[k], nums[right] = nums[right], nums[k] return nums right -= 1 return nums
https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/1646525/python-O(n)-time-O(1)-space-with-explanation
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] and arr[j] Example 1: Input: arr = [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1. Example 2: Input: arr = [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation. Example 3: Input: arr = [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7. Constraints: 1 <= arr.length <= 104 1 <= arr[i] <= 104
python O(n) time, O(1) space with explanation
322
previous-permutation-with-one-swap
0.508
uzumaki01
Medium
17,182
1,053
distant barcodes
class Solution: def rearrangeBarcodes(self, B: List[int]) -> List[int]: L, A, i = len(B), [0]*len(B), 0 for k,v in collections.Counter(B).most_common(): for _ in range(v): A[i], i = k, i + 2 if i >= L: i = 1 return A class Solution: def rearrangeBarcodes(self, B: List[int]) -> List[int]: L, C = len(B), collections.Counter(B) B.sort(key = lambda x: (C[x],x)) B[1::2], B[::2] = B[:L//2], B[L//2:] return B - Junaid Mansuri
https://leetcode.com/problems/distant-barcodes/discuss/411386/Two-Solutions-in-Python-3-(six-lines)-(beats-~95)
5
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: Input: barcodes = [1,1,1,1,2,2,3,3] Output: [1,3,1,3,1,2,1,2] Constraints: 1 <= barcodes.length <= 10000 1 <= barcodes[i] <= 10000
Two Solutions in Python 3 (six lines) (beats ~95%)
755
distant-barcodes
0.457
junaidmansuri
Medium
17,186
1,054
greatest common divisor of strings
class Solution: def gcdOfStrings(self, s1: str, s2: str) -> str: return s1[:math.gcd(len(s1), len(s2))] if s1 + s2 == s2 + s1 else ''
https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/860984/Python-3-or-GCD-1-liner-or-Explanation
61
For two strings s and t, we say "t divides s" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB" Example 3: Input: str1 = "LEET", str2 = "CODE" Output: "" Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of English uppercase letters.
Python 3 | GCD 1-liner | Explanation
3,500
greatest-common-divisor-of-strings
0.511
idontknoooo
Easy
17,191
1,071
flip columns for maximum number of equal rows
class Solution: def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int: dic = defaultdict(int) for row in matrix: local=[] for c in row: local.append(c^row[0]) dic[tuple(local)]+=1 return max(dic.values())
https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1440662/97-faster-oror-Well-Explained-with-example-oror-Easy-Approach
1
You are given an m x n binary matrix matrix. You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa). Return the maximum number of rows that have all values equal after some number of flips. Example 1: Input: matrix = [[0,1],[1,1]] Output: 1 Explanation: After flipping no values, 1 row has all values equal. Example 2: Input: matrix = [[0,1],[1,0]] Output: 2 Explanation: After flipping values in the first column, both rows have equal values. Example 3: Input: matrix = [[0,0,0],[0,0,1],[1,1,0]] Output: 2 Explanation: After flipping values in the first two columns, the last two rows have equal values. Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 300 matrix[i][j] is either 0 or 1.
🐍 97% faster || Well-Explained with example || Easy-Approach 📌📌
199
flip-columns-for-maximum-number-of-equal-rows
0.63
abhi9Rai
Medium
17,204
1,072
adding two negabinary numbers
class Solution: def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]: ans = list() m, n = len(arr1), len(arr2) i, j = m-1, n-1 def add(a, b): # A helper function to add -2 based numbers if a == 1 and b == 1: cur, carry = 0, -1 elif (a == -1 and b == 0) or (a == 0 and b == -1): cur = carry = 1 else: cur, carry = a+b, 0 return cur, carry # Return current value and carry carry = 0 while i >= 0 or j >= 0: # Two pointers from right side cur, carry_1, carry_2 = carry, 0, 0 if i >= 0: cur, carry_1 = add(cur, arr1[i]) if j >= 0: cur, carry_2 = add(cur, arr2[j]) carry = carry_1 + carry_2 ans.append(cur) i, j = i-1, j-1 ans = [1,1] + ans[::-1] if carry == -1 else ans[::-1] # Add [1, 1] if there is a carry -1 leftover for i, v in enumerate(ans): # Remove leading zero and return if v == 1: return ans[i:] else: return [0]
https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/1384126/Python-3-or-Math-Two-Pointers-or-Explanation
2
Given two numbers arr1 and arr2 in base -2, return the result of adding them together. Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1. Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros. Example 1: Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] Output: [1,0,0,0,0] Explanation: arr1 represents 11, arr2 represents 5, the output represents 16. Example 2: Input: arr1 = [0], arr2 = [0] Output: [0] Example 3: Input: arr1 = [0], arr2 = [1] Output: [1] Constraints: 1 <= arr1.length, arr2.length <= 1000 arr1[i] and arr2[i] are 0 or 1 arr1 and arr2 have no leading zeros
Python 3 | Math, Two Pointers | Explanation
558
adding-two-negabinary-numbers
0.364
idontknoooo
Medium
17,210
1,073
number of submatrices that sum to target
class Solution: def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int: # find the rows and columns of the matrix n,m = len(matrix) , len(matrix[0]) # find the prefix sum for each row for i in range(n): for j in range(1,m): matrix[i][j] += matrix[i][j-1] ans = 0 # fix the left boundary of the column for start in range(m): # fix the right boundary of the column for end in range(start,m): # a dictionary to map data d = defaultdict(lambda:0) d[0] = 1 summ = 0 # now we do check at each row for i in range(n): curr = matrix[i][end] if start > 0: curr -= matrix[i][start-1] summ += curr ans += d[summ - target] d[summ] += 1 return ans
https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2118388/or-PYTHON-SOL-or-EASY-or-EXPLAINED-or-VERY-SIMPLE-or-COMMENTED-or
1
Given a matrix and a target, return the number of non-empty submatrices that sum to target. A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2. Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'. Example 1: Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0 Output: 4 Explanation: The four 1x1 submatrices that only contain 0. Example 2: Input: matrix = [[1,-1],[-1,1]], target = 0 Output: 5 Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix. Example 3: Input: matrix = [[904]], target = 0 Output: 0 Constraints: 1 <= matrix.length <= 100 1 <= matrix[0].length <= 100 -1000 <= matrix[i][j] <= 1000 -10^8 <= target <= 10^8
| PYTHON SOL | EASY | EXPLAINED | VERY SIMPLE | COMMENTED |
203
number-of-submatrices-that-sum-to-target
0.698
reaper_27
Hard
17,215
1,074
occurrences after bigram
class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: ans, stack = [], [] for w in text.split(): if len(stack) > 1 and stack[-2] == first and stack[-1] == second: ans.append(w) stack.append(w) return ans
https://leetcode.com/problems/occurrences-after-bigram/discuss/1443810/Using-stack-for-words-93-speed
2
Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. Return an array of all the words third for each occurrence of "first second third". Example 1: Input: text = "alice is a good girl she is a good student", first = "a", second = "good" Output: ["girl","student"] Example 2: Input: text = "we will we will rock you", first = "we", second = "will" Output: ["we","rock"] Constraints: 1 <= text.length <= 1000 text consists of lowercase English letters and spaces. All the words in text a separated by a single space. 1 <= first.length, second.length <= 10 first and second consist of lowercase English letters.
Using stack for words, 93% speed
99
occurrences-after-bigram
0.638
EvgenySH
Easy
17,223
1,078
letter tile possibilities
class Solution: def numTilePossibilities(self, tiles: str) -> int: record = [0] * 26 for tile in tiles: record[ord(tile)-ord('A')] += 1 def dfs(record): s = 0 for i in range(26): if not record[i]: continue record[i] -= 1 s += dfs(record) + 1 record[i] += 1 return s return dfs(record)
https://leetcode.com/problems/letter-tile-possibilities/discuss/774815/Python-3-Backtracking-(no-set-no-itertools-simple-DFS-count)-with-explanation
21
You have n tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles. Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1 Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
Python 3 Backtracking (no set, no itertools, simple DFS count) with explanation
1,500
letter-tile-possibilities
0.761
idontknoooo
Medium
17,240
1,079
insufficient nodes in root to leaf paths
class Solution: def sufficientSubset(self, root: TreeNode, limit: int, pathSum = 0) -> TreeNode: if not root: return None if not root.left and not root.right: if pathSum + root.val < limit: return None return root root.left = self.sufficientSubset(root.left, limit, pathSum + root.val) root.right = self.sufficientSubset(root.right, limit, pathSum + root.val) if not root.left and not root.right: return None return root
https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/1350913/Simple-Python-Solution-or-O(N)-or-DFS
2
Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree. A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit. A leaf is a node with no children. Example 1: Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1 Output: [1,2,3,4,null,null,7,8,9,null,14] Example 2: Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22 Output: [5,4,8,11,null,17,4,7,null,null,null,5] Example 3: Input: root = [1,2,-3,-5,null,4,null], limit = -1 Output: [1,null,-3,4] Constraints: The number of nodes in the tree is in the range [1, 5000]. -105 <= Node.val <= 105 -109 <= limit <= 109
Simple Python Solution | O(N) | DFS
192
insufficient-nodes-in-root-to-leaf-paths
0.53
Astomak
Medium
17,256
1,080
smallest subsequence of distinct characters
class Solution: def smallestSubsequence(self, s: str) -> str: loc = {x: i for i, x in enumerate(s)} stack = [] for i, x in enumerate(s): if x not in stack: while stack and x < stack[-1] and i < loc[stack[-1]]: stack.pop() stack.append(x) return "".join(stack)
https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/894588/Python3-stack-O(N)
2
Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once. Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 <= s.length <= 1000 s consists of lowercase English letters. Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/
[Python3] stack O(N)
246
smallest-subsequence-of-distinct-characters
0.575
ye15
Medium
17,262
1,081
duplicate zeros
class Solution: def duplicateZeros(self, arr: List[int]) -> None: i = 0 n = len(arr) while(i<n): if arr[i]==0: arr.pop() arr.insert(i,0) i+=1 i+=1
https://leetcode.com/problems/duplicate-zeros/discuss/408059/Python-Simple-Solution
19
Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. Example 1: Input: arr = [1,0,2,3,0,4,5,0] Output: [1,0,0,2,3,0,0,4] Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] Example 2: Input: arr = [1,2,3] Output: [1,2,3] Explanation: After calling your function, the input array is modified to: [1,2,3] Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 9
Python Simple Solution
3,100
duplicate-zeros
0.515
saffi
Easy
17,271
1,089
largest values from labels
class Solution: def largestValsFromLabels(self, values: List[int], labels: List[int], num_wanted: int, use_limit: int) -> int: ans = 0 freq = {} for value, label in sorted(zip(values, labels), reverse=True): if freq.get(label, 0) < use_limit: ans += value num_wanted -= 1 if not num_wanted: break freq[label] = 1 + freq.get(label, 0) return ans
https://leetcode.com/problems/largest-values-from-labels/discuss/1025001/Python3-greedy-O(NlogN)
2
There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit. Choose a subset s of the n elements such that: The size of the subset s is less than or equal to numWanted. There are at most useLimit items with the same label in s. The score of a subset is the sum of the values in the subset. Return the maximum score of a subset s. Example 1: Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1 Output: 9 Explanation: The subset chosen is the first, third, and fifth items. Example 2: Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2 Output: 12 Explanation: The subset chosen is the first, second, and third items. Example 3: Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1 Output: 16 Explanation: The subset chosen is the first and fourth items. Constraints: n == values.length == labels.length 1 <= n <= 2 * 104 0 <= values[i], labels[i] <= 2 * 104 1 <= numWanted, useLimit <= n
[Python3] greedy O(NlogN)
161
largest-values-from-labels
0.609
ye15
Medium
17,321
1,090
shortest path in binary matrix
class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: # check if source and target are not clear cells if grid[0][0] != 0 or grid[-1][-1] != 0: return -1 N = len(grid) # offsets required for all 8 directions offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] q = deque() q.append((0,0)) # starting point visited = {(0, 0)} # finds unvisited clear cells using 8 offsets def get_neighbours(x,y): for x_offset, y_offset in offsets: new_row = x + x_offset new_col = y + y_offset if 0 <= new_row < N and 0 <= new_col < N and not grid[new_row][new_col] and (new_row, new_col) not in visited: yield (new_row, new_col) current_distance = 1 # start with one clear cell # standard iterative BFS traversal while q: length = len(q) # loop through all the cells at the same distance for _ in range(length): row, col = q.popleft() if row == N-1 and col==N-1: # reached target return current_distance # loop though all valid neignbours for p in get_neighbours(row, col): visited.add(p) q.append(p) current_distance+=1 # update the level or distance from source return -1
https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2043228/Python-Simple-BFS-with-Explanation
15
Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that: All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path. Example 1: Input: grid = [[0,1],[1,0]] Output: 2 Example 2: Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Example 3: Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1 Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
✅ Python Simple BFS with Explanation
1,800
shortest-path-in-binary-matrix
0.445
constantine786
Medium
17,329
1,091
shortest common supersequence
class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: n,m = len(str1),len(str2) dp = [[0 for j in range(m+1)]for i in range(n+1)] for i in range(1,n+1): for j in range(1,m+1): if str1[i-1] == str2[j-1]: dp[i][j] = 1+dp[i-1][j-1] else: dp[i][j] = max(dp[i-1][j],dp[i][j-1]) i,j = n,m ans = "" while(i>0 and j>0): if str1[i-1] == str2[j-1]: ans += str1[i-1] i -= 1 j -= 1 else: if(dp[i-1][j] > dp[i][j-1]): ans += str1[i-1] i -= 1 else: ans += str2[j-1] j -= 1 while(i>0): ans += str1[i-1] i -= 1 while(j>0): ans += str2[j-1] j -= 1 return ans[::-1]
https://leetcode.com/problems/shortest-common-supersequence/discuss/786544/Simple-Python-Accepted-Solution-using-LCS-implementation-faster-than-83-python-users
7
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s. Example 1: Input: str1 = "abac", str2 = "cab" Output: "cabac" Explanation: str1 = "abac" is a subsequence of "cabac" because we can delete the first "c". str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac". The answer provided is the shortest such string that satisfies these properties. Example 2: Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa" Output: "aaaaaaaa" Constraints: 1 <= str1.length, str2.length <= 1000 str1 and str2 consist of lowercase English letters.
Simple Python Accepted Solution using LCS implementation faster than 83% python users
323
shortest-common-supersequence
0.578
theflash007
Hard
17,363
1,092
statistics from a large sample
class Solution: def sampleStats(self, count: List[int]) -> List[float]: return [ #Minimum min(i for i,c in enumerate(count) if c != 0), #Maximum max(i for i,c in enumerate(count) if c != 0), #Mean sum(i*c for i,c in enumerate(count)) / sum(c for c in count if c != 0), #Media (lambda total: ( next(i for i,s in enumerate(itertools.accumulate(count)) if s >= total//2+1)+ next(i for i,s in enumerate(itertools.accumulate(count)) if s >= total//2+total%2) )/2 )(sum(c for c in count if c != 0)), #Mode max(((i,c) for i,c in enumerate(count) if c != 0),key=(lambda x: x[1]))[0] ]
https://leetcode.com/problems/statistics-from-a-large-sample/discuss/1653119/Python3-one-liner
0
You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample. Calculate the following statistics: minimum: The minimum element in the sample. maximum: The maximum element in the sample. mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements. median: If the sample has an odd number of elements, then the median is the middle element once the sample is sorted. If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted. mode: The number that appears the most in the sample. It is guaranteed to be unique. Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted. Example 1: Input: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Output: [1.00000,3.00000,2.37500,2.50000,3.00000] Explanation: The sample represented by count is [1,2,2,2,3,3,3,3]. The minimum and maximum are 1 and 3 respectively. The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375. Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5. The mode is 3 as it appears the most in the sample. Example 2: Input: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Output: [1.00000,4.00000,2.18182,2.00000,1.00000] Explanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4]. The minimum and maximum are 1 and 4 respectively. The mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182). Since the size of the sample is odd, the median is the middle element 2. The mode is 1 as it appears the most in the sample. Constraints: count.length == 256 0 <= count[i] <= 109 1 <= sum(count) <= 109 The mode of the sample that count represents is unique.
Python3 one-liner
179
statistics-from-a-large-sample
0.444
pknoe3lh
Medium
17,381
1,093
car pooling
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: path = [0]*1000 for num, a, b in trips: for loc in range (a, b): path[loc] += num if path[loc] > capacity: return False return True
https://leetcode.com/problems/car-pooling/discuss/1669593/Python3-STRAIGHTFORWARD-()-Explained
11
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location. Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise. Example 1: Input: trips = [[2,1,5],[3,3,7]], capacity = 4 Output: false Example 2: Input: trips = [[2,1,5],[3,3,7]], capacity = 5 Output: true Constraints: 1 <= trips.length <= 1000 trips[i].length == 3 1 <= numPassengersi <= 100 0 <= fromi < toi <= 1000 1 <= capacity <= 105
❤ [Python3] STRAIGHTFORWARD (✿◠‿◠), Explained
826
car-pooling
0.573
artod
Medium
17,384
1,094
find in mountain array
class Solution: def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int: def fn(lo, hi, mult): """Return index of target between lo (inclusive) and hi (exlusive).""" while lo < hi: mid = lo + hi >> 1 if mountain_arr.get(mid) == target: return mid elif mountain_arr.get(mid)*mult < target*mult: lo = mid + 1 else: hi = mid return -1 lo, hi = 0, mountain_arr.length() while lo < hi: mid = lo + hi >> 1 if mid and mountain_arr.get(mid-1) < mountain_arr.get(mid): lo = mid + 1 else: hi = mid if (x := fn(0, lo, 1)) != -1: return x if (x := fn(lo, mountain_arr.length(), -1)) != -1: return x return -1
https://leetcode.com/problems/find-in-mountain-array/discuss/1290875/Python3-binary-search
1
(This problem is an interactive problem.) You may recall that an array arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1. You cannot access the mountain array directly. You may only access the array using a MountainArray interface: MountainArray.get(k) returns the element of the array at index k (0-indexed). MountainArray.length() returns the length of the array. Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. Example 1: Input: array = [1,2,3,4,5,3,1], target = 3 Output: 2 Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. Example 2: Input: array = [0,1,2,4,2,1], target = 3 Output: -1 Explanation: 3 does not exist in the array, so we return -1. Constraints: 3 <= mountain_arr.length() <= 104 0 <= target <= 109 0 <= mountain_arr.get(index) <= 109
[Python3] binary search
48
find-in-mountain-array
0.357
ye15
Hard
17,421
1,095
brace expansion ii
class Solution: def braceExpansionII(self, expression: str) -> List[str]: stack,res,cur=[],[],[] for i in range(len(expression)): v=expression[i] if v.isalpha(): cur=[c+v for c in cur or ['']] elif v=='{': stack.append(res) stack.append(cur) res,cur=[],[] elif v=='}': pre=stack.pop() preRes=stack.pop() cur=[p+c for c in res+cur for p in pre or ['']] res=preRes elif v==',': res+=cur cur=[] return sorted(set(res+cur))
https://leetcode.com/problems/brace-expansion-ii/discuss/322002/Python3-Concise-iterative-solution-using-stack
102
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents. The grammar can best be understood through simple examples: Single letters represent a singleton set containing that word. R("a") = {"a"} R("w") = {"w"} When we take a comma-delimited list of two or more expressions, we take the union of possibilities. R("{a,b,c}") = {"a","b","c"} R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once) When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression. R("{a,b}{c,d}") = {"ac","ad","bc","bd"} R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"} Formally, the three rules for our grammar: For every lowercase letter x, we have R(x) = {x}. For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ... For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product. Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents. Example 1: Input: expression = "{a,b}{c,{d,e}}" Output: ["ac","ad","ae","bc","bd","be"] Example 2: Input: expression = "{{a,z},a{b,c},{ab,z}}" Output: ["a","ab","ac","z"] Explanation: Each distinct word is written only once in the final answer. Constraints: 1 <= expression.length <= 60 expression[i] consists of '{', '}', ','or lowercase English letters. The given expression represents a set of words based on the grammar given in the description.
[Python3] Concise iterative solution using stack
4,800
brace-expansion-ii
0.635
yuanzhi247012
Hard
17,427
1,096
distribute candies to people
class Solution: def distributeCandies(self, candies: int, num_people: int) -> List[int]: # create an array of size num_people and initialize it with 0 list_people = [0] * num_people # starting value index = 1 # iterate until the number of candies are more than 0 while candies > 0: # if candies are more than index value, add the index value to the location if candies > index: # we are using mod operation by the num_people to locate the index of the array # we are subtracting by 1 because the array index starts at 0 list_people[(index - 1) % num_people] += index else: # if candies are less than index value, add all remaining candies to location list_people[(index - 1) % num_people] += candies # subtract the candies with index values candies -= index # increment the index values index += 1 # return the resultant array return(list_people)
https://leetcode.com/problems/distribute-candies-to-people/discuss/797848/Solution-or-Python
11
We distribute some number of candies, to a row of n = num_people people in the following way: We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift). Return an array (of length num_people and sum candies) that represents the final distribution of candies. Example 1: Input: candies = 7, num_people = 4 Output: [1,2,3,1] Explanation: On the first turn, ans[0] += 1, and the array is [1,0,0,0]. On the second turn, ans[1] += 2, and the array is [1,2,0,0]. On the third turn, ans[2] += 3, and the array is [1,2,3,0]. On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1]. Example 2: Input: candies = 10, num_people = 3 Output: [5,2,3] Explanation: On the first turn, ans[0] += 1, and the array is [1,0,0]. On the second turn, ans[1] += 2, and the array is [1,2,0]. On the third turn, ans[2] += 3, and the array is [1,2,3]. On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. Constraints: 1 <= candies <= 10^9 1 <= num_people <= 1000
Solution | Python
439
distribute-candies-to-people
0.639
rushirg
Easy
17,430
1,103
path in zigzag labelled binary tree
class Solution: def pathInZigZagTree(self, label: int) -> List[int]: rows = [(1, 0)] #row represented by tuple (min_element_in_row, is_neg_order) while rows[-1][0]*2 <= label: rows.append((rows[-1][0]*2, 1 - rows[-1][1])) power, negOrder = rows.pop() res = [] while label > 1: res.append(label) if negOrder: # adjust label position and find parent with division by 2 # a, b - range of current row a, b = power, power*2 -1 label = (a + (b - label))//2 else: # divide label by 2 and adjust parent position # a, b - range of previous row a, b = power//2, power - 1 label = b - (label//2 - a) power, negOrder = rows.pop() res.append(1) return res[::-1]
https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/323382/Python-3-easy-explained
3
In an infinite binary tree where every node has two children, the nodes are labelled in row order. In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left. Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label. Example 1: Input: label = 14 Output: [1,3,4,14] Example 2: Input: label = 26 Output: [1,2,6,10,26] Constraints: 1 <= label <= 10^6
Python 3 easy explained
207
path-in-zigzag-labelled-binary-tree
0.75
vilchinsky
Medium
17,448
1,104
filling bookcase shelves
class Solution: def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int: n = len(books) dp = [sys.maxsize] * n dp[0] = books[0][1] # first book will always on it's own row for i in range(1, n): # for each book cur_w, height_max = books[i][0], books[i][1] dp[i] = dp[i-1] + height_max # initialize result for current book `dp[i]` for j in range(i-1, -1, -1): # for each previou `book[j]`, verify if it can be placed in the same row as `book[i]` if cur_w + books[j][0] > shelfWidth: break cur_w += books[j][0] height_max = max(height_max, books[j][1]) # update current max height dp[i] = min(dp[i], (dp[j-1] + height_max) if j-1 >= 0 else height_max) # always take the maximum heigh on current row return dp[n-1]
https://leetcode.com/problems/filling-bookcase-shelves/discuss/1517001/Python-3-or-DP-or-Explanation
5
You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth. We want to place these books in order onto bookcase shelves that have a total width shelfWidth. We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place. Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books. For example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf. Return the minimum possible height that the total bookshelf can be after placing shelves in this manner. Example 1: Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4 Output: 6 Explanation: The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6. Notice that book number 2 does not have to be on the first shelf. Example 2: Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6 Output: 4 Constraints: 1 <= books.length <= 1000 1 <= thicknessi <= shelfWidth <= 1000 1 <= heighti <= 1000
Python 3 | DP | Explanation
518
filling-bookcase-shelves
0.592
idontknoooo
Medium
17,456
1,105
parsing a boolean expression
class Solution: operands = {"!", "&amp;", "|", "t", "f"} values = {"t", "f"} def parseBoolExpr(self, expression: str) -> bool: stack = [] for c in expression: if c == ")": val = stack.pop() args = set() while val in Solution.values: args.add(val) val = stack.pop() if val == "!": stack.append("f" if "t" in args else "t") elif val == "&amp;": stack.append("f" if "f" in args else "t") elif val == "|": stack.append("t" if "t" in args else "f") elif c in Solution.operands: stack.append(c) return stack[0] == "t"
https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1582694/One-pass-with-stack-97-speed
2
A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes: 't' that evaluates to true. 'f' that evaluates to false. '!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr. '&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. '|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1. Given a string expression that represents a boolean expression, return the evaluation of that expression. It is guaranteed that the given expression is valid and follows the given rules. Example 1: Input: expression = "&(|(f))" Output: false Explanation: First, evaluate |(f) --> f. The expression is now "&(f)". Then, evaluate &(f) --> f. The expression is now "f". Finally, return false. Example 2: Input: expression = "|(f,f,f,t)" Output: true Explanation: The evaluation of (false OR false OR false OR true) is true. Example 3: Input: expression = "!(&(f,t))" Output: true Explanation: First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)". Then, evaluate !(f) --> NOT false --> true. We return true. Constraints: 1 <= expression.length <= 2 * 104 expression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','.
One pass with stack, 97% speed
142
parsing-a-boolean-expression
0.585
EvgenySH
Hard
17,465
1,106
defanging an ip address
class Solution: def defangIPaddr(self, address: str) -> str: address=address.replace(".","[.]") return address
https://leetcode.com/problems/defanging-an-ip-address/discuss/1697285/Python-code%3A-Defanging-an-IP-Address
3
Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]". Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0" Constraints: The given address is a valid IPv4 address.
Python code: Defanging an IP Address
78
defanging-an-ip-address
0.893
Anilchouhan181
Easy
17,472
1,108
corporate flight bookings
class Solution: def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]: res = [0]*n for first, last, seat in bookings: res[first - 1] += seat if last < n: res[last] -= seat return accumulate(res)
https://leetcode.com/problems/corporate-flight-bookings/discuss/2309125/Easy-Python-O(n)-using-accumulate
3
There are n flights that are labeled from 1 to n. You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range. Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i. Example 1: Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5 Output: [10,55,45,25,25] Explanation: Flight labels: 1 2 3 4 5 Booking 1 reserved: 10 10 Booking 2 reserved: 20 20 Booking 3 reserved: 25 25 25 25 Total seats: 10 55 45 25 25 Hence, answer = [10,55,45,25,25] Example 2: Input: bookings = [[1,2,10],[2,2,15]], n = 2 Output: [10,25] Explanation: Flight labels: 1 2 Booking 1 reserved: 10 10 Booking 2 reserved: 15 Total seats: 10 25 Hence, answer = [10,25] Constraints: 1 <= n <= 2 * 104 1 <= bookings.length <= 2 * 104 bookings[i].length == 3 1 <= firsti <= lasti <= n 1 <= seatsi <= 104
Easy Python O(n) using accumulate
140
corporate-flight-bookings
0.604
rinaba501
Medium
17,526
1,109
delete nodes and return forest
class Solution: def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]: to_delete = set(to_delete) # O(1) lookup def fn(node, pval): """Return node upon deletion of required values.""" if not node: return if node.val in to_delete: node.left = fn(node.left, None) node.right = fn(node.right, None) return else: if not pval: ans.append(node) node.left = fn(node.left, node.val) node.right = fn(node.right, node.val) return node ans = [] fn(root, None) return ans
https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1025341/Python3-dfs-O(N)
5
Given the root of a binary tree, each node in the tree has a distinct value. After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees). Return the roots of the trees in the remaining forest. You may return the result in any order. Example 1: Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output: [[1,2,null,4],[6],[7]] Example 2: Input: root = [1,2,4,null,3], to_delete = [3] Output: [[1,2,4]] Constraints: The number of nodes in the given tree is at most 1000. Each node has a distinct value between 1 and 1000. to_delete.length <= 1000 to_delete contains distinct values between 1 and 1000.
[Python3] dfs O(N)
233
delete-nodes-and-return-forest
0.693
ye15
Medium
17,545
1,110
maximum nesting depth of two valid parentheses strings
class Solution: def maxDepthAfterSplit(self, seq: str) -> List[int]: ans=[] prev=1 for i in seq: if i=='(': if prev==0: ans.append(1) else: ans.append(0) else: ans.append(prev) if prev==0: prev=1 else: prev=0 return ans
https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2825324/Python-oror-98.06-Faster-oror-Greedy-Approach-oror-O(N)-Solution
1
A string is a valid parentheses string (denoted VPS) if and only if it consists of "(" and ")" characters only, and: It is the empty string, or It can be written as AB (A concatenated with B), where A and B are VPS's, or It can be written as (A), where A is a VPS. We can similarly define the nesting depth depth(S) of any VPS S as follows: depth("") = 0 depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's depth("(" + A + ")") = 1 + depth(A), where A is a VPS. For example, "", "()()", and "()(()())" are VPS's (with nesting depths 0, 1, and 2), and ")(" and "(()" are not VPS's. Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length). Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value. Return an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them. Example 1: Input: seq = "(()())" Output: [0,1,1,1,1,0] Example 2: Input: seq = "()(())()" Output: [0,0,0,1,1,0,1,1] Constraints: 1 <= seq.size <= 10000
Python || 98.06% Faster || Greedy Approach || O(N) Solution
10
maximum-nesting-depth-of-two-valid-parentheses-strings
0.732
DareDevil_007
Medium
17,555
1,111
relative sort array
class Solution: def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: # initialise a dictionary since we're going to want to count the occurences of each element in arr1 dic = {} # this loop populates the dictionary with the number of occurences for each element for elem in arr1: if dic.get(elem) is None: dic[elem] = 1 else: dic[elem] = dic[elem] + 1 # initialise a new list to store the values which exist in both arr2 and arr1 output = [] # populate output with the elements multiplied by their occurences (e.g. [1]*2 = [1, 1]) for elem in arr2: output += [elem]*dic[elem] # initialise a new list to store the elements which are in arr1 but not arr2 extra_output = [] # populate extra_output with these elements multiplied by their occurences. # Note: set(arr1)-set(arr2) provides us with the set of numbers which exist in arr1 but not in arr2 for elem in set(arr1)-set(arr2): extra_output += [elem]*dic[elem] # return the first list and the sorted second list return output + sorted(extra_output)
https://leetcode.com/problems/relative-sort-array/discuss/343445/Python3.-Actually-easy-to-understand.-Beats-75-on-speed-and-100-on-memory
12
Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. Example 1: Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] Output: [2,2,2,1,4,3,3,9,6,7,19] Example 2: Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] Output: [22,28,8,6,17,44] Constraints: 1 <= arr1.length, arr2.length <= 1000 0 <= arr1[i], arr2[i] <= 1000 All the elements of arr2 are distinct. Each arr2[i] is in arr1.
Python3. Actually easy to understand. Beats 75% on speed and 100% on memory
1,800
relative-sort-array
0.684
softbabywipes
Easy
17,564
1,122
lowest common ancestor of deepest leaves
class Solution: def ht(self, node): if not node: return 0 return max(self.ht(node.left), self.ht(node.right)) + 1 def dfs(self, node): if not node: return None left, right = self.ht(node.left), self.ht(node.right) if left == right: return node if left > right: return self.dfs(node.left) if left < right: return self.dfs(node.right) def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]: return self.dfs(root)
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1760394/Python-easy-to-understand-and-read-or-DFS
4
Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. Recall that: The node of a binary tree is a leaf if and only if it has no children The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1. The lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A. Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest leaf-nodes of the tree. Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3. Example 2: Input: root = [1] Output: [1] Explanation: The root is the deepest node in the tree, and it's the lca of itself. Example 3: Input: root = [0,1,3,null,2] Output: [2] Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself. Constraints: The number of nodes in the tree will be in the range [1, 1000]. 0 <= Node.val <= 1000 The values of the nodes in the tree are unique. Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
Python easy to understand and read | DFS
184
lowest-common-ancestor-of-deepest-leaves
0.706
sanial2001
Medium
17,612
1,123
longest well performing interval
class Solution: def longestWPI(self, hours: List[int]) -> int: dic = defaultdict(int) dummy = [1 if hours[0]>8 else -1] for h in hours[1:]: c = 1 if h>8 else -1 dummy.append(dummy[-1]+c) res = 0 for i in range(len(dummy)): if dummy[i]>0: res = max(res,i+1) else: if dummy[i]-1 in dic: res = max(res,i-dic[dummy[i]-1]) if dummy[i] not in dic: dic[dummy[i]] = i return res
https://leetcode.com/problems/longest-well-performing-interval/discuss/1495771/For-Beginners-oror-Well-Explained-oror-97-faster-oror-Easy-to-understand
4
We are given hours, a list of the number of hours worked per day for a given employee. A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8. A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days. Return the length of the longest well-performing interval. Example 1: Input: hours = [9,9,6,0,6,6,9] Output: 3 Explanation: The longest well-performing interval is [9,9,6]. Example 2: Input: hours = [6,6,6] Output: 0 Constraints: 1 <= hours.length <= 104 0 <= hours[i] <= 16
📌📌 For-Beginners || Well-Explained || 97% faster || Easy-to-understand 🐍
471
longest-well-performing-interval
0.346
abhi9Rai
Medium
17,623
1,124
smallest sufficient team
class Solution: def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]: # Firstly, convert all the sublists in people into sets for easier processing. for i, skills in enumerate(people): people[i] = set(skills) # Remove all skill sets that are subset of another skillset, by replacing the subset with an # empty set. We do this rather than completely removing, so that indexes aren't # disrupted (which is a pain to have to sort out later). for i, i_skills in enumerate(people): for j, j_skills in enumerate(people): if i != j and i_skills.issubset(j_skills): people[i] = set() # Now build up a dictionary of skills to the people who can perform them. The backtracking algorithm # will use this. skills_to_people = collections.defaultdict(set) for i, skills in enumerate(people): for skill in skills: skills_to_people[skill].add(i) people[i] = set(skills) # Keep track of some data used by the backtracking algorithm. self.unmet_skills = set(req_skills) # Backtracking will remove and readd skills here as needed. self.smallest_length = math.inf # Smallest team length so far. self.current_team = [] # Current team members. self.best_team = [] # Best team we've found, i,e, shortest team that covers skills/ # Here is the backtracking algorithm. def meet_skill(skill=0): # Base case: All skills are met. if not self.unmet_skills: # If the current team is smaller than the previous we found, update it. if self.smallest_length > len(self.current_team): self.smallest_length = len(self.current_team) self.best_team = self.current_team[::] # In Python, this makes a copy of a list. return # So that we don't carry out the rest of the algorithm. # If this skill is already met, move onto the next one. if req_skills[skill] not in self.unmet_skills: return meet_skill(skill + 1) # Note return is just to stop rest of code here running. Return values # are not caught and used. # Otherwise, consider all who could meet the current skill. for i in skills_to_people[req_skills[skill]]: # Add this person onto the team by updating the backtrading data. skills_added_by_person = people[i].intersection(self.unmet_skills) self.unmet_skills = self.unmet_skills - skills_added_by_person self.current_team.append(i) # Do the recursive call to further build the team. meet_skill(skill + 1) # Backtrack by removing the person from the team again. self.current_team.pop() self.unmet_skills = self.unmet_skills.union(skills_added_by_person) # Kick off the algorithm. meet_skill() return self.best_team
https://leetcode.com/problems/smallest-sufficient-team/discuss/334630/Python-Optimized-backtracking-with-explanation-and-code-comments-88-ms
44
In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has. Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person. For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3]. Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order. It is guaranteed an answer exists. Example 1: Input: req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]] Output: [0,2] Example 2: Input: req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] Output: [1,2] Constraints: 1 <= req_skills.length <= 16 1 <= req_skills[i].length <= 16 req_skills[i] consists of lowercase English letters. All the strings of req_skills are unique. 1 <= people.length <= 60 0 <= people[i].length <= 16 1 <= people[i][j].length <= 16 people[i][j] consists of lowercase English letters. All the strings of people[i] are unique. Every skill in people[i] is a skill in req_skills. It is guaranteed a sufficient team exists.
Python - Optimized backtracking with explanation and code comments [88 ms]
3,100
smallest-sufficient-team
0.47
Hai_dee
Hard
17,628
1,125
number of equivalent domino pairs
class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: m = collections.defaultdict(int) ans = 0 for a, b in dominoes: if a > b: a, b = b, a v = 10*a + b if v in m: ans += m[v] m[v] += 1 return ans
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/405437/Python3-Concise-and-Efficient
6
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]. Example 1: Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] Output: 1 Example 2: Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] Output: 3 Constraints: 1 <= dominoes.length <= 4 * 104 dominoes[i].length == 2 1 <= dominoes[i][j] <= 9
Python3 - Concise and Efficient
310
number-of-equivalent-domino-pairs
0.469
luojl
Easy
17,631
1,128
shortest path with alternating colors
class Solution: def shortestAlternatingPaths(self, n, red_edges, blue_edges): neighbors = [[[], []] for _ in range(n)] ans = [[0, 0]]+[[2*n, 2*n] for _ in range(n-1)] for u, v in red_edges: neighbors[u][0].append(v) for u, v in blue_edges: neighbors[u][1].append(v) def dfs(u, c, dist): for v in neighbors[u][c]: if dist+1<ans[v][c]: ans[v][c] = dist+1 dfs(v, 1-c, dist+1) dfs(0, 0, 0) dfs(0, 1, 0) return [x if x<2*n else -1 for x in map(min, ans)]
https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/712063/Python-DFS
5
You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays redEdges and blueEdges where: redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph. Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist. Example 1: Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = [] Output: [0,1,-1] Example 2: Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]] Output: [0,1,-1] Constraints: 1 <= n <= 100 0 <= redEdges.length, blueEdges.length <= 400 redEdges[i].length == blueEdges[j].length == 2 0 <= ai, bi, uj, vj < n
Python DFS
226
shortest-path-with-alternating-colors
0.43
stuxen
Medium
17,644
1,129
minimum cost tree from leaf values
class Solution: def mctFromLeafValues(self, arr: List[int]) -> int: arr = [float('inf')] + arr + [float('inf')] n, res = len(arr), 0 while n>3: mi = min(arr) ind = arr.index(mi) if arr[ind-1]<arr[ind+1]: res+=arr[ind-1]*arr[ind] else: res+=arr[ind+1]*arr[ind] arr.remove(mi) n = len(arr) return res
https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/1510611/Greedy-Approach-oror-97-faster-oror-Well-Explained
21
Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond to the values of each leaf in an in-order traversal of the tree. The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively. Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer. A node is a leaf if and only if it has zero children. Example 1: Input: arr = [6,2,4] Output: 32 Explanation: There are two possible trees shown. The first has a non-leaf node sum 36, and the second has non-leaf node sum 32. Example 2: Input: arr = [4,11] Output: 44 Constraints: 2 <= arr.length <= 40 1 <= arr[i] <= 15 It is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 231).
📌📌 Greedy-Approach || 97% faster || Well-Explained 🐍
769
minimum-cost-tree-from-leaf-values
0.685
abhi9Rai
Medium
17,657
1,130
maximum of absolute value expression
class Solution: def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int: minA = minB = minC = minD = math.inf maxA = maxB = maxC = maxD = -math.inf for i, (num1, num2) in enumerate(zip(arr1, arr2)): minA = min(minA, i + num1 + num2) maxA = max(maxA, i + num1 + num2) minB = min(minB, i + num1 - num2) maxB = max(maxB, i + num1 - num2) minC = min(minC, i - num1 + num2) maxC = max(maxC, i - num1 + num2) minD = min(minD, i - num1 - num2) maxD = max(maxD, i - num1 - num2) return max(maxA - minA, maxB - minB, maxC - minC, maxD - minD)
https://leetcode.com/problems/maximum-of-absolute-value-expression/discuss/1835078/Python-3-or-O(n)O(1)
2
Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length. Example 1: Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 Example 2: Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] Output: 20 Constraints: 2 <= arr1.length == arr2.length <= 40000 -10^6 <= arr1[i], arr2[i] <= 10^6
Python 3 | O(n)/O(1)
322
maximum-of-absolute-value-expression
0.494
dereky4
Medium
17,665
1,131
n th tribonacci number
class Solution: def tribonacci(self, n: int) -> int: a, b, c = 0, 1, 1 for i in range(n): a, b, c = b, c, a + b + c return a - Junaid Mansuri
https://leetcode.com/problems/n-th-tribonacci-number/discuss/350547/Solution-in-Python-3-(beats-~100)
14
The Tribonacci sequence Tn is defined as follows: T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. Given n, return the value of Tn. Example 1: Input: n = 4 Output: 4 Explanation: T_3 = 0 + 1 + 1 = 2 T_4 = 1 + 1 + 2 = 4 Example 2: Input: n = 25 Output: 1389537 Constraints: 0 <= n <= 37 The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
Solution in Python 3 (beats ~100%)
1,600
n-th-tribonacci-number
0.633
junaidmansuri
Easy
17,670
1,137
alphabet board path
class Solution: def __init__(self): board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"] self.d = {c:(i, j) for i, row in enumerate(board) for j, c in enumerate(row)} def alphabetBoardPath(self, target: str) -> str: ans, prev = '', (0, 0) for c in target: cur = self.d[c] delta_x, delta_y = cur[0]-prev[0], cur[1]-prev[1] h = 'R'*delta_y if delta_y > 0 else 'L'*(-delta_y) v = 'D'*delta_x if delta_x > 0 else 'U'*(-delta_x) ans += (h+v if cur == (5,0) else v+h) + '!' prev = cur return ans
https://leetcode.com/problems/alphabet-board-path/discuss/837601/Python-3-or-Straight-forward-solution-or-Explanations
2
On an alphabet board, we start at position (0, 0), corresponding to character board[0][0]. Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below. We may make the following moves: 'U' moves our position up one row, if the position exists on the board; 'D' moves our position down one row, if the position exists on the board; 'L' moves our position left one column, if the position exists on the board; 'R' moves our position right one column, if the position exists on the board; '!' adds the character board[r][c] at our current position (r, c) to the answer. (Here, the only positions that exist on the board are positions with letters on them.) Return a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so. Example 1: Input: target = "leet" Output: "DDR!UURRR!!DDD!" Example 2: Input: target = "code" Output: "RR!DDRR!UUL!R!" Constraints: 1 <= target.length <= 100 target consists only of English lowercase letters.
Python 3 | Straight forward solution | Explanations
184
alphabet-board-path
0.523
idontknoooo
Medium
17,731
1,138
largest 1 bordered square
class Solution: def largest1BorderedSquare(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dp = [[(0, 0)] * (n) for _ in range((m))] for i in range(m): # calculate prefix-sum as `hint` section suggested for j in range(n): if not grid[i][j]: continue dp[i][j] = (dp[i][j][0] + dp[i-1][j][0] + 1, dp[i][j][1] + dp[i][j-1][1] + 1) for win in range(min(m, n)-1, -1, -1): # for each window size for i in range(m-win): # for each x-axis for j in range(n-win): # for each y-axis if not grid[i][j]: continue # determine whether square of (i, j), (i+win, j+win) is 1-boarded x1, y1 = dp[i+win][j+win] # bottom-right corner x2, y2 = dp[i][j+win] # upper-right corner x3, y3 = dp[i+win][j] # bottom-left corner x4, y4 = dp[i][j] # upper-left corner if y1 - y3 == x1 - x2 == y2 - y4 == x3 - x4 == win: return (win+1) * (win+1) return 0
https://leetcode.com/problems/largest-1-bordered-square/discuss/1435087/Python-3-or-Prefix-sum-DP-O(N3)-or-Explanation
2
Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid. Example 1: Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9 Example 2: Input: grid = [[1,1,0,0]] Output: 1 Constraints: 1 <= grid.length <= 100 1 <= grid[0].length <= 100 grid[i][j] is 0 or 1
Python 3 | Prefix-sum, DP, O(N^3) | Explanation
347
largest-1-bordered-square
0.501
idontknoooo
Medium
17,739
1,139
stone game ii
class Solution: def stoneGameII(self, piles: List[int]) -> int: suffix_sum = self._suffix_sum(piles) @lru_cache(None) def dfs(pile: int, M: int, turn: bool) -> Tuple[int, int]: # turn: true - alex, false - lee sum_alex, sum_lee = suffix_sum[pile], suffix_sum[pile] for next_pile in range(pile + 1, min(pile + 2 * M + 1, len(piles) + 1)): sum_alex_next, sum_lee_next = dfs( next_pile, max(M, next_pile - pile), not turn ) range_sum = suffix_sum[pile] - suffix_sum[next_pile] if turn: if sum_lee_next < sum_lee: sum_alex = sum_alex_next + range_sum sum_lee = sum_lee_next else: if sum_alex_next < sum_alex: sum_alex = sum_alex_next sum_lee = sum_lee_next + range_sum return sum_alex, sum_lee return dfs(0, 1, True)[0]
https://leetcode.com/problems/stone-game-ii/discuss/793881/python-DP-Thought-process-explained
36
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. Initially, M = 1. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X). The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get. Example 1: Input: piles = [2,7,9,4,4] Output: 10 Explanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. Example 2: Input: piles = [1,2,3,4,5,100] Output: 104 Constraints: 1 <= piles.length <= 100 1 <= piles[i] <= 104
[python] DP Thought process explained
1,900
stone-game-ii
0.649
omgitspavel
Medium
17,743
1,140
longest common subsequence
class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: dp = [] # Fill the matrix for _ in range(len(text1)+1): row = [] for _ in range(len(text2)+1): row.append(0) dp.append(row) longest_length = 0 # Start looping throught the text1 and text2 for i in range(1, len(text1)+1): for j in range(1, len(text2)+1): # If characters match # fill the current cell by adding one to the diagonal value if text1[i-1] == text2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 else: # If characters do not match # Fill the cell with max value of previous row and column dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # Keep track of the MAXIMUM value in the matrix longest_length = max(longest_length, dp[i][j]) return longest_length
https://leetcode.com/problems/longest-common-subsequence/discuss/2331817/Python3-or-Java-or-C%2B%2B-or-DP-or-O(nm)-or-BottomUp-(Tabulation)
10
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3. Example 2: Input: text1 = "abc", text2 = "abc" Output: 3 Explanation: The longest common subsequence is "abc" and its length is 3. Example 3: Input: text1 = "abc", text2 = "def" Output: 0 Explanation: There is no such common subsequence, so the result is 0. Constraints: 1 <= text1.length, text2.length <= 1000 text1 and text2 consist of only lowercase English characters.
Python3 | Java | C++ | DP | O(nm) | BottomUp (Tabulation)
488
longest-common-subsequence
0.588
khaydaraliev99
Medium
17,752
1,143
decrease elements to make array zigzag
class Solution: def movesToMakeZigzag(self, nums: List[int]) -> int: def greedy(nums, small_first=True): if n <= 1: return 0 ans = 0 for i in range(n-1): if small_first and nums[i] >= nums[i+1]: ans += nums[i] - (nums[i+1]-1) nums[i] = nums[i+1] - 1 elif not small_first and nums[i] <= nums[i+1]: ans += nums[i+1] - (nums[i]-1) nums[i+1] = nums[i] - 1 small_first = not small_first return ans n = len(nums) return min(greedy(nums[:], True), greedy(nums[:], False))
https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/891850/Python-3-or-Greedy-Two-pass-or-Explanation
1
Given an array nums of integers, a move consists of choosing any element and decreasing it by 1. An array A is a zigzag array if either: Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ... OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ... Return the minimum number of moves to transform the given array nums into a zigzag array. Example 1: Input: nums = [1,2,3] Output: 2 Explanation: We can decrease 2 to 0 or 3 to 1. Example 2: Input: nums = [9,6,1,6,2] Output: 4 Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 1000
Python 3 | Greedy Two pass | Explanation
312
decrease-elements-to-make-array-zigzag
0.47
idontknoooo
Medium
17,813
1,144
binary tree coloring game
class Solution: def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool: first = None def count(node): nonlocal first total = 0 if node: if node.val == x: first = node total += count(node.left) + count(node.right) + 1 return total s = count(root) # Get total number of nodes, and x node (first player's choice) l = count(first.left) # Number of nodes on left branch r = count(first.right) # Number of nodes on right branch p = s-l-r-1 # Number of nodes on parent branch (anything else other than node, left subtree of node or right subtree of node) return l+r < p or l+p < r or r+p < l
https://leetcode.com/problems/binary-tree-coloring-game/discuss/797574/Python-3-or-DFS-or-One-pass-and-Three-pass-or-Explanation
13
Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n. Initially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue. Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.) If (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes. You are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false. Example 1: Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3 Output: true Explanation: The second player can choose the node with value 2. Example 2: Input: root = [1,2,3], n = 3, x = 1 Output: false Constraints: The number of nodes in the tree is n. 1 <= x <= n <= 100 n is odd. 1 <= Node.val <= n All the values of the tree are unique.
Python 3 | DFS | One pass & Three pass | Explanation
501
binary-tree-coloring-game
0.515
idontknoooo
Medium
17,819
1,145
longest chunked palindrome decomposition
class Solution: def longestDecomposition(self, text: str) -> int: # Used a prime number generator on the internet to grab a prime number to use. magic_prime = 32416189573 # Standard 2 pointer technique variables. low = 0 high = len(text) - 1 # These are the hash tracking variables. cur_low_hash = 0 cur_high_hash = 0 cur_hash_length = 0 # This is the number of parts we've found, i.e. the k value we need to return. k = 0 while low < high: # To put the current letter onto our low hash (i.e. the one that goes forward from # the start of the string, we shift up the existing hash by multiplying by the base # of 26, and then adding on the new character by converting it to a number from 0 - 25. cur_low_hash *= 26 # Shift up by the base of 26. cur_low_hash += ord(text[low]) - 97 # Take away 97 so that it's between 0 and 25. # The high one, i.e. the one backwards from the end is a little more complex, as we want the # hash to represent the characters in forward order, not backwards. If we did the exact same # thing we did for low, the string abc would be represented as cba, which is not right. # Start by getting the character's 0 - 25 number. high_char = ord(text[high]) - 97 # The third argument to pow is modular arithmetic. It says to give the answer modulo the # magic prime (more on that below). Just pretend it isn't doing that for now if it confuses you. # What we're doing is making an int that puts the high character at the top, and then the # existing hash at the bottom. cur_high_hash = (high_char * pow(26, cur_hash_length, magic_prime)) + cur_high_hash # Mathematically, we can safely do this. Impressive, huh? I'm not going to go into here, but # I recommend studying up on modular arithmetic if you're confused. # The algorithm would be correct without doing this, BUT it'd be very slow as the numbers could # become tens of thousands of bits long. The problem with that of course is that comparing the # numbers would no longer be O(1) constant. So we need to keep them small. cur_low_hash %= magic_prime cur_high_hash %= magic_prime # And now some standard 2 pointer technique stuff. low += 1 high -= 1 cur_hash_length += 1 # This piece of code checks if we currently have a match. # This is actually probabilistic, i.e. it is possible to get false positives. # For correctness, we should be verifying that this is actually correct. # We would do this by ensuring the characters in each hash (using # the low, high, and length variables we've been tracking) are # actually the same. But here I didn't bother as I figured Leetcode # would not have a test case that broke my specific prime. if cur_low_hash == cur_high_hash: k += 2 # We have just added 2 new strings to k. # And reset our hashing variables. cur_low_hash = 0 cur_high_hash = 0 cur_hash_length = 0 # At the end, there are a couple of edge cases we need to address.... # The first is if there is a middle character left. # The second is a non-paired off string in the middle. if (cur_hash_length == 0 and low == high) or cur_hash_length > 0: k += 1 return k
https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/350711/Close-to-O(n)-Python-Rabin-Karp-Algorithm-with-two-pointer-technique-with-explanation-(~40ms)
33
You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that: subtexti is a non-empty string. The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text). subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k). Return the largest possible value of k. Example 1: Input: text = "ghiabcdefhelloadamhelloabcdefghi" Output: 7 Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)". Example 2: Input: text = "merchant" Output: 1 Explanation: We can split the string on "(merchant)". Example 3: Input: text = "antaprezatepzapreanta" Output: 11 Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)". Constraints: 1 <= text.length <= 1000 text consists only of lowercase English characters.
Close to O(n) Python, Rabin Karp Algorithm with two pointer technique with explanation (~40ms)
2,400
longest-chunked-palindrome-decomposition
0.597
Hai_dee
Hard
17,823
1,147
day of the year
class Solution: def dayOfYear(self, date: str) -> int: y, m, d = map(int, date.split('-')) days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (y % 400) == 0 or ((y % 4 == 0) and (y % 100 != 0)): days[1] = 29 return d + sum(days[:m-1])
https://leetcode.com/problems/day-of-the-year/discuss/449866/Python-3-Four-liner-Simple-Solution
30
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. Example 1: Input: date = "2019-01-09" Output: 9 Explanation: Given date is the 9th day of the year in 2019. Example 2: Input: date = "2019-02-10" Output: 41 Constraints: date.length == 10 date[4] == date[7] == '-', and all other date[i]'s are digits date represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.
Python 3 - Four liner - Simple Solution
1,700
day-of-the-year
0.501
mmbhatk
Easy
17,830
1,154
number of dice rolls with target sum
class Solution: def numRollsToTarget(self, d: int, f: int, target: int) -> int: if d*f < target: return 0 # Handle special case, it speed things up, but not necessary elif d*f == target: return 1 # Handle special case, it speed things up, but not necessary mod = int(10**9 + 7) dp = [[0] * (target+1) for _ in range(d+1)] for j in range(1, min(f+1, target+1)): dp[1][j] = 1 for i in range(2, d+1): for j in range(1, target+1): for k in range(1, f+1): if j - k >= 0: dp[i][j] += dp[i-1][j-k] dp[i][j] %= mod return dp[-1][-1]
https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/822515/Python-3-or-DP-or-Explanation
12
You have n dice, and each dice has k faces numbered from 1 to k. Given three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7. Example 1: Input: n = 1, k = 6, target = 3 Output: 1 Explanation: You throw one die with 6 faces. There is only one way to get a sum of 3. Example 2: Input: n = 2, k = 6, target = 7 Output: 6 Explanation: You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1. Example 3: Input: n = 30, k = 30, target = 500 Output: 222616187 Explanation: The answer must be returned modulo 109 + 7. Constraints: 1 <= n, k <= 30 1 <= target <= 1000
Python 3 | DP | Explanation
1,400
number-of-dice-rolls-with-target-sum
0.536
idontknoooo
Medium
17,853
1,155
swap for longest repeated character substring
class Solution: def maxRepOpt1(self, text: str) -> int: first_occurence,last_occurence = {},{} ans,prev,count = 1,0,0 n = len(text) for i in range(n): if text[i] not in first_occurence: first_occurence[text[i]] = i last_occurence[text[i]] = i for i in range(n+1): if i < n and text[i] == text[prev]: count += 1 else: if first_occurence[text[prev]] < prev or last_occurence[text[prev]] > i : count += 1 ans = max(ans,count) count = 1 prev = i def someWork(item,before,after): count = 0 while before >= 0 and text[before] == item: count += 1 before -= 1 while after < n and text[after] == item: count += 1 after += 1 if first_occurence[item] <= before or last_occurence[item] >= after:count+=1 return count for i in range(1,n-1): ans = max(ans,someWork(text[i+1],i-1,i+1)) return ans
https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/2255000/PYTHON-or-AS-INTERVIEWER-WANTS-or-WITHOUT-ITERTOOLS-or-WELL-EXPLAINED-or
1
You are given a string text. You can swap two of the characters in the text. Return the length of the longest substring with repeated characters. Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3. Example 2: Input: text = "aaabaaa" Output: 6 Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6. Example 3: Input: text = "aaaaa" Output: 5 Explanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5. Constraints: 1 <= text.length <= 2 * 104 text consist of lowercase English characters only.
PYTHON | AS INTERVIEWER WANTS | WITHOUT ITERTOOLS | WELL EXPLAINED |
178
swap-for-longest-repeated-character-substring
0.454
reaper_27
Medium
17,915
1,156
find words that can be formed by characters
class Solution: # O(n^2) || O(1) # Runtime: 96ms 97.20% Memory: 14.5mb 84.92% def countCharacters(self, words: List[str], chars: str) -> int: ans=0 for word in words: for ch in word: if word.count(ch)>chars.count(ch): break else: ans+=len(word) return ans
https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2177578/Python3-O(n2)-oror-O(1)-Runtime%3A-96ms-97.20-Memory%3A-14.5mb-84.92
5
You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. Example 2: Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. Constraints: 1 <= words.length <= 1000 1 <= words[i].length, chars.length <= 100 words[i] and chars consist of lowercase English letters.
Python3 O(n^2) || O(1) Runtime: 96ms 97.20% Memory: 14.5mb 84.92%
350
find-words-that-can-be-formed-by-characters
0.677
arshergon
Easy
17,920
1,160
maximum level sum of a binary tree
class Solution: def maxLevelSum(self, root: TreeNode) -> int: queue = deque() #init a queue for storing nodes as we traverse the tree queue.append(root) #first node (level = 1) inserted #bfs = [] #just for understanding- this will be a bfs list to store nodes as we conduct the search, but we don't need it here. level_sum = 0 # for sum of each level level_nodes = 1 # for knowing when a particular level has ended sum_of_levels = [] #list to store all levels sum of nodes while queue: #begin BFS node = queue.popleft() #bfs.append(node) level_sum += node.val #add node if node.left: queue.append(node.left) if node.right: queue.append(node.right) level_nodes -= 1 #reduce level number by 1, as we popped out a node if level_nodes == 0: # if 0, then a level has ended, so calculate the sum sum_of_levels.append(level_sum) level_sum = 0 level_nodes = len(queue) return sum_of_levels.index(max(sum_of_levels)) + 1 #return index of max level sum
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/848959/BFS-Python-solution-with-comments!
1
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal. Example 1: Input: root = [1,7,0,7,-8,null,null] Output: 2 Explanation: Level 1 sum = 1. Level 2 sum = 7 + 0 = 7. Level 3 sum = 7 + -8 = -1. So we return the level with the maximum sum which is level 2. Example 2: Input: root = [989,null,10250,98693,-89388,null,null,null,-32127] Output: 2 Constraints: The number of nodes in the tree is in the range [1, 104]. -105 <= Node.val <= 105
BFS Python solution - with comments!
58
maximum-level-sum-of-a-binary-tree
0.661
tintsTy
Medium
17,951
1,161
as far from land as possible
class Solution: def maxDistance(self, grid: List[List[int]]) -> int: # The # of rows and # of cols M, N, result = len(grid), len(grid[0]), -1 # A list of valid points valid_points = {(i, j) for i in range(M) for j in range(N)} # A double-ended queue of "land" cells queue = collections.deque([(i, j) for i in range(M) for j in range(N) if grid[i][j] == 1]) # Check if all land, or all water, an edge case if len(queue) == M*N or len(queue) == 0: return -1 # BFS while queue: # One iteration here for _ in range(len(queue)): i, j = queue.popleft() for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if (x, y) not in valid_points: continue if grid[x][y] == 1: continue queue.append((x, y)) grid[x][y] = 1 # We mark water cells as land to avoid visiting them again # Increase the iteration/result count result += 1 return result
https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1158339/A-general-Explanation-w-Animation
8
Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1. The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|. Example 1: Input: grid = [[1,0,1],[0,0,0],[1,0,1]] Output: 2 Explanation: The cell (1, 1) is as far as possible from all the land with distance 2. Example 2: Input: grid = [[1,0,0],[0,0,0],[0,0,0]] Output: 4 Explanation: The cell (2, 2) is as far as possible from all the land with distance 4. Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1
A general Explanation w/ Animation
367
as-far-from-land-as-possible
0.486
dev-josh
Medium
17,962
1,162
last substring in lexicographical order
class Solution: def lastSubstring(self, s: str) -> str: S, L, a = [ord(i) for i in s] + [0], len(s), 1 M = max(S) I = [i for i in range(L) if S[i] == M] if len(I) == L: return s while len(I) != 1: b = [S[i + a] for i in I] M, a = max(b), a + 1 I = [I[i] for i, j in enumerate(b) if j == M] return s[I[0]:] - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/361321/Solution-in-Python-3-(beats-100)
3
Given a string s, return the last substring of s in lexicographical order. Example 1: Input: s = "abab" Output: "bab" Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab". Example 2: Input: s = "leetcode" Output: "tcode" Constraints: 1 <= s.length <= 4 * 105 s contains only lowercase English letters.
Solution in Python 3 (beats 100%)
742
last-substring-in-lexicographical-order
0.35
junaidmansuri
Hard
17,973
1,163
invalid transactions
class Solution: def invalidTransactions(self, transactions: List[str]) -> List[str]: invalid = [] for i, t1 in enumerate(transactions): name1, time1, amount1, city1 = t1.split(',') if int(amount1) > 1000: invalid.append(t1) continue for j, t2 in enumerate(transactions): if i != j: name2, time2, amount2, city2 = t2.split(',') if name1 == name2 and city1 != city2 and abs(int(time1) - int(time2)) <= 60: invalid.append(t1) break return invalid
https://leetcode.com/problems/invalid-transactions/discuss/670649/Simple-clean-python-only-10-lines
7
A transaction is possibly invalid if: the amount exceeds $1000, or; if it occurs within (and including) 60 minutes of another transaction with the same name in a different city. You are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction. Return a list of transactions that are possibly invalid. You may return the answer in any order. Example 1: Input: transactions = ["alice,20,800,mtv","alice,50,100,beijing"] Output: ["alice,20,800,mtv","alice,50,100,beijing"] Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too. Example 2: Input: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"] Output: ["alice,50,1200,mtv"] Example 3: Input: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"] Output: ["bob,50,1200,mtv"] Constraints: transactions.length <= 1000 Each transactions[i] takes the form "{name},{time},{amount},{city}" Each {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10. Each {time} consist of digits, and represent an integer between 0 and 1000. Each {amount} consist of digits, and represent an integer between 0 and 2000.
Simple clean python - only 10 lines
1,600
invalid-transactions
0.312
auwdish
Medium
17,979
1,169
compare strings by frequency of the smallest character
class Solution: def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]: def f(s): t = sorted(list(s))[0] return s.count(t) query = [f(x) for x in queries] word = [f(x) for x in words] m = [] for x in query: count = 0 for y in word: if y>x: count+=1 m.append(count) return m
https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/401039/Python-Simple-Code-Memory-efficient
14
Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = "dcce" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2. You are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words. Return an integer array answer, where each answer[i] is the answer to the ith query. Example 1: Input: queries = ["cbd"], words = ["zaaaz"] Output: [1] Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz"). Example 2: Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"] Output: [1,2] Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc"). Constraints: 1 <= queries.length <= 2000 1 <= words.length <= 2000 1 <= queries[i].length, words[i].length <= 10 queries[i][j], words[i][j] consist of lowercase English letters.
Python Simple Code Memory efficient
1,700
compare-strings-by-frequency-of-the-smallest-character
0.614
saffi
Medium
17,991
1,170
remove zero sum consecutive nodes from linked list
class Solution: def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(0,head) pre = 0 dic = {0: dummy} while head: pre+=head.val dic[pre] = head head = head.next head = dummy pre = 0 while head: pre+=head.val head.next = dic[pre].next head = head.next return dummy.next
https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/1701518/Easiest-Approach-oror-Clean-and-Concise-oror-Well-Explained
7
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.) Example 1: Input: head = [1,2,-3,3,1] Output: [3,1] Note: The answer [1,2,1] would also be accepted. Example 2: Input: head = [1,2,3,-3,4] Output: [1,2,4] Example 3: Input: head = [1,2,3,-3,-2] Output: [1] Constraints: The given linked list will contain between 1 and 1000 nodes. Each node in the linked list has -1000 <= node.val <= 1000.
📌📌 Easiest Approach || Clean & Concise || Well-Explained 🐍
282
remove-zero-sum-consecutive-nodes-from-linked-list
0.43
abhi9Rai
Medium
18,010
1,171
prime arrangements
class Solution: def numPrimeArrangements(self, n: int) -> int: # find number of prime indices # ways to arrange prime indices # is prime indices factorial # amount of non-prime indices is # n - prime indices # the factorial of non - prime indices # times the factorial of prime indices # is the amount of ways to arrange the # prime numbers and i be valid # use helper to find factorial of a number # use helper to see if a number is prime # time O(n ^ 2) space O(1) def isPrime(num): if num <= 1: return False for i in range(2, num // 2 + 1): if num % i == 0: return False return True def factorial(num): res = 1 for i in range(1, num + 1): res *= i return res primes = 0 for num in range(1, n + 1): if isPrime(num): primes += 1 return int(factorial(primes) * factorial(n - primes) % (10**9 + 7))
https://leetcode.com/problems/prime-arrangements/discuss/2794041/Find-product-between-factorial-of-primes-and-non-primes
0
Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.) (Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.) Since the answer may be large, return the answer modulo 10^9 + 7. Example 1: Input: n = 5 Output: 12 Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1. Example 2: Input: n = 100 Output: 682289015 Constraints: 1 <= n <= 100
Find product between factorial of primes & non-primes
4
prime-arrangements
0.537
andrewnerdimo
Easy
18,014
1,175
can make palindrome from substring
class Solution: def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]: prefix = [[0]*26] for c in s: elem = prefix[-1].copy() elem[ord(c)-97] += 1 prefix.append(elem) ans = [] for left, right, k in queries: cnt = sum(1&amp;(prefix[right+1][i] - prefix[left][i]) for i in range(26)) ans.append(cnt <= 2*k+1) return ans
https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/1201798/Python3-prefix-freq
2
You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter. If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false. Return a boolean array answer where answer[i] is the result of the ith query queries[i]. Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s. Example : Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]] Output: [true,false,false,true,true] Explanation: queries[0]: substring = "d", is palidrome. queries[1]: substring = "bc", is not palidrome. queries[2]: substring = "abcd", is not palidrome after replacing only 1 character. queries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab". queries[4]: substring = "abcda", could be changed to "abcba" which is palidrome. Example 2: Input: s = "lyb", queries = [[0,1,0],[2,2,1]] Output: [false,true] Constraints: 1 <= s.length, queries.length <= 105 0 <= lefti <= righti < s.length 0 <= ki <= s.length s consists of lowercase English letters.
[Python3] prefix freq
222
can-make-palindrome-from-substring
0.38
ye15
Medium
18,020
1,177
number of valid words for each puzzle
class Solution: def mask(self, word: str) -> int: result = 0 for ch in word: result |= 1 << (ord(ch)-ord('a')) return result def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]: word_count = Counter(self.mask(word) for word in words) result = [] for puzzle in puzzles: original_mask, first = self.mask(puzzle[1:]), self.mask(puzzle[0]) curr_mask, count = original_mask, word_count[first] while curr_mask: count += word_count[curr_mask|first] curr_mask = (curr_mask-1)&amp;original_mask result.append(count) return result
https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/1567415/Python-TrieBitmasking-Solutions-with-Explanation
16
With respect to a given puzzle string, a word is valid if both the following conditions are satisfied: word contains the first letter of puzzle. For each letter in word, that letter is in puzzle. For example, if the puzzle is "abcdefg", then valid words are "faced", "cabbage", and "baggage", while invalid words are "beefed" (does not include 'a') and "based" (includes 's' which is not in the puzzle). Return an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i]. Example 1: Input: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"] Output: [1,1,3,2,4,0] Explanation: 1 valid word for "aboveyz" : "aaaa" 1 valid word for "abrodyz" : "aaaa" 3 valid words for "abslute" : "aaaa", "asas", "able" 2 valid words for "absoryz" : "aaaa", "asas" 4 valid words for "actresz" : "aaaa", "asas", "actt", "access" There are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'. Example 2: Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"] Output: [0,1,3,2,0] Constraints: 1 <= words.length <= 105 4 <= words[i].length <= 50 1 <= puzzles.length <= 104 puzzles[i].length == 7 words[i] and puzzles[i] consist of lowercase English letters. Each puzzles[i] does not contain repeated characters.
[Python] Trie/Bitmasking Solutions with Explanation
596
number-of-valid-words-for-each-puzzle
0.465
zayne-siew
Hard
18,025
1,178
distance between bus stops
class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: a, b = min(start, destination), max(start, destination) return min(sum(distance[a:b]), sum(distance) - sum(distance[a:b]))
https://leetcode.com/problems/distance-between-bus-stops/discuss/377844/Python-Explanation
8
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops. Example 1: Input: distance = [1,2,3,4], start = 0, destination = 1 Output: 1 Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1. Example 2: Input: distance = [1,2,3,4], start = 0, destination = 2 Output: 3 Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3. Example 3: Input: distance = [1,2,3,4], start = 0, destination = 3 Output: 4 Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4. Constraints: 1 <= n <= 10^4 distance.length == n 0 <= start, destination < n 0 <= distance[i] <= 10^4
Python - Explanation
400
distance-between-bus-stops
0.541
nuclearoreo
Easy
18,028
1,184
day of the week
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: prev_year = year - 1 days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400 days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1]) days += day if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0): days += 1 return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][days % 7]
https://leetcode.com/problems/day-of-the-week/discuss/1084728/Python3-simple-solution
7
Given a date, return the corresponding day of the week for that date. The input is given as three integers representing the day, month and year respectively. Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. Example 1: Input: day = 31, month = 8, year = 2019 Output: "Saturday" Example 2: Input: day = 18, month = 7, year = 1999 Output: "Sunday" Example 3: Input: day = 15, month = 8, year = 1993 Output: "Sunday" Constraints: The given dates are valid dates between the years 1971 and 2100.
Python3 simple solution
333
day-of-the-week
0.576
EklavyaJoshi
Easy
18,049
1,185
maximum subarray sum with one deletion
class Solution: def maximumSum(self, arr: List[int]) -> int: n = len(arr) #maximum subarray starting from the last element i.e. backwards prefix_sum_ending = [float('-inf')]*n #maximum subarray starting from the first element i.e forwards prefix_sum_starting = [float('-inf')]*n prefix_sum_ending[n-1] = arr[n-1] prefix_sum_starting[0] = arr[0] for i in range(1,n): prefix_sum_starting[i] = max(prefix_sum_starting[i-1]+arr[i], arr[i]) for i in range(n-2,-1,-1): prefix_sum_ending[i] = max(prefix_sum_ending[i+1]+arr[i], arr[i]) max_without_deletion = max(prefix_sum_starting) max_with_deletion = float('-inf') for i in range(1,n-1): max_with_deletion = max(max_with_deletion, prefix_sum_starting[i-1]+prefix_sum_ending[i+1]) return max(max_without_deletion, max_with_deletion)
https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/1104253/Python-Kadane's-Algorithm-easy-solution
8
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be non-empty after deleting one element. Example 1: Input: arr = [1,-2,0,3] Output: 4 Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value. Example 2: Input: arr = [1,-2,-2,3] Output: 3 Explanation: We just choose [3] and it's the maximum sum. Example 3: Input: arr = [-1,-1,-1,-1] Output: -1 Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0. Constraints: 1 <= arr.length <= 105 -104 <= arr[i] <= 104
[Python] Kadane's Algorithm easy solution
522
maximum-subarray-sum-with-one-deletion
0.413
msd1311
Medium
18,058
1,186
make array strictly increasing
class Solution: def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int: arr2.sort() @cache def fn(i, prev): """Return min ops to make arr1[i:] increasing w/ given previous element.""" if i == len(arr1): return 0 ans = inf if (prev < arr1[i]): ans = fn(i+1, arr1[i]) k = bisect_right(arr2, prev) if k < len(arr2): ans = min(ans, 1 + fn(i+1, arr2[k])) return ans ans = fn(0, -inf) return ans if ans < inf else -1
https://leetcode.com/problems/make-array-strictly-increasing/discuss/1155655/Python3-top-down-dp
2
Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j]. If there is no way to make arr1 strictly increasing, return -1. Example 1: Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]. Example 2: Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]. Example 3: Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] Output: -1 Explanation: You can't make arr1 strictly increasing. Constraints: 1 <= arr1.length, arr2.length <= 2000 0 <= arr1[i], arr2[i] <= 10^9
[Python3] top-down dp
196
make-array-strictly-increasing
0.452
ye15
Hard
18,066
1,187
maximum number of balloons
class Solution: def maxNumberOfBalloons(self, text: str) -> int: c = collections.Counter(text) return min(c['b'],c['a'],c['l']//2,c['o']//2,c['n'])
https://leetcode.com/problems/maximum-number-of-balloons/discuss/1013213/2-Line-Python-using-Counter
8
Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. Example 1: Input: text = "nlaebolko" Output: 1 Example 2: Input: text = "loonbalxballpoon" Output: 2 Example 3: Input: text = "leetcode" Output: 0 Constraints: 1 <= text.length <= 104 text consists of lower case English letters only.
2 Line Python using Counter
385
maximum-number-of-balloons
0.618
majinlion
Easy
18,068
1,189
reverse substrings between each pair of parentheses
class Solution: def reverseParentheses(self, s: str) -> str: def solve(string): n = len(string) word = "" i = 0 while i <n: if string[i] == '(': new = "" count = 0 while True: count += 1 if string[i] == '(' else -1 if string[i] == ')' else 0 if count == 0: break new += string[i] i += 1 i += 1 word += solve(new[1:]) else: word += string[i] i += 1 return word[::-1] return solve(s)[::-1]
https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2290806/PYTHON-SOL-or-RECURSION-AND-STACK-SOL-or-DETAILED-EXPLANATION-WITH-PICTRUE-or
4
You are given a string s that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should not contain any brackets. Example 1: Input: s = "(abcd)" Output: "dcba" Example 2: Input: s = "(u(love)i)" Output: "iloveu" Explanation: The substring "love" is reversed first, then the whole string is reversed. Example 3: Input: s = "(ed(et(oc))el)" Output: "leetcode" Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. Constraints: 1 <= s.length <= 2000 s only contains lower case English characters and parentheses. It is guaranteed that all parentheses are balanced.
PYTHON SOL | RECURSION AND STACK SOL | DETAILED EXPLANATION WITH PICTRUE |
123
reverse-substrings-between-each-pair-of-parentheses
0.658
reaper_27
Medium
18,100
1,190
k concatenation maximum sum
class Solution: def kadane(self, nums): for i in range(1, len(nums)): if nums[i-1] > 0: nums[i] += nums[i-1] return max(max(nums), 0) def kConcatenationMaxSum(self, arr: List[int], k: int) -> int: sums = sum(arr) mod = 10**9 + 7 if k == 1: return self.kadane(arr) % (mod) if sums > 0: return (self.kadane(arr+arr) + (k-2)*sums) % (mod) else: return self.kadane(arr+arr) % (mod)
https://leetcode.com/problems/k-concatenation-maximum-sum/discuss/2201976/Python-easy-to-read-and-understand-or-kadane
2
Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0. As the answer can be very large, return the answer modulo 109 + 7. Example 1: Input: arr = [1,2], k = 3 Output: 9 Example 2: Input: arr = [1,-2,1], k = 5 Output: 2 Example 3: Input: arr = [-1,-2], k = 7 Output: 0 Constraints: 1 <= arr.length <= 105 1 <= k <= 105 -104 <= arr[i] <= 104
Python easy to read and understand | kadane
147
k-concatenation-maximum-sum
0.239
sanial2001
Medium
18,122
1,191
critical connections in a network
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: dic = collections.defaultdict(list) for c in connections: u, v = c dic[u].append(v) dic[v].append(u) timer = 0 depth, lowest, parent, visited = [float("inf")]*n, [float("inf")]*n, [float("inf")]*n, [False]*n res = [] def find(u): nonlocal timer visited[u] = True depth[u], lowest[u] = timer, timer timer += 1 for v in dic[u]: if not visited[v]: parent[v] = u find(v) if lowest[v]>depth[u]: res.append([u,v]) if parent[u]!=v: lowest[u] = min(lowest[u], lowest[v]) find(0) return res
https://leetcode.com/problems/critical-connections-in-a-network/discuss/382440/Python-DFS-Tree-Solution-(O(V%2BE)-complexity)
16
There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network. A critical connection is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. Example 1: Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]] Output: [[1,3]] Explanation: [[3,1]] is also accepted. Example 2: Input: n = 2, connections = [[0,1]] Output: [[0,1]] Constraints: 2 <= n <= 105 n - 1 <= connections.length <= 105 0 <= ai, bi <= n - 1 ai != bi There are no repeated connections.
Python DFS-Tree Solution (O(V+E) complexity)
5,500
critical-connections-in-a-network
0.545
ywen1995
Hard
18,130
1,192
minimum absolute difference
class Solution: def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: arr.sort() m = float('inf') out = [] for i in range(1, len(arr)): prev = arr[i - 1] curr = abs(prev - arr[i]) if curr < m: out = [[prev, arr[i]]] m = curr elif curr == m: out.append([prev, arr[i]]) return out
https://leetcode.com/problems/minimum-absolute-difference/discuss/569795/Easy-to-Understand-or-Faster-or-Simple-or-Python-Solution
16
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows a, b are from arr a < b b - a equals to the minimum absolute difference of any two elements in arr Example 1: Input: arr = [4,2,1,3] Output: [[1,2],[2,3],[3,4]] Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. Example 2: Input: arr = [1,3,6,10,15] Output: [[1,3]] Example 3: Input: arr = [3,8,-10,23,19,-4,-14,27] Output: [[-14,-10],[19,23],[23,27]] Constraints: 2 <= arr.length <= 105 -106 <= arr[i] <= 106
Easy to Understand | Faster | Simple | Python Solution
1,300
minimum-absolute-difference
0.697
Mrmagician
Easy
18,141
1,200
ugly number iii
class Solution: def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: # inclusion-exclusion principle ab = a*b//gcd(a, b) bc = b*c//gcd(b, c) ca = c*a//gcd(c, a) abc = ab*c//gcd(ab, c) lo, hi = 1, n*min(a, b, c) while lo < hi: mid = lo + hi >> 1 if mid//a + mid//b + mid//c - mid//ab - mid//bc - mid//ca + mid//abc < n: lo = mid + 1 else: hi = mid return lo
https://leetcode.com/problems/ugly-number-iii/discuss/723589/Python3-inconsistent-definition-of-%22ugly-numbers%22
33
An ugly number is a positive integer that is divisible by a, b, or c. Given four integers n, a, b, and c, return the nth ugly number. Example 1: Input: n = 3, a = 2, b = 3, c = 5 Output: 4 Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4. Example 2: Input: n = 4, a = 2, b = 3, c = 4 Output: 6 Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6. Example 3: Input: n = 5, a = 2, b = 11, c = 13 Output: 10 Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10. Constraints: 1 <= n, a, b, c <= 109 1 <= a * b * c <= 1018 It is guaranteed that the result will be in range [1, 2 * 109].
[Python3] inconsistent definition of "ugly numbers"
1,000
ugly-number-iii
0.285
ye15
Medium
18,183
1,201
smallest string with swaps
class Solution: def union(self, a, b): self.parent[self.find(a)] = self.find(b) def find(self, a): if self.parent[a] != a: self.parent[a] = self.find(self.parent[a]) return self.parent[a] def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: # 1. Union-Find self.parent = list(range(len(s))) for a, b in pairs: self.union(a, b) # 2. Grouping group = defaultdict(lambda: ([], [])) for i, ch in enumerate(s): parent = self.find(i) group[parent][0].append(i) group[parent][1].append(ch) # 3. Sorting res = [''] * len(s) for ids, chars in group.values(): ids.sort() chars.sort() for ch, i in zip(chars, ids): res[i] = ch return ''.join(res)
https://leetcode.com/problems/smallest-string-with-swaps/discuss/1985185/Python3-UNION-FIND-()**-Explained
55
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to after using the swaps. Example 1: Input: s = "dcab", pairs = [[0,3],[1,2]] Output: "bacd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[1] and s[2], s = "bacd" Example 2: Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]] Output: "abcd" Explaination: Swap s[0] and s[3], s = "bcad" Swap s[0] and s[2], s = "acbd" Swap s[1] and s[2], s = "abcd" Example 3: Input: s = "cba", pairs = [[0,1],[1,2]] Output: "abc" Explaination: Swap s[0] and s[1], s = "bca" Swap s[1] and s[2], s = "bac" Swap s[0] and s[1], s = "abc" Constraints: 1 <= s.length <= 10^5 0 <= pairs.length <= 10^5 0 <= pairs[i][0], pairs[i][1] < s.length s only contains lower case English letters.
✔️ [Python3] UNION-FIND (❁´▽`❁)*✲゚*, Explained
2,700
smallest-string-with-swaps
0.576
artod
Medium
18,188
1,202
sort items by groups respecting dependencies
class Solution: def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]: for i in range(n): if group[i] == -1: group[i] = i + m # re-group graph0 = {} # digraph of groups indeg0 = [0]*(m+n) # indegree of groups graph1 = {} # digrpah of items indeg1 = [0]*n # indegree of items for i, x in enumerate(beforeItems): for xx in x: if group[xx] != group[i]: graph0.setdefault(group[xx], []).append(group[i]) indeg0[group[i]] += 1 graph1.setdefault(xx, []).append(i) indeg1[i] += 1 def fn(graph, indeg): """Return topological sort of graph using Kahn's algo.""" ans = [] stack = [k for k in range(len(indeg)) if indeg[k] == 0] while stack: n = stack.pop() ans.append(n) for nn in graph.get(n, []): indeg[nn] -= 1 if indeg[nn] == 0: stack.append(nn) return ans tp0 = fn(graph0, indeg0) if len(tp0) != len(indeg0): return [] tp1 = fn(graph1, indeg1) if len(tp1) != len(indeg1): return [] mp0 = {x: i for i, x in enumerate(tp0)} mp1 = {x: i for i, x in enumerate(tp1)} return sorted(range(n), key=lambda x: (mp0[group[x]], mp1[x]))
https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/discuss/1149266/Python3-topological-sort
2
There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it. Return a sorted list of the items such that: The items that belong to the same group are next to each other in the sorted list. There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item). Return any solution if there is more than one solution and return an empty list if there is no solution. Example 1: Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]] Output: [6,3,4,1,5,2,0,7] Example 2: Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]] Output: [] Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list. Constraints: 1 <= m <= n <= 3 * 104 group.length == beforeItems.length == n -1 <= group[i] <= m - 1 0 <= beforeItems[i].length <= n - 1 0 <= beforeItems[i][j] <= n - 1 i != beforeItems[i][j] beforeItems[i] does not contain duplicates elements.
[Python3] topological sort
123
sort-items-by-groups-respecting-dependencies
0.506
ye15
Hard
18,203
1,203
unique number of occurrences
class Solution: def uniqueOccurrences(self, A: List[int]) -> bool: return (lambda x: len(x) == len(set(x)))(collections.Counter(A).values()) - Junaid Mansuri (LeetCode ID)@hotmail.com
https://leetcode.com/problems/unique-number-of-occurrences/discuss/393086/Solution-in-Python-3-(one-line)-(beats-100.00-)
13
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: Input: arr = [1,2] Output: false Example 3: Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true Constraints: 1 <= arr.length <= 1000 -1000 <= arr[i] <= 1000
Solution in Python 3 (one line) (beats 100.00 %)
2,600
unique-number-of-occurrences
0.709
junaidmansuri
Easy
18,204
1,207
get equal substrings within budget
class Solution: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: n = len(s) cost,start,ans = 0,0,0 for i in range(n): diff = abs(ord(s[i]) - ord(t[i])) if cost + diff <= maxCost: # we can increase our sliding window cost += diff else: # we are unable to increase our sliding window ans = max(ans,i - start) while True: cost -= abs(ord(s[start]) - ord(t[start])) start += 1 if cost + diff <= maxCost: break if cost + diff > maxCost: start = i + 1 else: cost += diff ans = max(ans,n - start) return ans
https://leetcode.com/problems/get-equal-substrings-within-budget/discuss/2312556/PYTHON-or-SLIDING-WINDOW-or-O(n)-or-WELL-EXPLAINED-or-EASY-or
1
You are given two strings s and t of the same length and an integer maxCost. You want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters). Return the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0. Example 1: Input: s = "abcd", t = "bcdf", maxCost = 3 Output: 3 Explanation: "abc" of s can change to "bcd". That costs 3, so the maximum length is 3. Example 2: Input: s = "abcd", t = "cdef", maxCost = 3 Output: 1 Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1. Example 3: Input: s = "abcd", t = "acde", maxCost = 0 Output: 1 Explanation: You cannot make any change, so the maximum length is 1. Constraints: 1 <= s.length <= 105 t.length == s.length 0 <= maxCost <= 106 s and t consist of only lowercase English letters.
PYTHON | SLIDING WINDOW | O(n) | WELL EXPLAINED | EASY |
36
get-equal-substrings-within-budget
0.478
reaper_27
Medium
18,248
1,208
remove all adjacent duplicates in string ii
class Solution: def removeDuplicates(self, s: str, k: int) -> str: stck = [['$', 0]] # a placeholder to mark stack is empty. This eliminates the need to do an empty check later for c in s: if stck[-1][0] == c: stck[-1][1]+=1 # update occurences count of top element if it matches current character if stck[-1][1] == k: stck.pop() else: stck.append([c, 1]) return ''.join(c * cnt for c, cnt in stck)
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/2012318/Python-Simple-One-Pass-Solution
81
You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. Example 1: Input: s = "abcd", k = 2 Output: "abcd" Explanation: There's nothing to delete. Example 2: Input: s = "deeedbbcccbdaa", k = 3 Output: "aa" Explanation: First delete "eee" and "ccc", get "ddbbbdaa" Then delete "bbb", get "dddaa" Finally delete "ddd", get "aa" Example 3: Input: s = "pbbcggttciiippooaais", k = 2 Output: "ps" Constraints: 1 <= s.length <= 105 2 <= k <= 104 s only contains lowercase English letters.
✅ Python Simple One Pass Solution
4,300
remove-all-adjacent-duplicates-in-string-ii
0.56
constantine786
Medium
18,254
1,209
minimum moves to reach target with rotations
class Solution: def minimumMoves(self, G: List[List[int]]) -> int: N, S, T, V, c = len(G), [(0, 0, 'h')], [], set(), 0 while S: for i in S: if i in V: continue if i == (N-1, N-2, 'h'): return c (a, b, o), _ = i, V.add(i) if o == 'h': if b + 2 != N and G[a][b+2] == 0: T.append((a, b+1, o)) if a + 1 != N and G[a+1][b] == 0 and G[a+1][b+1] == 0: T.append((a+1, b, o)), T.append((a, b, 'v')) elif o == 'v': if a + 2 != N and G[a+2][b] == 0: T.append((a+1, b, o)) if b + 1 != N and G[a][b+1] == 0 and G[a+1][b+1] == 0: T.append((a, b+1, o)), T.append((a, b, 'h')) S, T, c = T, [], c + 1 return -1
https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/393042/Python-3-(BFS-DFS-and-DP)-(With-Explanation)-(beats-100.00)
8
In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1). In one move the snake can: Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c). Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1). Return the minimum number of moves to reach the target. If there is no way to reach the target, return -1. Example 1: Input: grid = [[0,0,0,0,0,1], [1,1,0,0,1,0], [0,0,0,0,1,1], [0,0,1,0,1,0], [0,1,1,0,0,0], [0,1,1,0,0,0]] Output: 11 Explanation: One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down]. Example 2: Input: grid = [[0,0,1,1,1,1], [0,0,0,0,1,1], [1,1,0,0,0,1], [1,1,1,0,0,1], [1,1,1,0,0,1], [1,1,1,0,0,0]] Output: 9 Constraints: 2 <= n <= 100 0 <= grid[i][j] <= 1 It is guaranteed that the snake starts at empty cells.
Python 3 (BFS, DFS, and DP) (With Explanation) (beats 100.00%)
896
minimum-moves-to-reach-target-with-rotations
0.491
junaidmansuri
Hard
18,311
1,210