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...
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 e...
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) + ...
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 number...
✔️ [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) ...
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 ...
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)...
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 ...
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, th...
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:...
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,nul...
✅ [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: ...
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 ...
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] ...
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...
[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 rang...
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. ...
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 retu...
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]) ...
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 c...
[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 r...
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 ...
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): ...
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 ...
[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 ...
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 a...
[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 = ...
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...
[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],...
[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) ...
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 cont...
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)) ...
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...
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 movi...
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 ...
[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 += direct...
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...
✅ [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,...
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 gard...
**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 r...
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...
[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...
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" Ex...
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 ...
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 ...
[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 ...
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 ...
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...
✔️ 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 + stone...
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 ...
[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 tab...
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 heig...
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 += custo...
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 o...
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 num...
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: ...
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 rear...
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,...
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...
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],...
🐍 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: ...
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...
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][...
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 ex...
| 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 gi...
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 ...
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...
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...
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: I...
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) ...
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 q...
[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...
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 ...
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 t...
[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...
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...
✅ 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] = ...
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", ...
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)) / ...
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...
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 th...
❤ [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....
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...
[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) ...
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-deli...
[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 th...
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 ...
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() ...
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 t...
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 ...
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 t...
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...
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 lo...
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 I...
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]...
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: ...
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...
[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) ...
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 a...
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...
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...
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: ...
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 se...
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+...
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 o...
📌📌 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...
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 rep...
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 a...
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 equivale...
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) d...
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 ...
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: ...
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 subtre...
📌📌 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...
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...
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 ...
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: ...
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...
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): ...
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 ...
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] ...
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 tu...
[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) ...
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. ...
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) ...
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[...
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) + ...
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...
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 h...
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 <...
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] =...
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) ...
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,...
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 ...
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 characte...
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: ...
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 stri...
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...
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. Leve...
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 ...
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...
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 enumera...
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.l...
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 ...
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...
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...
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. Fo...
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 ...
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.) Exam...
📌📌 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 ...
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. ...
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: ...
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 ...
[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) ...
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 "be...
[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 ...
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 >...
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, mon...
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')...
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 p...
[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 ...
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...
[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...
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: ...
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" E...
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:...
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 a...
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 ...
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...
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]]] ...
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 Ex...
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: m...
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...
[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]]) -> st...
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 usin...
✔️ [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 ...
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 tha...
[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...
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 +...
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 ...
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 ...
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 ...
✅ 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] ==...
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...
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