post_href
stringlengths
57
213
python_solutions
stringlengths
71
22.3k
slug
stringlengths
3
77
post_title
stringlengths
1
100
user
stringlengths
3
29
upvotes
int64
-20
1.2k
views
int64
0
60.9k
problem_title
stringlengths
3
77
number
int64
1
2.48k
acceptance
float64
0.14
0.91
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2827826/5-LINE-oror-SIMPLE-SOLUTION-oror-FORMULA-BASED-oror-EASSY-TO-UNDERSTAND
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if len(coordinates) == 2: return True (x1, y1), (x2, y2) = coordinates[:2] for (x, y) in coordinates[2:]: if (y2 - y1) * (x - x2) != (y - y2) * (x2 - x1): return False return True
check-if-it-is-a-straight-line
5 LINE || SIMPLE SOLUTION || FORMULA BASED || EASSY TO UNDERSTAND
thezealott
0
4
check if it is a straight line
1,232
0.41
Easy
18,500
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2811202/Check-If-It-Is-a-Straight-Line-or-Python-or-With-an-explanation
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: tail = len(coordinates) if tail == 2: return True for coord in coordinates[1: tail - 1]: if not (coord[0] - coordinates[0][0]) * (coordinates[-1][1] - coordinates[0][1]) == (coord[1] - coordinates[0][1]) * (coordinates[-1][0] - coordinates[0][0]): return False return True
check-if-it-is-a-straight-line
Check If It Is a Straight Line | Python | With an explanation
SnLn
0
2
check if it is a straight line
1,232
0.41
Easy
18,501
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2726568/Python-Solution-Simple-readable-code
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: (x1,y1),(x2,y2) = coordinates[:2] for i in range(2,len(coordinates)): (x,y) = coordinates[i] # why we have not use the direct formula i.e division because it can give zero divisor #so instead of dividing we will cross multiply the slope equation to formulate the answer if (y1-y)*(x2-x1)!=(x1-x)*(y2-y1): return False return True
check-if-it-is-a-straight-line
Python Solution Simple readable code
nidhi_nishad26
0
6
check if it is a straight line
1,232
0.41
Easy
18,502
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2677294/Python-%2B-geometry
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: x0,y0=coordinates[0] x1,y1=coordinates[1] return all([(x-x0)*(y-y1)==(y-y0)*(x-x1) for x,y in coordinates[2:]])
check-if-it-is-a-straight-line
Python + geometry
Leox2022
0
6
check if it is a straight line
1,232
0.41
Easy
18,503
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2538667/Python-slope-solution-clear-explanation-O(n)-time-complexity.
class Solution: def checkStraightLine(self, coordinates): numerator = coordinates[1][1]- coordinates[0][1] denominator = coordinates[1][0]-coordinates[0][0] if denominator != 0: slope = numerator/denominator for r in range(2,len(coordinates)): # O(n) nextNumerator = coordinates[r][1]-coordinates[0][1] nextDenominator = coordinates[r][0]-coordinates[0][0] if nextDenominator == 0: return False nextSlope = nextNumerator/nextDenominator if nextSlope != slope: return False return True else: for r in range(2, len(coordinates)): # O(n) nextDenominator = coordinates[r][0]-coordinates[0][0] if nextDenominator != 0: return False return True
check-if-it-is-a-straight-line
Python slope solution, clear explanation, O(n) time complexity.
OsamaRakanAlMraikhat
0
106
check if it is a straight line
1,232
0.41
Easy
18,504
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2053443/python3-List-Comprehension
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: x0,y0=coordinates[0] x1,y1=coordinates[1] if all( False if (point[0]-x1)*(y1-y0)!=(point[1]-y1)*(x1-x0) else True for i, point in enumerate(coordinates) ): return True
check-if-it-is-a-straight-line
python3 List Comprehension
kedeman
0
79
check if it is a straight line
1,232
0.41
Easy
18,505
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/2037837/Python-simple-and-faster-solution
class Solution: def checkStraightLine(self, c: List[List[int]]) -> bool: test = (c[1][1]-c[0][1])/(c[1][0]-c[0][0]) if (c[1][0]-c[0][0]) else float('inf') for i in range(2, len(c)) : curr = (c[i][1]-c[i-1][1])/(c[i][0]-c[i-1][0]) if (c[i][0]-c[i-1][0]) else float('inf') if curr != test : return False return True
check-if-it-is-a-straight-line
Python simple and faster solution
runtime-terror
0
159
check if it is a straight line
1,232
0.41
Easy
18,506
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1851822/Python3-solution-using-line-passing-through-2-points-formula
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: coordinates.sort() x1 = coordinates[0][0] y1 = coordinates[0][1] x2 = coordinates[1][0] y2 = coordinates[1][1] for i in coordinates: x = i[0] y = i[1] if (x - x1) * (y2 - y1) != (y - y1) * (x2 - x1): return False return True
check-if-it-is-a-straight-line
Python3 solution using line passing through 2 points formula
alishak1999
0
80
check if it is a straight line
1,232
0.41
Easy
18,507
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1813609/4-Lines-Python-Solution-oror-55-Faster-oror-Memory-less-than-65
class Solution: def checkStraightLine(self, c: List[List[int]]) -> bool: if len(c)==2: return True for i in range(2,len(c)): if (c[1][1]-c[0][1])*(c[i][0]-c[0][0]) != (c[1][0]-c[0][0])*(c[i][1]-c[0][1]): return False return True
check-if-it-is-a-straight-line
4-Lines Python Solution || 55% Faster || Memory less than 65%
Taha-C
0
59
check if it is a straight line
1,232
0.41
Easy
18,508
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1781035/python3-solution-67ms-(with-explanation)-O(n)-time-and-O(1)-space
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: x1, y1 = coordinates[0][0], coordinates[0][1] x2, y2 = coordinates[1][0], coordinates[1][1] if x2 != x1: slope = (y2-y1)/(x2-x1) c = y2 - (slope*x2) #y = slope*x + c for coordinate in coordinates: x, y = coordinate[0], coordinate[1] Y = slope*x + c if Y != y: return False return True else: #equation: x = c i.e x1 or x2 in this case i.e the line is vertical/parallel to y axis => x should remain constant for coordinate in coordinates: x = coordinate[0] if x != x2: return False return True ```
check-if-it-is-a-straight-line
python3 solution 67ms (with explanation) O(n) time and O(1) space
kgrv
0
86
check if it is a straight line
1,232
0.41
Easy
18,509
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1724699/Python-dollarolution
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if coordinates[0][0] - coordinates[1][0] != 0: m = (coordinates[0][1] - coordinates[1][1])/(coordinates[0][0] - coordinates[1][0]) c = coordinates[0][1] - (coordinates[0][0] * m) for i in coordinates[2:]: if i[1] == m * i[0] + c: continue else: return False return True else: for i in coordinates[2:]: if i[0] == coordinates[0][0]: continue else: return False return True
check-if-it-is-a-straight-line
Python $olution
AakRay
0
161
check if it is a straight line
1,232
0.41
Easy
18,510
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1619213/python3-ymb%2Bb-watch-out-for-div-by-zero
class Solution: def checkStraightLine(self, c: List[List[int]]) -> bool: """ y=mx+b b = point[0][1] for x= m=(y2-y1)/(x2-x1) if point[i][1]==m*point[i][0]+b """ if len(functools.reduce(lambda a,b:a&b,[{c[i][0]} for i in range(len(c))])) ==1:return True if len(functools.reduce(lambda a,b:a&b,[{c[i][1]} for i in range(len(c))])) ==1:return True if (c[1][0]-c[0][0] )==0:return False m=(c[1][1]-c[0][1])/(c[1][0]-c[0][0]);b=c[0][1] return all([(m*(c[i][0]-c[0][0])+b)==c[i][1] for i in range(1,len(c))])
check-if-it-is-a-straight-line
python3 y=mb+b watch out for div by zero
mikekaufman4
0
91
check if it is a straight line
1,232
0.41
Easy
18,511
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1499322/Python-Slopes
class Solution: def checkStraightLine(self, A: List[List[int]]) -> bool: results = [] for i in A: for j in A: try: results.append( (i[1]-j[1]) / (i[0]-j[0]) ) except: pass return all([ i == results[0] for i in results ])
check-if-it-is-a-straight-line
[Python] Slopes
dev-josh
0
114
check if it is a straight line
1,232
0.41
Easy
18,512
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/633225/Intuitive-approach-by-checking-slope
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if len(coordinates) == 2: return True def get_slope(p1, p2): try: return (p2[1] - p1[1]) / (p2[0] - p1[0]) except: # Divided by zero. Use None to represent this case return None pp = coordinates[1] ''' Previous point ''' slope = get_slope(coordinates[0], pp) ''' The slope of first two points''' for np in coordinates[2:]: if get_slope(pp, np) != slope: return False pp = np return True
check-if-it-is-a-straight-line
Intuitive approach by checking slope
puremonkey2001
0
105
check if it is a straight line
1,232
0.41
Easy
18,513
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/621540/Python-Check-slopes-supereasy-to-understand
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: count = set() for i in range(1, len(coordinates)): if coordinates[i][0] - coordinates[i-1][0] == 0: count.add( float('inf')) else: count.add((coordinates[i][1]-coordinates[i-1][1]) / (coordinates[i][0]-coordinates[i-1][0])) return len(count) == 1
check-if-it-is-a-straight-line
[Python] Check slopes, supereasy to understand
syhwawa
0
69
check if it is a straight line
1,232
0.41
Easy
18,514
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/621257/Easy-understand-or-With-Explanation-or-O(n)
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: # y1 = kx1 + b # y2 = kx2 + b # k = (y1-y2)/(x1-x2), x1 !=x2 # b = y1 - x1 * (y1-y2)/(x1-x2) x1,y1 = coordinates[0] x2,y2 = coordinates[1] # if x1 == x2 if x1 == x2: for point in coordinates: if point[0] != x1: return False # if x1 != x2 k = (y1-y2)/(x1-x2) b = y1 - (x1 * (y1-y2)/(x1-x2)) for point in coordinates: x,y = point if y != k*x + b: return False return True
check-if-it-is-a-straight-line
๐Ÿ”ฅEasy-understand | With Explanation | O(n)๐Ÿ”ฅ
Get-Schwifty
0
169
check if it is a straight line
1,232
0.41
Easy
18,515
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/620794/Python3Java-a-concise-implementation
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: x0, y0 = coordinates[0] x1, y1 = coordinates[1] for x, y in coordinates[2:]: if (y1-y0)*(x-x0) != (y-y0)*(x1-x0): return False return True
check-if-it-is-a-straight-line
[Python3/Java] a concise implementation
ye15
0
42
check if it is a straight line
1,232
0.41
Easy
18,516
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/620228/Python3-3-lines-slope-based-solution-Check-If-It-Is-a-Straight-Line
class Solution: def checkStraightLine(self, coords: List[List[int]]) -> bool: if len(set(x for x, y in coords)) == 1: return True if len(set(x for x, y in coords)) < len(coords): return False return len(set((p1[1] - p2[1])/(p1[0] - p2[0]) for p1, p2 in zip(coords, coords[1:]))) == 1
check-if-it-is-a-straight-line
Python3 3 lines slope-based solution - Check If It Is a Straight Line
r0bertz
0
166
check if it is a straight line
1,232
0.41
Easy
18,517
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/620034/PYTHON-3-Simple-Approach-or-Using-Slope-or-Easy-to-Read
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: if len(coordinates) == 2: return True if coordinates[1][0] == coordinates[0][0]: first_slope = -1 else: first_slope = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]) for i in range(2 , len(coordinates)): if (coordinates[i][1] - coordinates[0][1]) / (coordinates[i][0] - coordinates[0][0]) != first_slope: return False return True
check-if-it-is-a-straight-line
[PYTHON 3] Simple Approach | Using Slope | Easy to Read
mohamedimranps
0
56
check if it is a straight line
1,232
0.41
Easy
18,518
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/620014/Python-Beats-95-and-memory-less-than-100-or-Time-O(n)-Space-O(1)
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: """ Brute Force Solution 1. find slope between each (xi, yi) and (x_i+1, y_i+1), i from [0, n-2] 2. if slopes is different than previously stored [between (x_i-1, y_i-1) --> (x_i, y_i)] slope --> return False. """ for idx in range(len(coordinates) - 1): x_i, y_i = coordinates[idx] x_i_next, y_i_next = coordinates[idx+1] if x_i_next == x_i: slope = float('inf') else: slope = (y_i_next - y_i)/(x_i_next - x_i) if idx > 0 and slope != prev_slope: return False prev_slope = slope return True
check-if-it-is-a-straight-line
[Python] Beats 95% and memory less than 100% | Time O(n), Space O(1)
var42
0
92
check if it is a straight line
1,232
0.41
Easy
18,519
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/558882/Python-solution-easy-to-undestand.-90-fast-100-memory.
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: same_slop = True last_slop = None intial_point = coordinates[0] for point in coordinates[1:]: try: slop = (point[1] - intial_point[1])/(point[0] - intial_point[0]) except ZeroDivisionError: slop = float(inf) if last_slop== None:last_slop = slop elif slop == last_slop:continue else: same_slop = False break return same_slop
check-if-it-is-a-straight-line
Python solution easy to undestand. 90% fast 100% memory.
sudhirkumarshahu80
0
181
check if it is a straight line
1,232
0.41
Easy
18,520
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/424760/Python-beats-100-simple-understanding-math-code
class Solution: def checkStraightLine(self, coordinates: List[List[int]]) -> bool: try: m = (coordinates[0][1] - coordinates[1][1])/(coordinates[0][0] - coordinates[1][0]) return len(set([y-m*x for x,y in coordinates]))==1 except: return len(set([x for x,y in coordinates]))==1
check-if-it-is-a-straight-line
Python beats 100% simple understanding math code
saffi
0
234
check if it is a straight line
1,232
0.41
Easy
18,521
https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/409057/Python-3-(six-lines)-(beats-~99)
class Solution: def checkStraightLine(self, C: List[List[int]]) -> bool: if len(set(i[0] for i in C)) == 1: return True if len(set(i[0] for i in C)) < len(C): return False m, [x1, y1] = (C[1][1]-C[0][1])//(C[1][0]-C[0][0]), C.pop(0) for x,y in C: if (y-y1)/(x-x1) != m: return False return True - Junaid Mansuri
check-if-it-is-a-straight-line
Python 3 (six lines) (beats ~99%)
junaidmansuri
0
432
check if it is a straight line
1,232
0.41
Easy
18,522
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1196525/Python3-simple-solution-using-%22startswith%22-method
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: ans = [] for i, path in enumerate(sorted(folder)): if i == 0 or not path.startswith(ans[-1] + "/"): ans.append(path) return ans
remove-sub-folders-from-the-filesystem
Python3 simple solution using "startswith" method
EklavyaJoshi
3
130
remove sub folders from the filesystem
1,233
0.654
Medium
18,523
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1264193/Python3-Brute-Forces-Readable-Solution
class Solution: def removeSubfolders(self, arr: List[str]) -> List[str]: arr.sort(key=len) files = [] while arr: curr = arr.pop(0) temp = [] for i in arr: if(curr + '/' in i and i.index(curr + '/') == 0): pass else: temp.append(i) files.append(curr) arr = temp return files
remove-sub-folders-from-the-filesystem
[Python3] Brute Forces Readable Solution
VoidCupboard
1
35
remove sub folders from the filesystem
1,233
0.654
Medium
18,524
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1090856/Python3-greedy
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: ans = [] for x in sorted(folder): if not ans or not x.startswith(ans[-1]+"/"): ans.append(x) return ans
remove-sub-folders-from-the-filesystem
[Python3] greedy
ye15
1
63
remove sub folders from the filesystem
1,233
0.654
Medium
18,525
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/409183/8-lines-python-solution-with-explain
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: # Sort, will guarantee the "/a" will comes before "/a/b" and they appear in sequence folder.sort() res = [] res.append(folder[0]) for i in range(1, len(folder)): # Append "/" to the previous is for the case: ["/a/b/c","/a/b/ca"] if folder[i].startswith(res[-1] + "/"): continue res.append(folder[i]) return res
remove-sub-folders-from-the-filesystem
8 lines python solution with explain
DPbacteria
1
259
remove sub folders from the filesystem
1,233
0.654
Medium
18,526
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/2847830/Python-(Simple-Maths)
class Solution: def removeSubfolders(self, folder): result = [] for i in sorted(folder): if not result or not i.startswith(result[-1] + "/"): result.append(i) return result
remove-sub-folders-from-the-filesystem
Python (Simple Maths)
rnotappl
0
1
remove sub folders from the filesystem
1,233
0.654
Medium
18,527
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/2816297/Trie-Intuitive-Python-Solution
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: self.result = [] trie = Trie() folder.sort() for val in folder: val = val.split("/") if trie.insert(val): self.result.append("/".join(val)) return self.result class TrieNode: def __init__(self, ch = None): self.ch = ch self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): cur = self.root for i in range(1, len(word)): c = word[i] if c not in cur.children: cur.children[c] = TrieNode(c) elif cur.children[c].is_end: return False cur = cur.children[c] cur.is_end = True return True
remove-sub-folders-from-the-filesystem
Trie, Intuitive, Python Solution
Ayomipo
0
1
remove sub folders from the filesystem
1,233
0.654
Medium
18,528
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/2331950/PYTHON-or-SORTING-%2B-HASHMAP-or-EXPLANATION-WITH-DETAILS-or-EASY-or
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: n , folders , ans = len(folder) , {} , [] folder.sort() for string in folder: string += '/' tmp , flag = "" , True for i in string: if i == '/' and tmp in folders: flag = False break tmp += i if flag == False:continue tmp = tmp[:len(tmp)-1] folders[tmp] = True ans.append(tmp) return ans
remove-sub-folders-from-the-filesystem
PYTHON | SORTING + HASHMAP | EXPLANATION WITH DETAILS | EASY |
reaper_27
0
44
remove sub folders from the filesystem
1,233
0.654
Medium
18,529
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1902333/Neat-Python-Trie-impl-early-termination-in-insert(folder)-Backtracking-for-All-parent-paths
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: # Runtime: 301 ms, faster than 76.81% of Python3 online submissions for Remove Sub-Folders from the Filesystem. root = {} def insert(s): cur = root for c in s.split("/"): if "#" in cur: break cur = cur.setdefault(c, {}) cur["#"] = s # find every paths def bt(cur, path, res): if not cur or "#" in cur: res.append("/".join(path)) return for c in cur: bt(cur[c], path + [c], res) # build Trie holds parents only for f in folder: insert(f) res = [] bt(root, [], res) return res
remove-sub-folders-from-the-filesystem
[็ญ†่จ˜] Neat Python Trie impl, early termination in insert(folder), Backtracking for All parent paths
hzhang413
0
27
remove sub folders from the filesystem
1,233
0.654
Medium
18,530
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1830194/Python3-Using-Tuples-beats-90
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: folder.sort(key=lambda f: len(f)) folderSet = set() res = [] for f in folder: fList = f.split("/")[1:] i, n = 0, len(fList) curTuple = () toAdd = True for i in range(n): curTuple += (fList[i], ) if curTuple in folderSet: toAdd = False break if toAdd: folderSet.add(curTuple) res.append(f) return res
remove-sub-folders-from-the-filesystem
Python3 Using Tuples beats 90%
totoslg
0
34
remove sub folders from the filesystem
1,233
0.654
Medium
18,531
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1615128/Python3-Solution-with-using-sorting-and-trie
class Solution: def is_subset(self, node, parts): for idx in range(1, len(parts)): if parts[idx] not in node: node[parts[idx]] = {} if 'end' in node[parts[idx]]: return True node = node[parts[idx]] node['end'] = True return False def removeSubfolders(self, folder: List[str]) -> List[str]: trie = {} folder.sort() res = [] for f in folder: parts = f.split('/') if not self.is_subset(trie, parts): res.append(f) return res
remove-sub-folders-from-the-filesystem
[Python3] Solution with using sorting and trie
maosipov11
0
58
remove sub folders from the filesystem
1,233
0.654
Medium
18,532
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/644297/Python3-2-solutions-trie-and-startswith-Remove-Sub-Folders-from-the-Filesystem
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: ans = [] for i, path in enumerate(sorted(folder)): if i == 0 or not path.startswith(ans[-1] + "/"): ans.append(path) return ans
remove-sub-folders-from-the-filesystem
Python3 2 solutions trie and startswith - Remove Sub-Folders from the Filesystem
r0bertz
0
234
remove sub folders from the filesystem
1,233
0.654
Medium
18,533
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/644297/Python3-2-solutions-trie-and-startswith-Remove-Sub-Folders-from-the-Filesystem
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: Node = lambda: defaultdict(Node) trie = Node() ans = [] for path in sorted(folder): n = trie for c in path[1:].split('/'): n = n[c] if '$' in n: break else: n['$'] = True ans.append(path) return ans
remove-sub-folders-from-the-filesystem
Python3 2 solutions trie and startswith - Remove Sub-Folders from the Filesystem
r0bertz
0
234
remove sub folders from the filesystem
1,233
0.654
Medium
18,534
https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1248503/Python3-solution-No-need-for-special-data-structure
class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: folder.sort(key=len, reverse=False) # shorter ones in the front result = [] while folder != []: curr = folder.pop(0) result.append(curr) tmp = copy.deepcopy(folder) for i in tmp: if (curr+"/") in i: folder.remove(i) # print(result) return result
remove-sub-folders-from-the-filesystem
Python3 solution No need for special data structure
dooollydd
-2
58
remove sub folders from the filesystem
1,233
0.654
Medium
18,535
https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/884039/Python3-sliding-window-with-explanation
class Solution: def balancedString(self, s: str) -> int: counter = collections.Counter(s) n = len(s) // 4 extras = {} for key in counter: if counter[key] > n: extras[key] = counter[key] - n if not extras: return 0 i = 0 res = len(s) for j in range(len(s)): if s[j] in extras: extras[s[j]] -= 1 while max(extras.values()) <= 0: res = min(res, j-i+1) if s[i] in extras: extras[s[i]] += 1 i += 1 return res
replace-the-substring-for-balanced-string
[Python3] sliding window with explanation
hwsbjts
10
888
replace the substring for balanced string
1,234
0.369
Medium
18,536
https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/1395504/verbose-clean-python3-interview-implementation-of-lee125-solution
class Solution: def balancedString(self, s: str) -> int: # take window sum of all 4 ? # instead of window sum, # should we maintain remaining sum! # fre of elements outside the window ;) # initially window is empty.. remaining_fre = collections.Counter(s) res = n = len(s) left = 0 for right, c in enumerate(s): remaining_fre[c] -= 1 # while window is valid that is: # remaining does not have any EXTRA elements!! # EXTRA element is any (element > n/4) while left < n and all(remaining_fre[ch] <= n/4 for ch in 'QWER'): res = min(res, right-left+1) remaining_fre[s[left]] += 1 # he goes out of window! into remaining left += 1 return res """ WHILE LEFT < N while loop condition is most trick!!! : https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/408978/JavaC%2B%2BPython-Sliding-Window Important Does i <= j + 1 makes more sense than i <= n. Strongly don't think, and i <= j + 1 makes no sense. Answer the question first: Why do we need such a condition in sliding window problem? Actually, we never need this condition in sliding window solution (Check all my other solutions link at the bottom). Usually count the element inside sliding window, and i won't be bigger than j because nothing left in the window. """
replace-the-substring-for-balanced-string
verbose clean python3 interview implementation of lee125 solution
yozaam
1
154
replace the substring for balanced string
1,234
0.369
Medium
18,537
https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/2332148/PYTHONor-SLIDING-WINDOWor-DETAILED-EXPLANATION-WITH-PICTURE-or-VERY-EASY-AND-FASTor
class Solution: def balancedString(self, s: str) -> int: n , start , count , req , cur, index , ans = len(s) , 0 ,defaultdict(int) ,[0]*4 , [0]*4 , {'Q':0,'W':1,'E':2,'R':3} , len(s) for i in s:count[i] += 1 for i in count: if count[i] > n // 4:req[index[i]] = count[i] - n // 4 if req == [0,0,0,0]: return 0 for i,val in enumerate(s): cur[index[val]] += 1 if cur[0] >= req[0] and cur[1] >= req[1] and cur[2] >= req[2] and cur[3] >= req[3]: while True: if s[start] in "QWER": if cur[index[s[start]]] > req[index[s[start]]]: cur[index[s[start]]] -= 1 start += 1 else: break else: start += 1 ans = min(ans,i - start + 1) return ans
replace-the-substring-for-balanced-string
PYTHON| SLIDING WINDOW| DETAILED EXPLANATION WITH PICTURE | VERY EASY AND FAST|
reaper_27
0
61
replace the substring for balanced string
1,234
0.369
Medium
18,538
https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/1090872/Python3-sliding-window-(2-pointer)
class Solution: def balancedString(self, s: str) -> int: target = {} for c in s: target[c] = 1 + target.get(c, 0) for c in target: target[c] = max(0, target[c] - len(s)//4) freq = defaultdict(int) ans = len(s) ii = 0 for i, c in enumerate(s): freq[c] = 1 + freq.get(c, 0) while ii < len(s) and all(freq.get(x, 0) >= target[x] for x in target): ans = min(ans, i-ii+1) freq[s[ii]] -= 1 ii += 1 return ans
replace-the-substring-for-balanced-string
[Python3] sliding window (2-pointer)
ye15
0
123
replace the substring for balanced string
1,234
0.369
Medium
18,539
https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/1090872/Python3-sliding-window-(2-pointer)
class Solution: def balancedString(self, s: str) -> int: freq = {} for c in s: freq[c] = 1 + freq.get(c, 0) ans = len(s) ii = 0 for i, c in enumerate(s): freq[c] -= 1 while ii < len(s) and all(freq[x] <= len(s)//4 for x in freq): ans = min(ans, i-ii+1) freq[s[ii]] += 1 ii += 1 return ans
replace-the-substring-for-balanced-string
[Python3] sliding window (2-pointer)
ye15
0
123
replace the substring for balanced string
1,234
0.369
Medium
18,540
https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/409295/Python-3-(seven-lines)
class Solution: def balancedString(self, S: str) -> int: L, m, D, c, i, j = len(S), len(S), {k:v-len(S)//4 for k,v in collections.Counter(S).items() if v>len(S)//4}, {k:0 for k in 'QWER'}, -1, 0 if not D: return 0 for j, s in enumerate(S): while i < L - 1 and any(c[k] < D[k] for k in D): i += 1; c[S[i]] += 1 if i == L - 1 and any(c[k] < D[k] for k in D): break m = min(m, i - j + 1); c[s] -= 1 return m - Junaid Mansuri
replace-the-substring-for-balanced-string
Python 3 (seven lines)
junaidmansuri
0
508
replace the substring for balanced string
1,234
0.369
Medium
18,541
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1431246/Easiest-oror-Heap-oror-98-faster-oror-Clean-and-Concise
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: jobs = sorted([(startTime[i],endTime[i],profit[i]) for i in range(len(startTime))]) heap=[] cp,mp = 0,0 # cp->current profit, mp-> max-profit for s,e,p in jobs: while heap and heap[0][0]<=s: et,tmp = heapq.heappop(heap) cp = max(cp,tmp) heapq.heappush(heap,(e,cp+p)) mp = max(mp,cp+p) return mp
maximum-profit-in-job-scheduling
๐Ÿ Easiest || Heap || 98% faster || Clean & Concise ๐Ÿ“Œ
abhi9Rai
17
1,100
maximum profit in job scheduling
1,235
0.512
Hard
18,542
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1597523/Python-Heapq-Priority-queue
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: combos = [] for index in range(len(startTime)): combos.append( (startTime[index], endTime[index], profit[index] )) combos.sort(key = lambda x: x[0]) maxProfit = 0 # this is based on start time heap = [] # (endTime, profit) for combo in combos: start = combo[0] while heap and heap[0][0] <= start: # pop all with endtime <= curr start time # remember our max profit is based start time ! maxProfit = max(heapq.heappop(heap)[1], maxProfit) heappush(heap, (combo[1], maxProfit + combo[2])) for remainCombo in heap: # update the max profit to endtime based maxProfit = max(maxProfit, remainCombo[1]) return maxProfit
maximum-profit-in-job-scheduling
Python Heapq Priority queue
MingAlgoKing
3
408
maximum profit in job scheduling
1,235
0.512
Hard
18,543
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848854/Python-or-Faster-than-92-or-Simple-and-easy-to-follow
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: N = len(startTime) jobs = list(zip(startTime, endTime, profit)) jobs.sort() @lru_cache(None) def helper(i): if i == N: return 0 j = i + 1 while j < N and jobs[i][1] > jobs[j][0]: j += 1 one = jobs[i][2] + helper(j) two = helper(i+1) return max(one, two) return helper(0)
maximum-profit-in-job-scheduling
Python | Faster than 92% | Simple and easy to follow
mukund-13
2
52
maximum profit in job scheduling
1,235
0.512
Hard
18,544
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2786459/Python%3A-Stupid-Simple-O(n*log-n)
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: jobs = list(zip(startTime, endTime, profit)) jobs.sort() jobs.append((maxsize, 0, 0)) maxProfit, h = 0, [] for s, e, p in jobs: while h and h[0][0] <= s: maxProfit = max(maxProfit, heappop(h)[1]) heappush(h, (e, maxProfit + p)) return maxProfit
maximum-profit-in-job-scheduling
Python: Stupid Simple O(n*log n)
cryptofool
2
31
maximum profit in job scheduling
1,235
0.512
Hard
18,545
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2336433/PYTHON-or-SORTING-%2B-DP-or-DETAILED-EXPLANATION-WITH-PICTURE-or-FAST-or-O(n-LOG-n-)-or
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: n = len(profit) jobs = [(startTime[i],endTime[i],profit[i]) for i in range(n)] jobs.sort(key = lambda x: x[1]) def binarySearch(x,low,high): while low <= high: mid = (low + high) // 2 if jobs[mid][1] <= x : low = mid + 1 else: high = mid - 1 return high total_profit = [0]*n for index in range(n): i = binarySearch(jobs[index][0] , 0 , index - 1) to_add = total_profit[i] if i != -1 else 0 total_profit[index] = max(total_profit[index-1],jobs[index][2] + to_add) return total_profit[-1]
maximum-profit-in-job-scheduling
PYTHON | SORTING + DP | DETAILED EXPLANATION WITH PICTURE | FAST | O(n LOG n ) |
reaper_27
2
171
maximum profit in job scheduling
1,235
0.512
Hard
18,546
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848727/Python3-Straightforward-DP
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: mp = {e: i for i, e in enumerate(sorted(set(startTime + endTime)))} j = {x:[] for x in range(len(mp))} for i in range(len(startTime)): j[mp[startTime[i]]].append((mp[startTime[i]], mp[endTime[i]], profit[i])) mp = [0 for i in range(len(mp))] for i in range(len(mp)): if i > 0: mp[i] = max(mp[i], mp[i-1]) for s, e, p in j[i]: mp[e] = max(mp[e], mp[i] + p) return max(mp)
maximum-profit-in-job-scheduling
Python3 Straightforward DP
godshiva
1
80
maximum profit in job scheduling
1,235
0.512
Hard
18,547
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2745447/Python3-or-Dp-%2B-BinarySearch
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: n,ans=len(startTime),0 state=[] for i in range(n): state.append([endTime[i],startTime[i],profit[i]]) state=sorted(state) dp=[0 for i in range(n)] dp[0]=state[0][2] for i in range(1,n): prevIndex=bisect.bisect_left(state,[state[i][1]+1]) if prevIndex==0: dp[i]=max(dp[i-1],state[i][2]) else: dp[i]=max(dp[i-1],dp[prevIndex-1]+state[i][2]) ans=max(ans,dp[i]) return ans
maximum-profit-in-job-scheduling
[Python3] | Dp + BinarySearch
swapnilsingh421
1
43
maximum profit in job scheduling
1,235
0.512
Hard
18,548
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2737869/Binary-search-solution-by-UC-Berkeley-Computer-Science-honor-society.
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: n = len(startTime) intervals = sorted([(startTime[i], endTime[i], profit[i]) for i in range(n)], key=lambda ival: ival[1]) dp = [0] * (n + 1) def findSubproblem(startVal): low, high = 0, n ret = -1 while low <= high: mid = low + (high - low) // 2 if intervals[mid][1] <= startVal: ret = mid low = mid + 1 else: high = mid - 1 return ret + 1 for i in range(1, n + 1): st = intervals[i - 1][0] dp[i] = dp[i - 1] dp[i] = max(dp[i], intervals[i-1][2] + dp[findSubproblem(st)]) return dp[n]
maximum-profit-in-job-scheduling
Binary search solution by UC Berkeley Computer Science honor society.
berkeley_upe
1
21
maximum profit in job scheduling
1,235
0.512
Hard
18,549
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2355765/Python3-DP%2BBinary-Search-(commented)
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: # s: start, t: terminate, p: profit # sort the job based on startTime so BinarySearch can be used to reduce time complexity # of the procedure of finding next, i.e. BinSearchNext() below jobs = [{'s':s, 't':t, 'p':p} for s, t, p in zip(startTime, endTime, profit)] jobs.sort(key = lambda d:d['s']) # Choice 1: schedule current job, and go on finding the next job, with index `curr_next` # for `curr_next`, it refers to the job that have startTime >= curr job's endTime # (s.t. there are no two jobs in the subset with overlapping time range, # as the problem description states), then compute dp(curr_next) and add them together # Choice 2: do not schedule current job, simply skip it and move the current index forward by 1, i.e. curr+1 # use caching to simulate memoization in DP @lru_cache def dp(curr): if curr == len(jobs): return 0 curr_next = BinSearchNext(curr) TakeProfit = jobs[curr]['p'] + dp(curr_next) NoTakeProfit = dp(curr+1) return max(TakeProfit, NoTakeProfit) # find the job that have startTime >= curr job's endTime `queryEndTime` def BinSearchNext(idx): queryEndTime = jobs[idx]['t'] l, r = idx+1, len(jobs)-1 while l <= r: mid = int((l+r)/2) if jobs[mid]['s'] >= queryEndTime: if jobs[mid-1]['s'] >= queryEndTime: r = mid - 1 # job[mid-1] does not overlap; job[mid] does not either, decrement `r` bound else: return mid # job[mid-1] overlaps; job[mid] does not; therefore job[mid] is the best valid next job else: l = mid + 1 # job[mid] overlaps (naturally job[mid-1] overlaps too), increment `l` bound # `return len(jobs)` means that no job can be found as the next job, it's either # 1. All jobs have been considered or 2. No left jobs have valid startTime return len(jobs) return dp(0) # let n = number of jobs, dp[0] it means to consider job set from job[0] to job[n-1], i.e. the complete job list # Time: 1183 ms, Space: 54 MB
maximum-profit-in-job-scheduling
[Python3] DP+Binary Search (commented)
LemonHerbs
1
86
maximum profit in job scheduling
1,235
0.512
Hard
18,550
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1572598/python-easy-to-understand-solution-O(nlogn)
class Solution: def binSearch(self, A, start, end, z): mid = -1 while start <= end: mid = (start + end) // 2 if A[mid] > z: end = mid - 1 else: start = mid + 1 return end def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: n = len(profit) jobs = [[endTime[i], startTime[i], profit[i]] for i in range(n)] jobs.sort() A = [v[0] for v in jobs] dp = [0 for _ in range(n)] dp[0] = jobs[0][2] for i in range(1, n): if jobs[i][1] < A[0]: dp[i] = max(dp[i-1], jobs[i][2]) continue lower = self.binSearch(A, 0, i-1, jobs[i][1]) dp[i] = max(dp[i-1], jobs[i][2] + dp[lower]) return dp[n-1]
maximum-profit-in-job-scheduling
python easy to understand solution O(nlogn)
ashish_chiks
1
701
maximum profit in job scheduling
1,235
0.512
Hard
18,551
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1090860/Python3-knapsack
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: startTime, endTime, profit = zip(*sorted(zip(startTime, endTime, profit))) @cache def fn(i): """Return max profit starting from index i.""" if i == len(startTime): return 0 ii = bisect_left(startTime, endTime[i]) return max(fn(i+1), profit[i] + fn(ii)) return fn(0)
maximum-profit-in-job-scheduling
[Python3] knapsack
ye15
1
319
maximum profit in job scheduling
1,235
0.512
Hard
18,552
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1036995/Python3-8-line-Solution
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: start, end, pro = zip(*sorted(zip(startTime, endTime, profit), key=lambda x: x[0])) @lru_cache(None) def dp(i): if i == len(start): return 0 j = bisect_left(start, end[i]) return max(pro[i] + dp(j), dp(i + 1)) return dp(0) ```
maximum-profit-in-job-scheduling
Python3 8 line Solution
udayd
1
727
maximum profit in job scheduling
1,235
0.512
Hard
18,553
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2849605/Python-DP-solution-using-binary-search-O(NlogN)-with-explanation
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: jobs = sorted(zip(startTime, endTime, profit), key = lambda x:x[1]) prof, time = [0], [0] for s,e,p in jobs: prof.append(max(prof[-1], prof[bisect_left(time, s+1)-1]+p)) time.append(e) return prof[-1]
maximum-profit-in-job-scheduling
[Python] DP solution using binary search O(NlogN) with explanation
zaynefn
0
7
maximum profit in job scheduling
1,235
0.512
Hard
18,554
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2849439/FASTEST-oror-BEATS-95-SUBMISSIONS-oror-EASIEST-oror-RECURSION
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: N=len(startTime) jobs=list(zip(startTime,endTime,profit)) jobs.sort() @lru_cache(None) def rec(i): if i==N: return 0 j=i+1 while j<N and jobs[i][1]>jobs[j][0]: j+=1 one=jobs[i][2]+rec(j) two=rec(i+1) return max(one,two) return rec(0)
maximum-profit-in-job-scheduling
FASTEST || BEATS 95% SUBMISSIONS || EASIEST || RECURSION
Pritz10
0
5
maximum profit in job scheduling
1,235
0.512
Hard
18,555
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2849344/Python-Intuitive-DFS-memoization
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: times = [] for i in range(len(startTime)): times.append((startTime[i],endTime[i], profit[i])) times.sort() dp = {} return self.helper(times, 0, 0, dp) def helper(self, job, i, start, dp): if i>= len(job): return 0 if i in dp and job[i][0]>=start: return dp[i] flag = False res = 0 if job[i][0]>=start: flag = True # pick res = max (res, job[i][2] + self.helper(job, i+1, job[i][1], dp)) # not pick res = max (res, self.helper(job, i+1, start, dp)) if flag: dp[i] = res return res
maximum-profit-in-job-scheduling
Python Intuitive DFS memoization
nirutgupta78
0
5
maximum profit in job scheduling
1,235
0.512
Hard
18,556
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2849333/Python3-oror-easy-fast-(9973)-and-short-explained-oror-DP-oror-Time-O(N-log(N))-Space-O(N)
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: dp_end = [0] dp_val = [0] for end,start,value in sorted( zip(endTime, startTime, profit) ): ind_start = bisect_right(dp_end, start) dp_end.append(end) dp_val.append( max(dp_val[-1], dp_val[ind_start-1]+value) ) return dp_val[-1]
maximum-profit-in-job-scheduling
Python3 || easy, fast (99%,73%) and short, explained || DP || Time O(N log(N)), Space O(N)
drevil_no1
0
4
maximum profit in job scheduling
1,235
0.512
Hard
18,557
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2849317/Python3-solution
class Solution: def jobScheduling(self, s: List[int], e: List[int], p: List[int]) -> int: jobs, n = sorted(zip(s, e, p)), len(s) # [1] prepare jobs for binary search dp = [0] * (n + 1) # by sorting them by start time for i in reversed(range(n)): # [2] knapsack: either try next job or k = bisect_left(jobs, jobs[i][1], key=lambda j: j[0]) # take this one together with trying dp[i] = max(jobs[i][2] + dp[k], dp[i+1]) # the next valid one return dp[0]
maximum-profit-in-job-scheduling
Python3 solution
avs-abhishek123
0
4
maximum profit in job scheduling
1,235
0.512
Hard
18,558
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2849039/concise-C%2B%2BPython%3A-sparse-sorted-time
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: evs = [] for s, e, p in zip(startTime, endTime, profit): evs.append((s, 0, 0, 0)) evs.append((e, 1, s, p)) best = 0 best_at = defaultdict(int) for t, typ, s, p in sorted(evs): if typ: best = max(best, best_at[s] + p) best_at[t] = best return best
maximum-profit-in-job-scheduling
concise C++/Python: sparse sorted time
asdju
0
2
maximum profit in job scheduling
1,235
0.512
Hard
18,559
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848840/Python3C%2B%2B-From-recursive-to-memoized-with-the-mistake-I-made
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: schedule = sorted(list(zip(startTime,endTime,profit))) def dfs(last_end,i): if i == len(schedule): return 0 take,not_take = 0,0 if schedule[i][0] >= last_end: take = schedule[i][2] + dfs(schedule[i][1],i+1) not_take = dfs(last_end,i+1) return max(take,not_take) return dfs(0,0)
maximum-profit-in-job-scheduling
[Python3/C++] From recursive to memoized with the mistake I made
shriyansnaik
0
6
maximum profit in job scheduling
1,235
0.512
Hard
18,560
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848840/Python3C%2B%2B-From-recursive-to-memoized-with-the-mistake-I-made
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: schedule = sorted(list(zip(startTime,endTime,profit))) dp = {} def dfs(last_end,i): if i == len(schedule): return 0 if (last_end,i) in dp: return dp[(last_end,i)] take,not_take = 0,0 if schedule[i][0] >= last_end: take = schedule[i][2] + dfs(schedule[i][1],i+1) not_take = dfs(last_end,i+1) dp[(last_end,i)] = max(take,not_take) return dp[(last_end,i)] return dfs(0,0)
maximum-profit-in-job-scheduling
[Python3/C++] From recursive to memoized with the mistake I made
shriyansnaik
0
6
maximum profit in job scheduling
1,235
0.512
Hard
18,561
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848840/Python3C%2B%2B-From-recursive-to-memoized-with-the-mistake-I-made
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: schedule = sorted(list(zip(startTime,endTime,profit))) dp = {} def dfs(last_end,i): if i == len(schedule): return 0 if schedule[i][0] < last_end: return dfs(last_end,i+1) if i in dp: return dp[i] take = schedule[i][2] + dfs(schedule[i][1],i+1) not_take = dfs(last_end,i+1) dp[i] = max(take,not_take) return dp[i] return dfs(0,0)
maximum-profit-in-job-scheduling
[Python3/C++] From recursive to memoized with the mistake I made
shriyansnaik
0
6
maximum profit in job scheduling
1,235
0.512
Hard
18,562
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848815/Python3-Solutions-with-DP
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: jobs=sorted(zip(startTime,endTime,profit),key=lambda x:x[1]) endTimes=[e for s,e,p in jobs] n=len(jobs) dp=[0]*n dp[0]=jobs[0][2] for i in range (1,n): s=jobs[i][0] e=jobs[i][1] p=jobs[i][2] dp[i]=dp[i-1] index=bisect.bisect_right(endTimes,s)-1 dp[i]=max(dp[i],(dp[index] if index>=0 else 0)+p) return dp[-1]
maximum-profit-in-job-scheduling
Python3 Solutions with DP
Motaharozzaman1996
0
8
maximum profit in job scheduling
1,235
0.512
Hard
18,563
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2848787/python-6-lines-O(nlogn)-time.-spaghetti-code-horrible-readibility
class Solution: # seeing the condition there, I knew we need to beat O(n^2) to # make it work. Then I started to think about greedy approach. # because this is interval, it reminds me of the sweeping line # method. Eventually the key observation was that for each # interval, the max profit at its end point equals to the # max(current max profit, max profit at start point + the # interval's profit). def jobScheduling(self, st: List[int], et: List[int], p: List[int]) -> int: # the second value j is flag for start or end time. 1 means start time. 0 means end time. lst = sorted([(t[i], j, p[i], i) for i in range(len(p)) for j, t in enumerate([et, st])]) d, res = {}, 0 for time, _, p, i in lst: if i in d: res = max(d[i], res); d.pop(i) else: d[i] = res + p return res
maximum-profit-in-job-scheduling
python 6 lines, O(nlogn) time. spaghetti code horrible readibility
tinmanSimon
0
3
maximum profit in job scheduling
1,235
0.512
Hard
18,564
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2614535/Clean-Python3-or-DP-and-Bisect-or-O(n-log(n))
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: # assume that once max_profit(i) is called, jobs[i] can be scheduled without conflict # to ensure this property, binary search the next job that can be done if we choose to do jobs[i] @cache def max_profit(i): if i >= len(jobs): return 0 prof1 = max_profit(i + 1) nxt = bisect_left(jobs, (jobs[i][1], 0, 0)) prof2 = jobs[i][2] + max_profit(nxt) return max(prof1, prof2) jobs = sorted(zip(startTime, endTime, profit)) return max_profit(0)
maximum-profit-in-job-scheduling
Clean Python3 | DP & Bisect | O(n log(n))
ryangrayson
0
48
maximum profit in job scheduling
1,235
0.512
Hard
18,565
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2453269/Python-easy-to-read-and-understand-or-recursion-%2B-memoization
class Solution: def solve(self, jobs, i, prev): n = len(jobs) if i == n: return 0 if jobs[i][0] >= prev: return max(self.solve(jobs, i+1, jobs[i][1]) + jobs[i][2], self.solve(jobs, i+1, prev)) else: return self.solve(jobs, i+1, prev) def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: jobs = sorted(list(zip(startTime, endTime, profit))) return self.solve(jobs, 0, float("-inf"))
maximum-profit-in-job-scheduling
Python easy to read and understand | recursion + memoization
sanial2001
0
103
maximum profit in job scheduling
1,235
0.512
Hard
18,566
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2453269/Python-easy-to-read-and-understand-or-recursion-%2B-memoization
class Solution: def solve(self, jobs, i, prev): n = len(jobs) if i == n: return 0 if (i, prev) in self.d: return self.d[(i, prev)] if jobs[i][0] >= prev: self.d[(i, prev)] = max(self.solve(jobs, i+1, jobs[i][1]) + jobs[i][2], self.solve(jobs, i+1, prev)) return self.d[(i, prev)] else: self.d[(i, prev)] = self.solve(jobs, i+1, prev) return self.d[(i, prev)] def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: self.d = {} jobs = sorted(list(zip(startTime, endTime, profit))) return self.solve(jobs, 0, float("-inf"))
maximum-profit-in-job-scheduling
Python easy to read and understand | recursion + memoization
sanial2001
0
103
maximum profit in job scheduling
1,235
0.512
Hard
18,567
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/2453269/Python-easy-to-read-and-understand-or-recursion-%2B-memoization
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: jobs = sorted(list(zip(startTime, endTime, profit))) pq = [] total = 0 for s,e,p in jobs: while pq and pq[0][0] <= s: end, pro = heapq.heappop(pq) total = max(total, pro) heapq.heappush(pq, (e, p+total)) while pq: end, pro = heapq.heappop(pq) total = max(total, pro) return total
maximum-profit-in-job-scheduling
Python easy to read and understand | recursion + memoization
sanial2001
0
103
maximum profit in job scheduling
1,235
0.512
Hard
18,568
https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1800745/DP-Solution-oror-Python3-oror-O(N2)-Time
class Solution: def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int: start = min(startTime) end = max(endTime) n = len(startTime) newList = [[startTime[i]-start+1, endTime[i]-start+1, profit[i]] for i in range(n)] newList.sort(key = lambda x : x[1]) n = len(newList) dp = [0]*(n + 1) for i in range(n): [starti, endi, costi] = newList[i] j = i-1 while j >= 0 and newList[j][1] > starti: j-=1 dp[i+1] = max(dp[j+1]+costi,dp[i+1], dp[i]) return dp[-1]
maximum-profit-in-job-scheduling
DP Solution || Python3 || O(N^2) Time
henriducard
0
149
maximum profit in job scheduling
1,235
0.512
Hard
18,569
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/933212/Python-3-greater-91.68-faster.-O(n)-time
def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: x, y = 1, z pairs = [] while x<=z and y>0: cf = customfunction.f(x,y) if cf==z: pairs.append([x,y]) x, y = x+1, y-1 elif cf > z: y -= 1 else: x += 1 return pairs
find-positive-integer-solution-for-a-given-equation
Python 3 -> 91.68% faster. O(n) time
mybuddy29
27
1,500
find positive integer solution for a given equation
1,237
0.693
Medium
18,570
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/414196/Two-Solutions-in-Python-3-(beats-100)
class Solution: def findSolution(self, C: 'CustomFunction', z: int) -> List[List[int]]: A, Y = [], z+1 for x in range(1,z+1): if C.f(x,1) > z: return A for y in range(Y,0,-1): if C.f(x,y) == z: Y, _ = y-1, A.append([x,y]) break return A
find-positive-integer-solution-for-a-given-equation
Two Solutions in Python 3 (beats 100%)
junaidmansuri
9
1,900
find positive integer solution for a given equation
1,237
0.693
Medium
18,571
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/414196/Two-Solutions-in-Python-3-(beats-100)
class Solution: def findSolution(self, C: 'CustomFunction', z: int) -> List[List[int]]: A, b = [], z+1 for x in range(1,z+1): if C.f(x,1) > z: return A a = 1 while C.f(x,b-1) > z: m = (a+b)//2 if C.f(x,m) > z: b = m else: a = m if C.f(x,b-1) == z: b, _ = b-1, A.append([x,b-1]) return A
find-positive-integer-solution-for-a-given-equation
Two Solutions in Python 3 (beats 100%)
junaidmansuri
9
1,900
find positive integer solution for a given equation
1,237
0.693
Medium
18,572
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/1092308/Python3-2-pointer
class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: ans = [] x, y = 1, 1000 while x <= 1000 and 1 <= y: if customfunction.f(x, y) < z: x += 1 elif customfunction.f(x, y) > z: y -= 1 else: ans.append([x, y]) x += 1 y -= 1 return ans
find-positive-integer-solution-for-a-given-equation
[Python3] 2-pointer
ye15
2
391
find positive integer solution for a given equation
1,237
0.693
Medium
18,573
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/1286831/Python3-solution
class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: l = [] for i in range(1,1000): for j in range(1,1000): if customfunction.f(i,j) == z: l.append([i,j]) elif customfunction.f(i,j) > z: break return l
find-positive-integer-solution-for-a-given-equation
Python3 solution
EklavyaJoshi
1
112
find positive integer solution for a given equation
1,237
0.693
Medium
18,574
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/2379180/Readable-Binary-Search-solution-python3
class Solution: # O(nlogn) time, where n is the domain width # O(m) space, where m is the length of the our solution set. # Approach: binary search, def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: solutionSet = [] x_limit = 1000 y_limit = 1000 def findPossibleYGivenX(start:int, end:int, x:int) -> None: mid = (start + end)//2 output = customfunction.f(x, mid) if output == z: solutionSet.append([x, mid]) curr = mid - 1 while customfunction.f(x, curr) == z: solutionSet.append([x, curr]) curr -=1 curr = mid + 1 while customfunction.f(x, curr) == z: solutionSet.append([x, curr]) curr +=1 return elif start == end-1: if customfunction.f(x, end) != z: return solutionSet.append([x, end]) elif output < z: findPossibleYGivenX(mid, end, x) elif output > z: findPossibleYGivenX(start, mid, x) for x in range(1, x_limit+1): findPossibleYGivenX(1, y_limit, x) return solutionSet
find-positive-integer-solution-for-a-given-equation
Readable Binary Search solution python3
destifo
0
40
find positive integer solution for a given equation
1,237
0.693
Medium
18,575
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/1492352/I-think-two-pointers-approach-is-better-than-binary-search.
class Solution: def findSolution(self, customf: 'CustomFunction', z: int) -> List[List[int]]: x, y = 1, 1000 res = [] while x <=y: # when f(x, y), x<=y is the solution if customf.f(x, y) == z: res.append([x, y]) x += 1 y -= 1 elif customf.f(x, y) > z: y -= 1 else: #customf.f(x, y) < z x += 1 x, y = 1000, 1 while x>y: # when f(x, y), x>y is the solution if customf.f(x, y) == z: res.append([x, y]) x -= 1 y += 1 elif customf.f(x, y) > z: x -= 1 else: #customf.f(x, y) < z y += 1 return res
find-positive-integer-solution-for-a-given-equation
I think two-pointers approach is better than binary search.
byuns9334
0
230
find positive integer solution for a given equation
1,237
0.693
Medium
18,576
https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/744367/Python3-or-Binary-Search-or-Straight-Forward
class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: result =[] for x in range(1,z+1): l,h=1,z while(l<=h): m=(l+h)//2 if (customfunction.f(x,m)==z): result.append([x,m]) break; elif (customfunction.f(x,m)<z): l=m+1 elif (customfunction.f(x,m)>z): h=m-1 return result
find-positive-integer-solution-for-a-given-equation
Python3 | Binary Search | Straight Forward
donpauly
0
292
find positive integer solution for a given equation
1,237
0.693
Medium
18,577
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1092321/Python3-backtracking
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: ans = [] for i in range(1<<n): ans.append(start ^ i ^ i >> 1) return ans
circular-permutation-in-binary-representation
[Python3] backtracking
ye15
1
117
circular permutation in binary representation
1,238
0.689
Medium
18,578
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1092321/Python3-backtracking
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: ans = [start] seen = set(ans) def fn(i, x): """Return circular permutation with x at i.""" if i == 2**n: diff = ans[-1] ^ start if not diff &amp; (diff-1): return ans for k in range(n): xx = x ^ 1 << k if xx not in seen: seen.add(xx) ans.append(xx) if tmp := fn(i+1, xx): return tmp ans.pop() seen.remove(xx) return fn(1, start)
circular-permutation-in-binary-representation
[Python3] backtracking
ye15
1
117
circular permutation in binary representation
1,238
0.689
Medium
18,579
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/487415/Python-Recursive-solution
class Solution: def solve(self, n, s, res): if n == 0: res.append(s) return s s1 = self.solve(n-1, s^0, res) s2 = self.solve(n-1, s1^(1<<n-1), res) return s2 def circularPermutation(self, n: int, start: int) -> List[int]: res = [] self.solve(n, start, res) return res
circular-permutation-in-binary-representation
Python Recursive solution
xyz76
1
144
circular permutation in binary representation
1,238
0.689
Medium
18,580
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1818086/Gray-code-with-simple-backtracking-and-then-rotate
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: ans=[] def gray_code(n): if n==0: ans.append(0) return gray_code(n-1) for i in range(len(ans)-1,-1,-1): ans.append(ans[i]| 1<<(n-1)) def rotate(ans): r=0 for i in range(len(ans)): if ans[i]==start: r=i break return ans[r:]+ans[:r] gray_code(n) ans=rotate(ans) return ans
circular-permutation-in-binary-representation
Gray code with simple backtracking and then rotate
shefali_7
0
52
circular permutation in binary representation
1,238
0.689
Medium
18,581
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1495761/Python3-3-liner
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: gray_code = [x ^ (x >> 1) for x in range(2 ** n)] start_i = gray_code.index(start) return gray_code[start_i:] + gray_code[:start_i]
circular-permutation-in-binary-representation
[Python3] 3-liner
Skaiir
0
95
circular permutation in binary representation
1,238
0.689
Medium
18,582
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1300838/Python3-solution-using-single-for-loop
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: l = [0] for i in range(1,2**n): l.append(i ^ (i >> 1)) return l[l.index(start):] + l[:l.index(start)]
circular-permutation-in-binary-representation
Python3 solution using single for loop
EklavyaJoshi
0
71
circular permutation in binary representation
1,238
0.689
Medium
18,583
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1157391/Python-3-solution-using-concept-of-gray-code
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: binary=[] for i in range((2**n)): x=bin(i).replace('0b','') binary.append(x) gray=[] for i in range(len(binary)): temp=[] for j in range(len(binary[i])): if j==0: temp.append(binary[i][j]) else: temp.append(str(int(binary[i][j])^int(binary[i][j-1]))) gray.append(int(''.join(temp),2)) a=gray.index(start) result=gray[a:]+gray[:a] return result
circular-permutation-in-binary-representation
Python 3 solution using concept of gray code
Underdog2000
0
101
circular permutation in binary representation
1,238
0.689
Medium
18,584
https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/790265/python3-gray-code-generation
class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: # gray code generation! for every new "bit": # 1) preface reversed list with 1 == same as adding 2^(N-1) # 2) squish onto existing list # (N) 1 2 3 gray # 0 00 000 0 # 1 01 001 1 # 11 011 2 # 10 010 3 # 110 4 # 111 5 # 101 6 # 100 7 # then find start position (ambiguously NOT gray representation) # slice and dice the created list with "start" at index 0 # O(2^N) time, O(2^N) space gc, bit = [0, 1], 1 while bit < n: bit += 1 next_vals = [] for val in reversed(gc): next_vals.append( val + 2**(bit-1) ) gc.extend(next_vals) ind = gc.index(start) return gc[ind:] + gc[:ind]
circular-permutation-in-binary-representation
python3 - gray code generation
dachwadachwa
0
108
circular permutation in binary representation
1,238
0.689
Medium
18,585
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1478666/Two-Approach-oror-Well-Explained-oror-97-faster
class Solution: def maxLength(self,arr): unique = [''] res = 0 for i in range(len(arr)): for j in range(len(unique)): local = arr[i]+unique[j] if len(local)==len(set(local)): unique.append(local) res=max(res,len(local)) return res
maximum-length-of-a-concatenated-string-with-unique-characters
๐Ÿ Two-Approach || Well-Explained || 97% faster ๐Ÿ“Œ
abhi9Rai
22
2,200
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,586
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1478666/Two-Approach-oror-Well-Explained-oror-97-faster
class Solution: res = 0 def maxLength(self,arr): self.backtrack(arr,0,"") return self.res def backtrack(self,arr,ind,local): if len(local)!=len(set(local)): return self.res = max(self.res,len(local)) for i in range(ind,len(arr)): self.backtrack(arr,i+1,local+arr[i])
maximum-length-of-a-concatenated-string-with-unique-characters
๐Ÿ Two-Approach || Well-Explained || 97% faster ๐Ÿ“Œ
abhi9Rai
22
2,200
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,587
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2737783/Python's-Simple-and-Easy-to-Understand-Solution-or-99-Faster
class Solution: def maxLength(self, arr: List[str]) -> int: n = len(arr) res = [""] op = 0 for word in arr: for r in res: newRes = r+word if len(newRes)!=len(set(newRes)): continue res.append(newRes) op = max(op, len(newRes)) return op
maximum-length-of-a-concatenated-string-with-unique-characters
โœ”๏ธ Python's Simple and Easy to Understand Solution | 99% Faster ๐Ÿ”ฅ
pniraj657
21
1,700
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,588
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738251/Python-Elegant-and-Short-or-DP
class Solution: """ Time: O(n^2) Memory: O(n^2) """ def maxLength(self, sequences: List[str]) -> int: dp = [set()] for seq in sequences: chars = set(seq) if len(chars) < len(seq): continue dp.extend(chars | other for other in dp if not (chars &amp; other)) return max(map(len, dp))
maximum-length-of-a-concatenated-string-with-unique-characters
Python Elegant & Short | DP
Kyrylo-Ktl
12
1,100
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,589
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2160080/Python-easy-to-read-and-understand-or-recursion
class Solution: def solve(self, words, index, word): if len(word) != len(set(word)): return self.ans = max(self.ans, len(word)) if index == len(words): return for i in range(index, len(words)): self.solve(words, i+1, word+words[i]) def maxLength(self, arr: List[str]) -> int: self.ans = 0 self.solve(arr, 0, '') return self.ans
maximum-length-of-a-concatenated-string-with-unique-characters
Python easy to read and understand | recursion
sanial2001
4
328
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,590
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1743841/easy-solution-using-python3-and-backtracking
class Solution: def maxLength(self, arr: List[str]) -> int: self.m = 0 def solve(com,arr): if(len(com) == len(set(com))): self.m = max(self.m,len(com)) else: return for i in range(len(arr)): solve(com+"".join(arr[i]),arr[i+1:]) solve("",arr) return self.m
maximum-length-of-a-concatenated-string-with-unique-characters
easy solution using python3 and backtracking
jagdishpawar8105
2
202
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,591
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1186501/python-dfs
class Solution: def maxLength(self, arr: List[str]) -> int: self.max_l = 0 self.dfs(arr, '', set(), 0) return self.max_l def dfs(self, arr, cur_s, visited, idx): if idx == len(arr): return for i in range(idx, len(arr)): if i in visited: continue if len(cur_s) + len(arr[i]) != len(set(cur_s + arr[i])): continue self.max_l = max(self.max_l, len(cur_s) + len(arr[i])) visited.add(i) self.dfs(arr, cur_s + arr[i], visited, i + 1) visited.remove(i)
maximum-length-of-a-concatenated-string-with-unique-characters
python dfs
happyBo2020
2
291
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,592
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/872596/Python-3-(3.8)-or-Backtracking-Set-Union-Walrus-Operator-or-Explanation
class Solution: def maxLength(self, arr: List[str]) -> int: arr = [(s, l) for word in arr if (l:=len(s:=set(word))) == len(word)] ans, n = 0, len(arr) def dfs(arr, cur_s, cur_l, idx): nonlocal ans, n ans = max(ans, cur_l) if idx == n: return [dfs(arr, union, union_len, i+1) for i in range(idx, n) if (union_len:=len(union:=arr[i][0] | cur_s)) == arr[i][1] + cur_l] dfs(arr, set(), 0, 0) return ans
maximum-length-of-a-concatenated-string-with-unique-characters
Python 3 (3.8) | Backtracking, Set Union, Walrus Operator | Explanation
idontknoooo
2
649
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,593
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2738994/Python3-Easy-Understanding-Bitmask-%2B-DFS
class Solution: def maxLength(self, arr: List[str]) -> int: arr_masks = [] for s in arr: mask = 0 uniq = True for c in s: shift = ord(c) - ord('a') if (1 << shift) &amp; mask == 0: mask |= (1 << shift) else: uniq = False break if uniq: arr_masks.append(mask) # print(list(map(lambda x: format(x, '032b'), arr_masks))) res = [0] mask = 0 def dfs(idx, mask, item): if idx == len(arr_masks): # print(mask) res[0] = max(mask.bit_count(), res[0]) return if arr_masks[idx] &amp; mask == 0: # dfs(idx + 1, arr_masks[idx] &amp; mask, item + [idx]) # TAKE BUGGG! dfs(idx + 1, arr_masks[idx] | mask, item + [idx]) # TAKE FIXX! dfs(idx + 1, mask, item) # No TAKE dfs(0, 0, []) return res[0] """ ========================= """ n = len(arr) # ALSO AC, ref to lee215 # res = set([]) # dp = [set(arr[0])] dp = [set([])] for i in range(n): s = arr[i] set_s = set(s) if len(s) != len(set_s): continue for item in dp: if set_s &amp; item: continue dp.append(item | set_s) # FIXXX! # item |= set_s # BUGGG! # dp.append(set_s) # BUGG # print(dp) return max(len(item) for item in dp)
maximum-length-of-a-concatenated-string-with-unique-characters
[Python3] Easy Understanding -- Bitmask + DFS
JoeH
1
7
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,594
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/414400/Two-Solutions-in-Python-3-(three-lines)
class Solution: def maxLength(self, A: List[str]) -> int: B, A = [set()], [set(a) for a in A if len(set(a)) == len(a)] for a in A: B += [a|c for c in B if not a&amp;c] return max(len(a) for a in B)
maximum-length-of-a-concatenated-string-with-unique-characters
Two Solutions in Python 3 (three lines)
junaidmansuri
1
962
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,595
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/414400/Two-Solutions-in-Python-3-(three-lines)
class Solution: def maxLength(self, A: List[str]) -> int: C, A, m, i = {''}, [set(a) for a in A if len(set(a)) == len(a)], 0, 0 while i < len(A): B, C, i = C, set(), i+1 for b in B: bs = set(list(b)) for a in A: if not (a &amp; bs): u = ''.join(sorted(list(a | bs))) if u not in C: m, _ = max(m,len(u)), C.add(u) return m - Junaid Mansuri
maximum-length-of-a-concatenated-string-with-unique-characters
Two Solutions in Python 3 (three lines)
junaidmansuri
1
962
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,596
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2797407/Python-solution-backtracking
class Solution: def maxLength(self, arr: List[str]) -> int: def backtracking(index,string,combinations): if index == len(arr): return string = string + arr[index] self.max_len = max(self.max_len,len(string)) combinations.append(string) for i in range(index+1,len(arr)): if len(set(string).intersection(set(arr[i]))) == 0 and len(set(arr[i])) == len(arr[i]): backtracking(i,string,combinations) #string.replace(arr[index] ,"") combinations=[] self.max_len = 0 for i in range(len(arr)): if len(set(arr[i])) == len(arr[i]): backtracking(i,"",combinations) print(combinations) return self.max_len
maximum-length-of-a-concatenated-string-with-unique-characters
Python solution backtracking
ishitakumardps
0
2
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,597
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2740986/Python-or-Clean-or-easy-to-understand-with-comments
class Solution: def maxLength(self, arr: List[str]) -> int: dp = [set()] for s in arr: # check whether the picked string has duplicate element # if yes , continue to next string if len(set(s)) < len(s): continue # if not put the string in a set # why? , because in next steps we will use the operator on sets s = set(s) # we will traverse in the array, using colan we will traverse # only till current size of dp , it will update it after evey iteration for a in dp[:]: # this '&amp;' means if we have anything common or if the intersection of these two sets # is not NULL the continue, dont consider the string if s &amp; a: continue #append what a or c both have to dp dp.append(s | a) #max length of concatenated string length = max(len(a) for a in dp) return length
maximum-length-of-a-concatenated-string-with-unique-characters
Python | Clean | easy to understand with comments
nush29
0
14
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,598
https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/2740240/Python-backtrack-(brute-force)
class Solution: def maxLength(self, arr: List[str]) -> int: res = [0] def backtrack(s, i): if len(set(s)) != len(s): return if i == len(arr) - 1: res[0] = max(res[0], len(s)) return for j in range(i + 1, len(arr)): if set(s).intersection(set(arr[j])) == set(): backtrack(s + arr[j], j) res[0] = max(res[0], len(s)) for i in range(len(arr)): backtrack(arr[i], i) return res[0]
maximum-length-of-a-concatenated-string-with-unique-characters
Python backtrack (brute-force)
JSTM2022
0
6
maximum length of a concatenated string with unique characters
1,239
0.522
Medium
18,599