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/sort-an-array/discuss/648242/simple-of-simple
class Solution: def sortArray(self, nums: List[int]) -> List[int]: return sorted(nums)
sort-an-array
simple of simple
seunggabi
0
107
sort an array
912
0.594
Medium
14,800
https://leetcode.com/problems/sort-an-array/discuss/2166504/Python3-easy-to-understand-one-liner
class Solution: def sortArray(self, nums: List[int]) -> List[int]: return sorted(nums)
sort-an-array
Python3 easy to understand one liner
pro6igy
-2
90
sort an array
912
0.594
Medium
14,801
https://leetcode.com/problems/sort-an-array/discuss/1380141/One-LIne-Solution-Runtime%3A-280-ms-faster-than-88.62-of-Python3
class Solution: def sortArray(self, nums: List[int]) -> List[int]: return sorted(nums) #1 ``` ``` #2 import heapq class Solution: def sortArray(self, nums: List[int]) -> List[int]: heapq.heapify(nums) l=[] while(nums): l.append(heapq.heappop(nums)) return l ```
sort-an-array
One LIne Solution Runtime: 280 ms, faster than 88.62% of Python3
harshmalviya7
-4
158
sort an array
912
0.594
Medium
14,802
https://leetcode.com/problems/cat-and-mouse/discuss/1563154/Python3-dp-minimax
class Solution: def catMouseGame(self, graph: List[List[int]]) -> int: n = len(graph) @cache def fn(i, m, c): """Return """ if i == 2*n: return 0 # tie if m == 0: return 1 # mouse wins if m == c: return 2 # cat wins if i&1: # cat's turn tie = 0 for cc in graph[c]: if cc != 0: x = fn(i+1, m, cc) if x == 2: return 2 if x == 0: tie = 1 if tie: return 0 return 1 else: # mouse's turn tie = 0 for mm in graph[m]: x = fn(i+1, mm, c) if x == 1: return 1 if x == 0: tie = 1 if tie: return 0 return 2 return fn(0, 1, 2)
cat-and-mouse
[Python3] dp - minimax
ye15
0
212
cat and mouse
913
0.351
Hard
14,803
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2821961/Did-you-known-about-'gcd'-function-%3AD
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: x = Counter(deck).values() return reduce(gcd, x) > 1
x-of-a-kind-in-a-deck-of-cards
Did you known about 'gcd' function? :D
almazgimaev
0
3
x of a kind in a deck of cards
914
0.32
Easy
14,804
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2797650/Python3-Short-one-liner-with-explanation
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: return gcd(*Counter(deck).values())>1
x-of-a-kind-in-a-deck-of-cards
[Python3] Short one-liner with explanation
Berthouille
0
8
x of a kind in a deck of cards
914
0.32
Easy
14,805
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2647780/greatest-common-divisor-python-solution
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: d=defaultdict(int) for i in deck: d[i]+=1 for k in d: gcd=d[k] break for k in d: gcd=math.gcd(gcd,d[k]) return gcd!=1
x-of-a-kind-in-a-deck-of-cards
greatest common divisor python solution
abhayCodes
0
31
x of a kind in a deck of cards
914
0.32
Easy
14,806
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2224822/python-solution-oror-without-GCD
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: hash = {} for num in deck: if num not in hash: hash[num] = 0 hash[num] += 1 countArr = list(hash.values()) minCount = min(countArr) if minCount < 2: return False for i in range(2, minCount + 1): divisible = [a % i == 0 for a in countArr] if all(divisible): return True return False
x-of-a-kind-in-a-deck-of-cards
python solution || without GCD
lamricky11
0
121
x of a kind in a deck of cards
914
0.32
Easy
14,807
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2012943/Python-One-Liner-(x2)!
class Solution: def hasGroupsSizeX(self, deck): return reduce(gcd, Counter(deck).values()) >= 2
x-of-a-kind-in-a-deck-of-cards
Python - One-Liner (x2)!
domthedeveloper
0
99
x of a kind in a deck of cards
914
0.32
Easy
14,808
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2012943/Python-One-Liner-(x2)!
class Solution: def hasGroupsSizeX(self, deck): return gcd(*Counter(deck).values()) >= 2
x-of-a-kind-in-a-deck-of-cards
Python - One-Liner (x2)!
domthedeveloper
0
99
x of a kind in a deck of cards
914
0.32
Easy
14,809
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/1836529/1-Line-Python-Solution-oror-97-Faster-oror-Memory-less-than-60
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: return reduce(gcd, Counter(deck).values())>=2
x-of-a-kind-in-a-deck-of-cards
1-Line Python Solution || 97% Faster || Memory less than 60%
Taha-C
0
107
x of a kind in a deck of cards
914
0.32
Easy
14,810
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/1836529/1-Line-Python-Solution-oror-97-Faster-oror-Memory-less-than-60
class Solution: def hasGroupsSizeX(self, deck: List[int]) -> bool: C=Counter(deck).values() for i in range(2,len(deck)+1): if all([c%i==0 for c in C]): return True return False
x-of-a-kind-in-a-deck-of-cards
1-Line Python Solution || 97% Faster || Memory less than 60%
Taha-C
0
107
x of a kind in a deck of cards
914
0.32
Easy
14,811
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1359686/PYTHON-Best-solution-yet!-EXPLAINED-with-comments-to-make-life-easier.-O(n)-and-O(1)
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: """ Intuition(logic) is to find two maximums. One maximum is for left array and other maximum is for right array. But the condition is that, the right maximum should be such that, no element after that right maximum should be less than the left maximum. If there is any element after right maximum which is less than left maximum, that means there is another right maximum possible and therefore in that case assign left maximum to right maximum and keep searching the array for correct right maximum till the end. """ #start with both left maximum and right maximum with first element. left_max = right_max = nums[0] # our current index partition_ind = 0 # Iterate from 1 to end of the array for i in range(1,len(nums)): #update right_max always after comparing with each nums #in order to find our correct right maximum right_max = max(nums[i], right_max) """ if current element is less than left maximum, that means this element must belong to the left subarray. * so our partition index will be updated to current index * and left maximum will be updated to right maximum. Why left maximum updated to right maximum ? Because when we find any element less than left_maximum, that means the right maximum which we had till now is not valid and we have to find the valid right maximum again while iterating through the end of the loop. """ if nums[i] < left_max: left_max = right_max partition_ind = i return partition_ind+1
partition-array-into-disjoint-intervals
[PYTHON] Best solution yet! EXPLAINED with comments to make life easier. O(n) & O(1)
er1shivam
7
352
partition array into disjoint intervals
915
0.486
Medium
14,812
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1355377/Python3-The-easiest-way-to-solve-this-problem-in-my-opinion
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: lng = len(nums) maxx, minn = nums[0], min(nums[1:]) for i in range(lng): maxx = max(maxx, nums[i]) if minn == nums[i]: minn = min(nums[i + 1:]) if maxx <= minn: return i + 1
partition-array-into-disjoint-intervals
[Python3] The easiest way to solve this problem in my opinion
rn100799
1
31
partition array into disjoint intervals
915
0.486
Medium
14,813
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1355086/Python-simple-solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: ans=0 maxo=nums[0] maxtn=nums[0] for i in range(len(nums)): if nums[i]>=maxtn: pass else: ans=i maxtn=max(maxtn,nums[i],maxo) maxo=max(nums[i],maxo) return ans+1
partition-array-into-disjoint-intervals
Python simple solution
RedHeadphone
1
77
partition array into disjoint intervals
915
0.486
Medium
14,814
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1354489/Partition-Array-into-Disjoint-Intervals-Python-Easy-solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: a = list(accumulate(nums, max)) b = list(accumulate(nums[::-1], min))[::-1] for i in range(1, len(nums)): if a[i-1] <= b[i]: return i
partition-array-into-disjoint-intervals
Partition Array into Disjoint Intervals , Python , Easy solution
user8744WJ
1
120
partition array into disjoint intervals
915
0.486
Medium
14,815
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1354450/Partition-Array-into-Disjoint-Intervals%3A-Simple-Python-Solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: n = len(nums) left_length = 1 left_max = curr_max = nums[0] for i in range(1, n-1): if nums[i] < left_max: left_length = i+1 left_max = curr_max else: curr_max = max(curr_max, nums[i]) return left_length
partition-array-into-disjoint-intervals
Partition Array into Disjoint Intervals: Simple Python Solution
user6820GC
1
81
partition array into disjoint intervals
915
0.486
Medium
14,816
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/2495974/Best-Python3-implementation-oror-Easy-to-understand
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: prefix = [nums[0] for _ in range(len(nums))] suffix = [nums[-1] for _ in range(len(nums))] for i in range(1, len(nums)): prefix[i] = max(prefix[i-1], nums[i-1]) for i in range(len(nums)-2, -1, -1): suffix[i] = min(suffix[i+1], nums[i+1]) for i in range(0, len(nums)-1): if prefix[i] <= suffix[i]: return i+1
partition-array-into-disjoint-intervals
✔️ Best Python3 implementation || Easy to understand
explusar
0
19
partition array into disjoint intervals
915
0.486
Medium
14,817
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1863642/Python-2-Arrays
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: mina = [None] * len(nums) maxa = [None] * len(nums) maxa[0] = nums[0] mina[len(nums)-1] = nums[len(nums)-1] for i in range(1,len(nums)): maxa[i] = max(maxa[i-1], nums[i]) for i in range(len(nums)-2, -1, -1): mina[i] = min(mina[i+1], nums[i]) for i in range(len(nums)): if maxa[i] <= mina[i+1]: return i+1
partition-array-into-disjoint-intervals
Python 2 Arrays
DietCoke777
0
23
partition array into disjoint intervals
915
0.486
Medium
14,818
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1858264/Python-easy-to-read-and-understand-or-max-chunk-to-make-array-sorted-II
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: n = len(nums) left = [nums[0] for _ in range(n)] right = [nums[n-1] for _ in range(n)] for i in range(1, n): left[i] = max(left[i-1], nums[i]) for i in range(n-2, -1, -1): right[i] = min(right[i+1], nums[i]) right.append(float("inf")) for i in range(n): if left[i] <= right[i+1]: return i+1
partition-array-into-disjoint-intervals
Python easy to read and understand | max chunk to make array sorted II
sanial2001
0
33
partition array into disjoint intervals
915
0.486
Medium
14,819
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1667844/python-simple-O(n)-time-O(n)-space-solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: n = len(nums) # max(left) <= min(right) maxleft, minright = {}, {} maxv, minv = float('-inf'), float('inf') for i in range(n): maxv = max(maxv, nums[i]) maxleft[i] = maxv for i in range(n-1, -1, -1): minv = min(minv, nums[i]) minright[i] = minv for i in range(n-1): if maxleft[i] <= minright[i+1]: return i+1
partition-array-into-disjoint-intervals
python simple O(n) time, O(n) space solution
byuns9334
0
73
partition array into disjoint intervals
915
0.486
Medium
14,820
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1355817/Simple-Python-Solution-or-93-faster-or-Clean-solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: left_size,target,cur_max = 0,nums[0],nums[0] for i in range(1,len(nums)): if nums[i] < target : left_size = i target = cur_max cur_max = max(cur_max, nums[i]) return left_size+1
partition-array-into-disjoint-intervals
Simple Python Solution | 93% faster | Clean solution
shankha117
0
36
partition array into disjoint intervals
915
0.486
Medium
14,821
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1354831/clean-explained-comments-easy-min-and-max-prefix-sum-3-pass-solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: # if ALL in right are > ALL in small # then: # ====>(max of left) < (min of right) # simple... just calculate prefix max, and suffix min ;) # at this point if i make a break-then what will be the maximum? prefix_max = nums[:] suffix_min = nums[:] for i in range(1, len(nums)): prefix_max[i] = max(prefix_max[i-1], nums[i]) for j in range(len(nums)-2,-1,-1): suffix_min[j] = min(suffix_min[j+1], nums[j]) # try all values for the 'breakpoint'/'starting edge of right' for edge in range(1,len(nums)): if prefix_max[edge-1] <= suffix_min[edge]: return edge
partition-array-into-disjoint-intervals
clean explained comments easy min and max prefix sum 3 pass solution
yozaam
0
19
partition array into disjoint intervals
915
0.486
Medium
14,822
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1354681/Python-simple1-pass-O(n)-time-O(1)-space-faster-than-98.74-less-than-91.29
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: m = mnext = nums[0] s = 0 for i in range(len(nums)): if m > nums[i]: m = mnext s = i elif mnext < nums[i]: mnext = nums[i] return s + 1 ```
partition-array-into-disjoint-intervals
Python, simple,1 pass, O(n) time, O(1) space, faster than 98.74, less than 91.29%
MihailP
0
48
partition array into disjoint intervals
915
0.486
Medium
14,823
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1354592/Python3-Easy-Solution-Explained
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: for i in range(1, len(nums)): left = nums[:i] right = nums[i:] if max(left) <= min(right): print(left, right) return i
partition-array-into-disjoint-intervals
Python3 Easy Solution, Explained
chaudhary1337
0
22
partition array into disjoint intervals
915
0.486
Medium
14,824
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1354592/Python3-Easy-Solution-Explained
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: """ 1. all x in left <= all y in right === max(left) <= min(right) 2. both non empty 3. minimize len(left) """ # build direction: -> a_max = [nums[0]] # start at start for i in range(1, len(nums)): a_max.append(max(a_max[-1], nums[i])) # build direction: <- a_min = [nums[-1]] # start at end for i in reversed(range(0, len(nums)-1)): # reverse direction a_min.append(min(a_min[-1], nums[i])) a_min.reverse() # reversing the reversed list for i in range(1, len(nums)): if a_max[i-1] <= a_min[i]: # `i` is the place of split, and thus gives the length of `left` return i
partition-array-into-disjoint-intervals
Python3 Easy Solution, Explained
chaudhary1337
0
22
partition array into disjoint intervals
915
0.486
Medium
14,825
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1274290/Python-fast(~98)-and-simple
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: max_left = nums[0] min_right = min(nums[1:]) count = 1 for i in range(1, len(nums[1:]), 1): if max_left <= min_right: break max_left = max_left if nums[i] < max_left else nums[i] min_right = min_right if min_right < nums[i] else min(nums[i+1:]) count += 1 return count
partition-array-into-disjoint-intervals
[Python] fast(~98%) and simple
cruim
0
67
partition array into disjoint intervals
915
0.486
Medium
14,826
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1175299/python-O(n)-faster-than-98
class Solution: def partitionDisjoint(self, A) -> int: min_index = A.index(min(A)) maxN = max(A[:min_index+1]) minN = min(A[min_index+1:]) for i in range(min_index, len(A)-1): if A[i] > maxN: maxN = A[i] if A[i] == minN: minN = min(A[i+1:]) if maxN <= minN: return i+1
partition-array-into-disjoint-intervals
python, O(n), faster than 98%
dustlihy
0
55
partition array into disjoint intervals
915
0.486
Medium
14,827
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/955316/Python3-greedy-O(N)
class Solution: def partitionDisjoint(self, A: List[int]) -> int: ans = 0 mx, val = -inf, inf for i, x in enumerate(A, 1): mx = max(mx, x) if x < val: ans = i val = mx return ans
partition-array-into-disjoint-intervals
[Python3] greedy O(N)
ye15
0
69
partition array into disjoint intervals
915
0.486
Medium
14,828
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/955316/Python3-greedy-O(N)
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: ans = 0 mx = threshold = nums[0] for i, x in enumerate(nums): mx = max(mx, x) if x < threshold: # threshold to partition the array ans = i threshold = mx return ans + 1
partition-array-into-disjoint-intervals
[Python3] greedy O(N)
ye15
0
69
partition array into disjoint intervals
915
0.486
Medium
14,829
https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/882355/Python-3-or-Running-MinMax-O(N)-or-Explanation
class Solution: def partitionDisjoint(self, A: List[int]) -> int: n = len(A) large, small = [0] * n, [0] * n l, s = -sys.maxsize, sys.maxsize for i in range(n): large[i], small[n-1-i] = (l:=max(l, A[i])), (s:=min(s, A[n-1-i])) for i in range(n): if large[i] <= small[i+1]: return i+1 return -1
partition-array-into-disjoint-intervals
Python 3 | Running Min/Max, O(N) | Explanation
idontknoooo
0
194
partition array into disjoint intervals
915
0.486
Medium
14,830
https://leetcode.com/problems/word-subsets/discuss/2353565/Solution-Using-Counter-in-Python
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: result = [] tempDict = Counter() for w in words2: tempDict |= Counter(w) print(tempDict) for w in words1: if not tempDict - Counter(w): result.append(w) return result
word-subsets
Solution Using Counter in Python
AY_
26
1,200
word subsets
916
0.54
Medium
14,831
https://leetcode.com/problems/word-subsets/discuss/2352984/Python-or-SImple-and-Easy-or-Using-dictionaries-or-Count
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: ans = set(words1) letters = {} for i in words2: for j in i: count = i.count(j) if j not in letters or count > letters[j]: letters[j] = count for i in words1: for j in letters: if i.count(j) < letters[j]: ans.remove(i) break return list(ans)
word-subsets
Python | SImple and Easy | Using dictionaries | Count
revanthnamburu
14
1,100
word subsets
916
0.54
Medium
14,832
https://leetcode.com/problems/word-subsets/discuss/2356000/Python3-oror-12-lines-dict-and-counter-w-explanation-oror-TM%3A-8473
class Solution: # Suppose for example: # words1 = ['food', 'coffee', 'foofy'] # words2 = ['foo', 'off'] # # Here's the plan: # 1) Construct a dict in which the key is a char in # one or more words in words2, and the key's max # count in those words. # for 'foo': c2 = {'o': 2, 'f': 1} # for 'off': c2 = {'o': 1, 'f': 2} # so: d = {'o': 2, 'f': 2} # # 2) Use a counter for each word in words1 to determine # whether the word has at least the quantity of each char # in d: # for 'food' : c1 = {'o': 2, 'f': 1, 'd': 1} (fails at 'f') # for 'coffee': c1 = {'f': 2, 'e': 2, 'o': 1, 'c': 1 } (fails at 'o') # for 'foofy ': c1 = {'f': 2, 'o': 2, 'y': 1} (success) # # 3) return answer: # answer = ['foofy'] # def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: d, ans = defaultdict(int), [] for word in words2: # <-- 1) c2 = Counter(word) for ch in c2: d[ch] = max(d[ch], c2[ch]) for word in words1: # <-- 2) c1 = Counter(word) for ch in d: if c1[ch] < d[ch]: break else: ans.append(word) # <-- else executes only if the for-loop # completes without break return ans # <-- 3)
word-subsets
Python3 || 12 lines, dict & counter w/ explanation || T/M: 84%/73%
warrenruud
9
409
word subsets
916
0.54
Medium
14,833
https://leetcode.com/problems/word-subsets/discuss/2352799/Python-two-liner
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: w2 = reduce(operator.or_, map(Counter, words2)) return [w1 for w1 in words1 if Counter(w1) >= w2]
word-subsets
Python two-liner
blue_sky5
7
663
word subsets
916
0.54
Medium
14,834
https://leetcode.com/problems/word-subsets/discuss/956392/Python3-frequency-table-O(M%2BN)
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: freq = [0]*26 for w in B: temp = [0]*26 for c in w: temp[ord(c)-97] += 1 for i in range(26): freq[i] = max(freq[i], temp[i]) ans = [] for w in A: temp = [0]*26 for c in w: temp[ord(c)-97] += 1 if all(freq[i] <= temp[i] for i in range(26)): ans.append(w) return ans
word-subsets
[Python3] frequency table O(M+N)
ye15
5
324
word subsets
916
0.54
Medium
14,835
https://leetcode.com/problems/word-subsets/discuss/956392/Python3-frequency-table-O(M%2BN)
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: freq = Counter() for x in B: freq |= Counter(x) return [x for x in A if not freq - Counter(x)]
word-subsets
[Python3] frequency table O(M+N)
ye15
5
324
word subsets
916
0.54
Medium
14,836
https://leetcode.com/problems/word-subsets/discuss/1129213/Optimal-Solution-or-Python-easy-to-understand-with-comments-and-explanation
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: counters = defaultdict(dict) # put all word feq maps in counters for word_a in A: counters[word_a] = Counter(word_a) for word_b in B: counters[word_b] = Counter(word_b) def isSubset(a, b) -> bool: # check if b is subset of a counter_a = counters[a] counter_b = counters[b] # if counter_b has more keys then it can't be subset of a if len(counter_b.keys()) > len(counter_a.keys()): return False # can't be subset if any key in counter_b is not present in counter_a # or if the freq doesn't match for key in counter_b.keys(): if (key not in counter_a.keys()) or (counter_a[key] < counter_b[key]): return False # that means word b is subset of word a return True result = [] for word_a in A: universal = True for word_b in B: if not isSubset(word_a,word_b): universal = False break if universal: result.append(word_a) return result
word-subsets
Optimal Solution | Python easy to understand with comments and explanation
CaptainX
3
213
word subsets
916
0.54
Medium
14,837
https://leetcode.com/problems/word-subsets/discuss/1129213/Optimal-Solution-or-Python-easy-to-understand-with-comments-and-explanation
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: b_counter = defaultdict(int) # by default all key values would be 0 # create frequency map of B considering all words as a single word for word in B: char_freqmap = Counter(word) for ch in char_freqmap.keys(): # keep the freq which is greater b_counter[ch] = max(b_counter[ch], char_freqmap[ch]) result = [] for word in A: a_counter = Counter(word) if len(a_counter.keys()) < len(b_counter.keys()): continue universal = True for ch in b_counter.keys(): if ch not in a_counter or a_counter[ch] < b_counter[ch]: universal = False break if universal: result.append(word) return result
word-subsets
Optimal Solution | Python easy to understand with comments and explanation
CaptainX
3
213
word subsets
916
0.54
Medium
14,838
https://leetcode.com/problems/word-subsets/discuss/2353223/Python-SImple-Solution
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: mc = Counter() for w in words2: t = Counter(w) for i in t: mc[i] = max(mc[i],t[i]) ans = [] for w in words1: t = Counter(w) for i in mc: if mc[i]>t[i]: break else: ans.append(w) return ans
word-subsets
Python SImple Solution
RedHeadphone
2
369
word subsets
916
0.54
Medium
14,839
https://leetcode.com/problems/word-subsets/discuss/2359914/python-oror-counter
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: res = [] word2Counter = Counter() for word in words2: word2Counter |= Counter(word) for word in words1: tempCounter = Counter(word) tempCounter.subtract(word2Counter) if min(tempCounter.values()) >= 0: res.append(word) return res
word-subsets
python || counter
noobj097
1
14
word subsets
916
0.54
Medium
14,840
https://leetcode.com/problems/word-subsets/discuss/2353901/Python-or-Using-dictionary-or-No-special-function-or-Easy
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: #Function to create specific dictionary with count of letters def create_dic(word): has={} for i in word: if i in has: has[i]+=1 else: has[i]=1 return has #Necassary variables ans=[] words1_dict=[] words2_dict={} #Creating list of all the dictionaries in word1 for i in words1: words1_dict.append(create_dic(i)) #Adding all the letters of word2 in one dictionary for i in words2: #Create dictionary of each word temp=create_dic(i) #Add these dictionary to a single dictionary for j in temp: if j in words2_dict: words2_dict[j]=max(words2_dict[j],temp[j]) else: words2_dict[j]=temp[j] #Final condition to filter the answers for i in range(len(words1_dict)): flag=True for k in words2_dict: if k not in words1_dict[i] or words2_dict[k]>words1_dict[i][k]: flag=False break if flag: ans.append(words1[i]) return ans
word-subsets
Python | Using dictionary | No special function | Easy
RickSanchez101
1
61
word subsets
916
0.54
Medium
14,841
https://leetcode.com/problems/word-subsets/discuss/2353450/Faster-than-87.33-of-Python3-Proved
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: char = [0]*26 for word in words2: hash_w2 = {} for w in word: if w not in hash_w2: hash_w2[w] = 0 hash_w2[w] += 1 char[ord(w)-97] = max(hash_w2[w], char[ord(w)-97]) res = [] for word in words1: hash_w = {i:0 for i in word} for w in word: hash_w[w] += 1 flag = False for i in range(26): if char[i] == 0: continue if chr(97+i) in hash_w and char[i] <= hash_w[chr(97+i)]: flag = True else: flag = False![Uploading file...]() break if flag: res.append(word) return res
word-subsets
Faster than 87.33% of Python3 [Proved]
sagarhasan273
1
18
word subsets
916
0.54
Medium
14,842
https://leetcode.com/problems/word-subsets/discuss/2175281/Python3-O(m%2Bn)-runtime%3A-2683ms-5.20-memory%3A-18.1mb-98.62
class Solution: # O(m+n)where m is words1(word) and n is words2(word) # runtime: 2683ms 5.20% memory: 18.1mb 98.62% def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: result = [] maxCount = [0] * 26 for word in words2: charFreq = self.getFreqOfChar(word) for j in range(26): maxCount[j] = max(maxCount[j], charFreq[j]) for idx, word in enumerate(words1): word1CharFreq = self.getFreqOfChar(word) flag = True for i in range(26): if maxCount[i] > word1CharFreq[i]: flag = False break if flag: result.append(word) return result def getFreqOfChar(self, string): freq = [0] * 26 for j in string: freq[ord(j)-ord('a')] += 1 return freq
word-subsets
Python3 O(m+n) runtime: 2683ms 5.20% memory: 18.1mb 98.62%
arshergon
1
136
word subsets
916
0.54
Medium
14,843
https://leetcode.com/problems/word-subsets/discuss/2603349/simple-pythonic-solutiuon
class Solution: # Reduce the words in words2 to a single word with max frequencies of each of the characters from words of words2 # This way one can make the B map # Now check all the words in words1 # The ones with frequency more than the required ones will qualify def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: B = defaultdict(int) for word in words2: count = Counter(word) for char in count: B[char] = max(B[char], count[char]) res = [] for word in words1: count = Counter(word) for c in B: if B[c] > count[c]: break else: res.append(word) return res
word-subsets
simple pythonic solutiuon
shiv-codes
0
43
word subsets
916
0.54
Medium
14,844
https://leetcode.com/problems/word-subsets/discuss/2357187/Python3-or-Beats-85.84
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] mp = {} for i in chars: mp[i] = 0 for word in words2: mp2 = {} for i in word: if mp2.get(i) is None: mp2[i] = 0 mp2[i] += 1 mp[i] = max(mp2[i], mp[i]) ans = [] for word in words1: mp2 = {} for i in word: if mp2.get(i) is None: mp2[i] = 0 mp2[i] += 1 flg = True for ch in mp.keys(): if mp2.get(ch, 0) < mp[ch]: flg = False break if flg: ans.append(word) return ans
word-subsets
Python3 | Beats 85.84%
fake_death
0
19
word subsets
916
0.54
Medium
14,845
https://leetcode.com/problems/word-subsets/discuss/2355674/Python3-or-Explanation
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: totalWordCount = {} for b in words2: temp = Counter(b) for key, value in temp.items(): if key not in totalWordCount: totalWordCount[key] = value else: totalWordCount[key] = max(value, totalWordCount[key]) output = [] for a in words1: temp = Counter(a) if all(k in temp and temp[k] >= v for k, v in totalWordCount.items()): output.append(a) return output
word-subsets
Python3 | Explanation
arvindchoudhary33
0
15
word subsets
916
0.54
Medium
14,846
https://leetcode.com/problems/word-subsets/discuss/2355050/Python-Simple-and-Easy
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: s=set(''.join(words2)) mWord={} for i in s: mWord[i]=max([word.count(i) for word in words2]) def isUniversal(word): wordMap={w: word.count(w) for w in word} for k,v in mWord.items(): if k in wordMap: if wordMap[k]>=v: continue return False return True return filter(isUniversal,words1)
word-subsets
Python Simple and Easy
Reversaidx
0
16
word subsets
916
0.54
Medium
14,847
https://leetcode.com/problems/word-subsets/discuss/2354707/Python3-oror-Fast-and-Easy-Understanding
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: res = [] need = {} for w in words2: temp = {} for c in w: temp[c] = 1 + temp.get(c, 0) if not need: need = temp else: for k in temp: need[k] = max(need[k], temp[k]) if k in need else temp[k] n, h = len(need), 0 for w in words1: have = {} ignore = set() h = 0 for c in w: if c in need: have[c] = 1 + have.get(c, 0) if c in need and have[c] == need[c] and c not in ignore: h += 1 ignore.add(c) if h == n: res.append(w) return res
word-subsets
Python3 || Fast and Easy Understanding
Dewang_Patil
0
42
word subsets
916
0.54
Medium
14,848
https://leetcode.com/problems/word-subsets/discuss/2354425/Python-solution
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: chars = [0] * 26 for w in words2: curr = [0] * 26 for c in w: curr[ord(c) - ord('a')] += 1 for i in range(26): chars[i] = max(chars[i], curr[i]) result = [] for w in words1: curr = [0] * 26 for c in w: curr[ord(c) - ord('a')] += 1 isvalid = True for i in range(26): if chars[i] > curr[i]: isvalid = False break if isvalid: result.append(w) return result
word-subsets
Python solution
user6397p
0
15
word subsets
916
0.54
Medium
14,849
https://leetcode.com/problems/word-subsets/discuss/2354326/Python-Faster-than-97.00-using-Max-Frequency-Table-oror-Documented
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: result = []; maxDict = {} # generate frequency table for each word in words2 (max requirment of letters) for word in words2: dict = {} for c in word: dict[c] = dict.get(c, 0) + 1 # store maximum frequency of letter for c in dict: maxDict[c] = max(dict[c], maxDict.get(c, 0)) # pick word from words1, and check if it is universal for word in words1: dict = {} # generate frequency table for word on words1 for c in word: dict[c] = dict.get(c, 0) + 1 # if frequency of any letter in maxDict is greater than one in word, return false isUniversal = True for k, v in maxDict.items(): if v > dict.get(k, 0): isUniversal = False break # word is universal, add to the results if isUniversal: result.append(word) return result
word-subsets
[Python] Faster than 97.00% using Max Frequency Table || Documented
Buntynara
0
20
word subsets
916
0.54
Medium
14,850
https://leetcode.com/problems/word-subsets/discuss/2354026/Python-oror-Using-Hashmap
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: # create hashmap of words2 and compare this hash map with every word in words1 result = list() chardict = dict() for i in words2: for j in i: count = i.count(j) if j not in chardict.keys(): chardict[j] = count else: chardict[j] = max(chardict[j],count) for w in words1: count = 0 for key,val in chardict.items(): if key in w and val <= w.count(key): count +=1 if count == len(chardict.keys()): result.append(w) return result
word-subsets
Python || Using Hashmap
dyforge
0
26
word subsets
916
0.54
Medium
14,851
https://leetcode.com/problems/word-subsets/discuss/2353677/Python3-Pythonic-way-in-2-lines-of-code
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: universal_word2 = reduce(operator.or_, map(Counter, words2)) return [word for word in words1 if universal_word2 <= Counter(word)]
word-subsets
[Python3] Pythonic way in 2 lines of code
geka32
0
31
word subsets
916
0.54
Medium
14,852
https://leetcode.com/problems/word-subsets/discuss/2353370/python-solution-using-hashmap
class Solution(object): def wordSubsets(self, words1, words2): """ :type words1: List[str] :type words2: List[str] :rtype: List[str] """ res = [] hashmap = {} for i in words2: temp = {} for j in i: temp[j] = temp.get(j , 0) + 1 for j in temp: hashmap[j] = max(hashmap.get(j , 0) , temp[j]) for i in words1: temp = {} for j in i: temp[j] = temp.get(j , 0) + 1 if all([k in temp and v <= temp[k] for k, v in hashmap.items()]): res.append(i) return res
word-subsets
python solution using hashmap
jhaprashant1108
0
45
word subsets
916
0.54
Medium
14,853
https://leetcode.com/problems/word-subsets/discuss/2353116/PythonororEasy-Understanding
class Solution: from collections import defaultdict def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: def count(word): output = defaultdict(int) for i in word: output[i] += 1 return output words2_dict = defaultdict(int) for i in words2: temp_dict = count(i) for key in temp_dict: if temp_dict[key] > words2_dict[key]: words2_dict[key] = temp_dict[key] ans = [] for j in words1: i = 0 word1_dict = count(j) for key in words2_dict: if words2_dict[key] > word1_dict[key]: i = 1 break if i == 0: ans.append(j) return ans
word-subsets
Python||Easy Understanding
songmiao
0
25
word subsets
916
0.54
Medium
14,854
https://leetcode.com/problems/word-subsets/discuss/2352914/python-solution-O(N)-Performance%3A686-ms-96.33
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: dwords2 = {} dwords1 = [] ans = [] for w in words2: tmpd = {} for ch in w: if ch not in tmpd: tmpd[ch] = 0 tmpd[ch] += 1 for ch in tmpd: if ch not in dwords2: dwords2[ch] = 0 dwords2[ch] = max(dwords2[ch],tmpd[ch]) for word1 in words1: tmpd = {} for ch in word1: if ch not in tmpd: tmpd[ch] = 0 tmpd[ch] += 1 dwords1.append(tmpd) for i,t in enumerate(dwords1): fail = False for ch in dwords2: if ch not in t: fail = True break elif t[ch] < dwords2[ch]: fail = True break if not fail : ans.append(words1[i]) return ans
word-subsets
python solution O(N), Performance:686 ms, 96.33%
cheoljoo
0
45
word subsets
916
0.54
Medium
14,855
https://leetcode.com/problems/word-subsets/discuss/1343280/Simple-Python-Solution-O(N)
class Solution: def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]: d={} for i in words2: d2={} for j in i: if(j in d2.keys()): d2[j]=d2[j]+1 else: d2[j]=1 for k in d2.keys(): if(k in d.keys() and d2[k]>d[k]) or (k not in d.keys() ) : d[k]=d2[k] l3=[] for i in words1: d2={} for j in i: if(j in d2.keys()): d2[j]=d2[j]+1 else: d2[j]=1 f=0 for k in d.keys(): if(k in d2.keys() and d2[k]<d[k]) or (k not in d2.keys() ) : f=1 break if(f==0): l3.append(i) return l3
word-subsets
Simple Python Solution O(N)
Rajashekar_Booreddy
0
245
word subsets
916
0.54
Medium
14,856
https://leetcode.com/problems/word-subsets/discuss/1128869/Python3-Using-a-dictionary-or-faster-than-94
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: d ={} for x in B: for b in x: if b in d: d[b] = max(x.count(b), d[b]) else: d[b] = x.count(b) tmp = [] for a in A: d1 = d.copy() for i in a: if i in d1 : d1[i] -= 1 if d1[i] < 0: d1[i] = 0 if sum(list(d1.values())) == 0: tmp.append(a) return tmp
word-subsets
[Python3] Using a dictionary | faster than 94%
SushilG96
0
85
word subsets
916
0.54
Medium
14,857
https://leetcode.com/problems/word-subsets/discuss/1128057/Python3-with-comments
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: #reduce all b's into a single hash table hashTable = {} for b in B: temp = Counter(b) for i in temp: hashTable[i] = max(hashTable.get(i,0),temp[i]) #compare hashTable to every word in A res = [] for a in A: a_table = Counter(a) for i in hashTable: #if the letter exists in a AND the number of occurrences in a is greater or equal to occurences in hash table if a_table.get(i) and hashTable[i] <= a_table[i]: continue break else: #appends to answer only if break keyword has not been run res.append(a) return res
word-subsets
Python3 with comments
JJT007
0
105
word subsets
916
0.54
Medium
14,858
https://leetcode.com/problems/word-subsets/discuss/1101433/Python-Soln-using-Dictionary!!
class Solution: def wordSubsets(self, A: List[str], B: List[str]) -> List[str]: ans=[] maind={} for i in B: d={} for j in i: if j in d: d[j]+=1 else: d[j]=1 for j in i: if j not in maind: maind[j]=d[j] if j not in d: d[j]=0 maind[j]=max(maind[j],d[j]) # print(maind) for i in A: d1={} f=True for j in i: if j in d1: d1[j]+=1 else: d1[j]=1 # print(d1) for j in maind: if j not in d1: d1[j]=-1 # print( maind[j],d1[j]) if maind[j]>d1[j]: f=False break if f: ans.append(i) return ans
word-subsets
Python Soln using Dictionary!!
harshvivek14
0
147
word subsets
916
0.54
Medium
14,859
https://leetcode.com/problems/reverse-only-letters/discuss/337853/Solution-in-Python-3
class Solution: def reverseOnlyLetters(self, S: str) -> str: S = list(S) c = [c for c in S if c.isalpha()] for i in range(-1,-len(S)-1,-1): if S[i].isalpha(): S[i] = c.pop(0) return "".join(S) - Python 3 - Junaid Mansuri
reverse-only-letters
Solution in Python 3
junaidmansuri
9
1,100
reverse only letters
917
0.615
Easy
14,860
https://leetcode.com/problems/reverse-only-letters/discuss/1277595/easy-two-pointer-or-python
class Solution: def reverseOnlyLetters(self, s: str) -> str: y='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' one = 0 two = len(s)-1 s= list(s) while one < two: if s[one] in y: if s[two] in y: s[one], s[two] = s[two] , s[one] one+=1 two-=1 else: two-=1 else: one+=1 return ''.join(s)
reverse-only-letters
easy two pointer | python
chikushen99
7
416
reverse only letters
917
0.615
Easy
14,861
https://leetcode.com/problems/reverse-only-letters/discuss/2388988/Faster-than-97-super-simple-python-code
class Solution: def reverseOnlyLetters(self, s: str) -> str: l = [] for i in s: if i.isalpha(): l.append(i) l = l[::-1] for i, c in enumerate(s): if c.isalpha() == False: l.insert(i, c) return "".join(l)
reverse-only-letters
Faster than 97% super simple python code
pro6igy
1
92
reverse only letters
917
0.615
Easy
14,862
https://leetcode.com/problems/reverse-only-letters/discuss/2166451/Python3-O(n)-oror-O(n)-if-return-result-don't-count-as-extra-space%3A-O(1)
class Solution: def reverseOnlyLetters(self, string: str) -> str: newString = list(string) left, right = 0, len(newString) - 1 while left < right: while left < right and newString[left].isalpha() == False: left += 1 while right > left and newString[right].isalpha() == False: right -= 1 newString[left], newString[right] = newString[right], newString[left] left += 1 right -= 1 return ''.join(newString)
reverse-only-letters
Python3 O(n) || O(n) if return result don't count as extra space: O(1)
arshergon
1
77
reverse only letters
917
0.615
Easy
14,863
https://leetcode.com/problems/reverse-only-letters/discuss/1463115/Simple-Python-Solution
class Solution: def reverseOnlyLetters(self, s: str) -> str: s, left, right = list(s), 0, len(s) - 1 while right >= left: if s[left].isalpha() and s[right].isalpha(): s[left], s[right] = s[right], s[left] left += 1 right -= 1 elif s[left].isalpha(): right -= 1 elif s[right].isalpha(): left += 1 else: left += 1 right -= 1 return ''.join(s)
reverse-only-letters
Simple Python Solution
HadaEn
1
114
reverse only letters
917
0.615
Easy
14,864
https://leetcode.com/problems/reverse-only-letters/discuss/1444543/Python-Two-Lines
class Solution: def reverseOnlyLetters(self, s: str) -> str: stack = [ c for c in s if c.isalpha() ] return "".join([ c if not c.isalpha() else stack.pop() for idx, c in enumerate(s) ])
reverse-only-letters
[Python] Two Lines
dev-josh
1
76
reverse only letters
917
0.615
Easy
14,865
https://leetcode.com/problems/reverse-only-letters/discuss/1122839/python
class Solution: def reverseOnlyLetters(self, S: str) -> str: S = list(S) left = 0 right = len(S) - 1 while left < right: if not S[left].isalpha(): left += 1 continue if not S[right].isalpha(): right -= 1 continue S[left], S[right] = S[right], S[left] left += 1 right -= 1 return ''.join(S)
reverse-only-letters
python
charmeleon
1
91
reverse only letters
917
0.615
Easy
14,866
https://leetcode.com/problems/reverse-only-letters/discuss/2824900/Python-Beginner-Friendly-List
class Solution: def reverseOnlyLetters(self, s: str) -> str: l = [] l1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z','A','B','C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S', 'T','U','V','U','W','X','Y','Z'] l2 = [] l3 = [] for i in range(len(s)): if s[i] in l1: l.append(s[i]) else: l2.append(i) l3.append(s[i]) l.reverse() for i in range(len(l2)): l.insert(l2[i],l3[i]) return "".join(l)
reverse-only-letters
Python - Beginner Friendly - List
spraj_123
0
3
reverse only letters
917
0.615
Easy
14,867
https://leetcode.com/problems/reverse-only-letters/discuss/2819656/Solution-For-reverse-program-in-python
class Solution: def reverseOnlyLetters(self, s: str) -> str: l , r = 0, len(s)-1 s=list(s) while l<r: while not s[l].isalpha() and l<r: l+=1 while not s[r].isalpha() and l<r: r-=1 s[l],s[r]=s[r],s[l] l+=1 r-=1 return "".join(s)
reverse-only-letters
Solution For reverse program in python
myselfhetvi
0
1
reverse only letters
917
0.615
Easy
14,868
https://leetcode.com/problems/reverse-only-letters/discuss/2804241/Easy-Solution-oror-O(n)
class Solution: def reverseOnlyLetters(self, s: str) -> str: low = 0 high = len(s)-1 s= list(s) while(low<high): if(s[low].isalpha() and s[high].isalpha()): temp = s[low] s[low]= s[high] s[high]= temp low+=1 high-=1 elif(s[low].isalpha() and not s[high].isalpha()): high-=1 elif(not s[low].isalpha() and s[high].isalpha()): low+=1 elif(not s[low].isalpha() and not s[high].isalpha()): low+=1 high-=1 return ''.join(s)
reverse-only-letters
Easy Solution || O(n)
hasan2599
0
2
reverse only letters
917
0.615
Easy
14,869
https://leetcode.com/problems/reverse-only-letters/discuss/2804235/Easy-Solution-oror-O(n)
class Solution: def reverseOnlyLetters(self, s: str) -> str: low = 0 high = len(s)-1 s= list(s) while(low<high): if(s[low].isalpha() and s[high].isalpha()): s[low],s[high]= s[high],s[low] low+=1 high-=1 elif(s[low].isalpha() and not s[high].isalpha()): high-=1 elif(not s[low].isalpha() and s[high].isalpha()): low+=1 elif(not s[low].isalpha() and not s[high].isalpha()): low+=1 high-=1 return ''.join(s)
reverse-only-letters
Easy Solution || O(n)
hasan2599
0
2
reverse only letters
917
0.615
Easy
14,870
https://leetcode.com/problems/reverse-only-letters/discuss/2781804/python-easy-iteration-and-swap
class Solution: def reverseOnlyLetters(self, s: str) -> str: s=list(s) alphabet = list(string.ascii_lowercase) alphabet.extend(string.ascii_uppercase) l=0 r=len(s)-1 while l<r: while s[l] not in alphabet and l<r : l+=1 while s[r] not in alphabet and l<r: r-=1 s[l],s[r]=s[r],s[l] l+=1 r-=1 return ''.join(s)
reverse-only-letters
python easy iteration and swap
sahityasetu1996
0
1
reverse only letters
917
0.615
Easy
14,871
https://leetcode.com/problems/reverse-only-letters/discuss/2748350/Python-and-Golang
class Solution: def reverseOnlyLetters(self, s: str) -> str: letters = [] for char in s: if char.isalpha(): letters.append(char) result = [] for char in s: if char.isalpha(): result.append(letters.pop()) else: result.append(char) return ''.join(result)
reverse-only-letters
Python and Golang答え
namashin
0
10
reverse only letters
917
0.615
Easy
14,872
https://leetcode.com/problems/reverse-only-letters/discuss/2736945/Python-simple-and-fast-solution
class Solution: def reverseOnlyLetters(self, s: str) -> str: s = list(s) l, r = 0, len(s) - 1 while l < r: while not s[l].isalpha(): l += 1 if l == r: return ''.join(s) while not s[r].isalpha(): r -= 1 s[l], s[r] = s[r], s[l] l += 1 r -= 1 return ''.join(s)
reverse-only-letters
Python simple and fast solution
Mark_computer
0
10
reverse only letters
917
0.615
Easy
14,873
https://leetcode.com/problems/reverse-only-letters/discuss/2470238/Two-pointers-using-Python
class Solution: def reverseOnlyLetters(self, s: str) -> str: left = 0 right = len(s) - 1 s = list(s) while left < right: if not s[left].isalpha(): left += 1 elif not s[right].isalpha(): right -= 1 else: s[left], s[right] = s[right], s[left] left += 1 right -= 1 return "".join(s)
reverse-only-letters
Two pointers using Python
Monicaaaaaa
0
34
reverse only letters
917
0.615
Easy
14,874
https://leetcode.com/problems/reverse-only-letters/discuss/2294557/Python-using-Regular-Expression
class Solution: def reverseOnlyLetters(self, s: str) -> str: f = re.findall('[A-Za-z]',s)[::-1] s = list(s) i = 0 for x in range(len(s)): if re.match('[A-Za-z]',s[x]): s[x] = f[i] i+=1 return(''.join(s))
reverse-only-letters
Python using Regular Expression
Yodawgz0
0
27
reverse only letters
917
0.615
Easy
14,875
https://leetcode.com/problems/reverse-only-letters/discuss/2032806/Python-Simple-and-Easy-Solution-oror-Slack
class Solution: def reverseOnlyLetters(self, s: str) -> str: alphabets = [i for i in s if i.isalpha()] res = [] for i in range(len(s)): if s[i].isalpha(): res.append(alphabets.pop()) else: res.append(s[i]) return "".join(res)
reverse-only-letters
Python - Simple and Easy Solution || Slack
dayaniravi123
0
82
reverse only letters
917
0.615
Easy
14,876
https://leetcode.com/problems/reverse-only-letters/discuss/1988937/98.86-faster-using-list-comprehension
class Solution: def reverseOnlyLetters(self, s: str) -> str: letters = list(reversed([c for c in s if c.isalpha()])) for i, symbol in enumerate(s): if not symbol.isalpha(): letters.insert(i, symbol) return "".join(letters)
reverse-only-letters
98.86% faster using list comprehension
andrewnerdimo
0
92
reverse only letters
917
0.615
Easy
14,877
https://leetcode.com/problems/reverse-only-letters/discuss/1983679/Easiest-and-Simplest-Python3-Solution-or-Beginner-friendly-Approach-or-100-Faster
class Solution: def reverseOnlyLetters(self, s: str) -> str: temp=[] for i in s: if i.isalpha(): temp.append(i) ss="".join(temp) ss=ss[::-1] # print(ss) temp.clear() j=0 for i in range(len(s)): if s[i].isalpha(): temp.append(ss[j]) j+=1 else: temp.append(s[i]) return ("".join(temp))
reverse-only-letters
Easiest & Simplest Python3 Solution | Beginner-friendly Approach | 100% Faster
RatnaPriya
0
75
reverse only letters
917
0.615
Easy
14,878
https://leetcode.com/problems/reverse-only-letters/discuss/1951934/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def reverseOnlyLetters(self, s: str) -> str: alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" l, r = 0, len(s)-1 arr = ['']*len(s) result = "" while l<=r: if s[l] in alpha and s[r] in alpha: arr[l] = s[r] arr[r] = s[l] l+=1 r-=1 elif s[l] in alpha and s[r] not in alpha: r-=1 elif s[l] not in alpha and s[r] in alpha: l+=1 else: l+=1 r-=1 for i, n in enumerate(arr): if n == '': arr[i] = s[i] for i in arr: result+=i return result
reverse-only-letters
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
77
reverse only letters
917
0.615
Easy
14,879
https://leetcode.com/problems/reverse-only-letters/discuss/1902198/Python-beginner-friendly-solution
class Solution: def reverseOnlyLetters(self, s: str) -> str: rev_let = ''.join(x for x in s if x.isalpha())[::-1] res = "" pos = 0 for i in range(len(s)): if s[i].isalpha(): res += rev_let[pos] pos += 1 else: res += s[i] return res
reverse-only-letters
Python beginner friendly solution
alishak1999
0
62
reverse only letters
917
0.615
Easy
14,880
https://leetcode.com/problems/reverse-only-letters/discuss/1638690/Python-Beats-96
class Solution: def reverseOnlyLetters(self, s: str) -> str: ans = '' for i in range(len(s)): if s[i].isalpha(): ans += s[i] ans = ans[::-1] s = [char for char in s] j = 0 for i in range(len(s)): if s[i].isalpha(): s[i] =ans[j] j += 1 return ''.join(s)
reverse-only-letters
Python Beats 96%
ElyasGoli
0
70
reverse only letters
917
0.615
Easy
14,881
https://leetcode.com/problems/reverse-only-letters/discuss/1573757/Python3-solution-82-faster
class Solution: def reverseOnlyLetters(self, s: str) -> str: s1 = "" for x in s: if x.isalpha(): s1 += x s2 = s1[::-1] s3 = "" k = 0 for i in range(len(s)): if s[i].isalpha(): s3 += s2[k] k += 1 else: s3 += s[i] return s3 ```
reverse-only-letters
Python3 solution 82% faster
Abhijeeth01
0
122
reverse only letters
917
0.615
Easy
14,882
https://leetcode.com/problems/reverse-only-letters/discuss/1480461/Two-pointer-solution-in-Python
class Solution: def reverseOnlyLetters(self, s: str) -> str: i, j, s = 0, len(s) - 1, list(s) while i < j: is_alpha = (s[i].isalpha(), s[j].isalpha()) if all(is_alpha): s[i], s[j], i, j = s[j], s[i], i + 1, j - 1 elif not is_alpha[0]: i += 1 elif not is_alpha[1]: j -= 1 return "".join(s)
reverse-only-letters
Two-pointer solution in Python
mousun224
0
87
reverse only letters
917
0.615
Easy
14,883
https://leetcode.com/problems/reverse-only-letters/discuss/1463709/Reverse-Only-Letters-or-Python-O(n)
class Solution: def reverseOnlyLetters(self, s: str) -> str: start = 0 end = len(s) - 1 s = list(s) while start < end: if s[start].isalpha() and s[end].isalpha(): s[start], s[end] = s[end], s[start] start += 1 end -= 1 elif not s[start].isalpha(): start += 1 else: end -= 1 return "".join(s)
reverse-only-letters
Reverse Only Letters | Python O(n)
mohanhamal999
0
57
reverse only letters
917
0.615
Easy
14,884
https://leetcode.com/problems/reverse-only-letters/discuss/1463667/Python3-Two-Pointers
class Solution: def reverseOnlyLetters(self, s: str) -> str: s = list(s) left, right = 0, len(s) - 1 while left < right: while left < len(s) and not s[left].isalpha(): left += 1 while right > -1 and not s[right].isalpha(): right -= 1 if left >= right: break s[left], s[right] = s[right], s[left] left += 1 right -= 1 return ''.join(s)
reverse-only-letters
[Python3] Two Pointers
maosipov11
0
34
reverse only letters
917
0.615
Easy
14,885
https://leetcode.com/problems/reverse-only-letters/discuss/1463516/2-Python-Solutions%3A-letter-stack-and-2-pointers-easy-understand
class Solution: def reverseOnlyLetters(self, s: str) -> str: # method 1: two pointers head, tail = 0, len(s)-1 res = list(s) while head < tail: if not res[head].isalpha(): # head index is not alphabet, move head forward head += 1 elif not res[tail].isalpha(): # tail index is not alphabet, move tail backward tail -= 1 else: res[head], res[tail] = res[tail], res[head] # exchange position head += 1 tail -= 1 return ''.join(res) # method 2: stacking chars = [c for c in s if c.isalpha()] # extract alphabets res = list() for c in s: if c.isalpha(): # if position is alphabet, pop alphabets list to this index res.append(chars.pop()) else: # append non-alphabets res.append(c) return "".join(res)
reverse-only-letters
2 Python Solutions: letter stack and 2 pointers easy understand
JieYuLin
0
22
reverse only letters
917
0.615
Easy
14,886
https://leetcode.com/problems/reverse-only-letters/discuss/1463025/Python-Solution
class Solution: def reverseOnlyLetters(self, s: str) -> str: n = len(s) ch = [''] * n start, end = 0, n - 1 while start < end: if s[start].isalpha() and s[end].isalpha(): ch[start], ch[end] = s[end], s[start] start += 1 end -= 1 if not (s[start].isalpha()): ch[start] = s[start] start += 1 if not (s[end].isalpha()): ch[end] = s[end] end -= 1 if start == end: ch[start] = s[start] return "".join(ch)
reverse-only-letters
Python Solution
mariandanaila01
0
71
reverse only letters
917
0.615
Easy
14,887
https://leetcode.com/problems/reverse-only-letters/discuss/1446705/Python3-solution-or-easy-solution
class Solution: def reverseOnlyLetters(self, s: str) -> str: # get all the letters in a list # reverse the list of letters # replace the letters form s with the ones from letters s = list(s) letters = [] for i in range(len(s)): if s[i].isalpha(): letters.append(s[i]) j = 0 letters.reverse() for i in range(len(s)): if s[i].isalpha(): s[i] = letters[j] j += 1 return "".join(s)
reverse-only-letters
Python3 solution | easy solution
FlorinnC1
0
65
reverse only letters
917
0.615
Easy
14,888
https://leetcode.com/problems/reverse-only-letters/discuss/1429023/Using-Two-pointer-Technique-with-100-Faster-greater-(O)N
class Solution: def reverseOnlyLetters(self, s: str) -> str: first = 0 last = len(s) - 1 s = list(s) helper = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' while first < last: if s[last] not in helper: last -= 1 if s[first] not in helper: first += 1 if s[first] in helper and s[last] in helper: s[first], s[last] = s[last], s[first] first += 1 last -= 1 return "".join(s)
reverse-only-letters
Using Two pointer Technique with 100% Faster -> (O)N
yugalshah
0
30
reverse only letters
917
0.615
Easy
14,889
https://leetcode.com/problems/reverse-only-letters/discuss/1308254/Python-Solution-Two-Pointers
class Solution: def reverseOnlyLetters(self, s: str) -> str: if not s or len(s) == 1: return s i,j,l = 0, len(s)-1, list(s) while i < j: if l[i].isalpha() and l[j].isalpha(): l[i], l[j] = l[j], l[i] i += 1 j -= 1 elif l[i].isalpha(): j -= 1 elif l[j].isalpha(): i += 1 else: i += 1 j -= 1 return ''.join(l)
reverse-only-letters
Python Solution - Two Pointers
5tigerjelly
0
58
reverse only letters
917
0.615
Easy
14,890
https://leetcode.com/problems/reverse-only-letters/discuss/1240127/python-solution-90-fast
class Solution: def reverseOnlyLetters(self, s: str) -> str: indexdata = [] textreocrd =[] for i in range(0,len(s)): if s[i].isalpha(): textreocrd.append(s[i]) else: indexdata.append([i,s[i]]) textreocrd.reverse() for i in indexdata: ind = i[0] val = i[1] textreocrd.insert(ind,val) return "".join(textreocrd)
reverse-only-letters
python solution 90% fast
Beastchariot
0
56
reverse only letters
917
0.615
Easy
14,891
https://leetcode.com/problems/reverse-only-letters/discuss/1144872/Python-Stack-implementation-or-O(N)-Time-O(N)-Space
class Solution: def reverseOnlyLetters(self, S: str) -> str: stack = [] s = "" for i in range(len(S)): if S[i].isalpha(): stack.append(S[i]) for i in S: if not i.isalpha(): s += i else: s += stack.pop() return s
reverse-only-letters
Python Stack implementation | O(N) Time O(N) Space
vanigupta20024
0
72
reverse only letters
917
0.615
Easy
14,892
https://leetcode.com/problems/reverse-only-letters/discuss/1097296/Python3-simple-solution-using-two-approaches
class Solution: def reverseOnlyLetters(self, S: str) -> str: i = 0 j = len(S)-1 a = '' while i < len(S): if S[i].isalpha() and S[j].isalpha(): a += S[j] j -= 1 i += 1 elif not S[i].isalpha(): a += S[i] i += 1 else: j -= 1 return a
reverse-only-letters
Python3 simple solution using two approaches
EklavyaJoshi
0
55
reverse only letters
917
0.615
Easy
14,893
https://leetcode.com/problems/reverse-only-letters/discuss/1097296/Python3-simple-solution-using-two-approaches
class Solution: def reverseOnlyLetters(self, S: str) -> str: x = '' for i in S: if i.isalpha(): x = i + x i = 0 j = 0 a = '' while j < len(x) or i < len(S): if S[i].isalpha(): a += x[j] j += 1 else: a += S[i] i += 1 return a
reverse-only-letters
Python3 simple solution using two approaches
EklavyaJoshi
0
55
reverse only letters
917
0.615
Easy
14,894
https://leetcode.com/problems/reverse-only-letters/discuss/719356/Python-Stack-solution
class Solution: def reverseOnlyLetters(self, S: str) -> str: tmp = [] non = {} for i,v in enumerate(S): if v.isalpha(): tmp.append(v) else: non[i] = v res = '' for x in range(len(S)): if x in non: res += non[x] else: res += tmp.pop() return res
reverse-only-letters
Python Stack solution
fuzzywuzzy21
0
60
reverse only letters
917
0.615
Easy
14,895
https://leetcode.com/problems/reverse-only-letters/discuss/577857/Simple-Python-Solution-Runtime%3A-20-ms-faster-than-98.33
class Solution: def reverseOnlyLetters(self, S: str) -> str: x="" for i in range(len(S)): if 'a'<=S[i]<='z' or 'A'<=S[i]<='Z': x+=S[i] x=x[::-1] print(x) j=0 s="" for i in range(len(S)): if 'a'<=S[i]<='z' or 'A'<=S[i]<='Z': s+=x[j] j+=1 else: s+=S[i] return (s)
reverse-only-letters
Simple Python Solution- Runtime: 20 ms, faster than 98.33%
Ayu-99
0
25
reverse only letters
917
0.615
Easy
14,896
https://leetcode.com/problems/reverse-only-letters/discuss/401099/Python-Simple-Solution
class Solution: def reverseOnlyLetters(self, S: str) -> str: s = list(S) m='' for i in range(len(S)): if S[i].isalpha(): m+=S[i] s[i] = '' m = m[::-1] for i in range(len(s)): if s[i]=='': t = m[0] m = m[1:] s[i] = t return ''.join(s)
reverse-only-letters
Python Simple Solution
saffi
0
114
reverse only letters
917
0.615
Easy
14,897
https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/633106/Python-O(n)-Kadane-DP-w-Visualization
class Solution: def maxSubarraySumCircular(self, A: List[int]) -> int: array_sum = 0 local_min_sum, global_min_sum = 0, float('inf') local_max_sum, global_max_sum = 0, float('-inf') for number in A: local_min_sum = min( local_min_sum + number, number ) global_min_sum = min( global_min_sum, local_min_sum ) local_max_sum = max( local_max_sum + number, number ) global_max_sum = max( global_max_sum, local_max_sum ) array_sum += number # global_max_sum denotes the maximum subarray sum without crossing boundary # arry_sum - global_min_sum denotes the maximum subarray sum with crossing boundary if global_max_sum > 0: return max( array_sum - global_min_sum, global_max_sum ) else: # corner case handle for all number are negative return global_max_sum
maximum-sum-circular-subarray
Python O(n) Kadane // DP [w/ Visualization]
brianchiang_tw
12
1,100
maximum sum circular subarray
918
0.382
Medium
14,898
https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/633106/Python-O(n)-Kadane-DP-w-Visualization
class Solution: def maxSubarraySumCircular(self, nums: List[int]) -> int: def maxSubArray( A: List[int]) -> int: size = len(A) dp = [ 0 for _ in range(size)] dp[0] = A[0] for i in range(1, size): dp[i] = max(dp[i-1] + A[i], A[i]) return max(dp) # ----------------------------------------------------------- ## Boundary case, only one element if len(nums) == 1: return nums[0] ## General cases: # Maximal without first element drop = maxSubArray(nums[1:]) # Maxiaml with first element selected pick = sum(nums) + max(0, maxSubArray([-number for number in nums[1:]])) return max(drop, pick)
maximum-sum-circular-subarray
Python O(n) Kadane // DP [w/ Visualization]
brianchiang_tw
12
1,100
maximum sum circular subarray
918
0.382
Medium
14,899