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/find-subsequence-of-length-k-with-the-largest-sum/discuss/1623400/Python-sorting | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
nums = sorted([(n, i) for i, n in enumerate(nums)])[-k:]
return [n for n, _ in sorted(nums, key=itemgetter(1))] | find-subsequence-of-length-k-with-the-largest-sum | Python, sorting | blue_sky5 | 0 | 146 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 29,000 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1623326/Python-sorting-solution | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
x = sorted(nums, reverse=True)
s = Counter(x[:k]) #get largest k num
res = []
# To be in order so the extra step is needed
for num in nums:
if s[num] > 0:
res.append(num)
s[num] -= 1
return res | find-subsequence-of-length-k-with-the-largest-sum | Python sorting solution | abkc1221 | 0 | 136 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 29,001 |
https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1623318/Python-simple-using-window | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
n = len(nums)
window = nums[:k]
for i in range(k,n):
curr_min = min(window)
if nums[i] > curr_min:
window.remove(curr_min)
window.append(nums[i])
return window | find-subsequence-of-length-k-with-the-largest-sum | Python simple using window | vj9880 | 0 | 123 | find subsequence of length k with the largest sum | 2,099 | 0.425 | Easy | 29,002 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1623325/Python3-prefix-and-suffix | class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
suffix = [0]*len(security)
for i in range(len(security)-2, 0, -1):
if security[i] <= security[i+1]: suffix[i] = suffix[i+1] + 1
ans = []
prefix = 0
for i in range(len(security)-time):
if i and security[i-1] >= security[i]: prefix += 1
else: prefix = 0
if prefix >= time and suffix[i] >= time: ans.append(i)
return ans | find-good-days-to-rob-the-bank | [Python3] prefix & suffix | ye15 | 5 | 243 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,003 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/2801128/Python3-Prefix-Sum-Solution | class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
grid1 = [0, 1]
grid2 = [0, 1]
for i in range(len(security)-1):
if security[i] >= security[i+1]: grid1.append(1)
else: grid1.append(0)
if security[i] <= security[i+1]: grid2.append(1)
else: grid2.append(0)
start = 0
for i in range(len(grid1)):
start += grid1[i]
grid1[i] = start
start = 0
for i in range(len(grid2)):
start += grid2[i]
grid2[i] = start
res = []
for t in range(time+1, len(grid1)-time):
if grid1[t] - grid1[t-time] == time and grid2[t+time] - grid2[t] == time:
res.append(t-1)
return res | find-good-days-to-rob-the-bank | Python3 Prefix Sum Solution | xxHRxx | 0 | 2 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,004 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/2678317/Python-solution | class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
result=[]
left=[0]*len(security)
right=[0]*len(security)
for i in range(1,len(security)):
if security[i]<security[i-1]:
left[i]=left[i-1]+1
elif security[i]==security[i-1]:
left[i]=left[i-1]+1
right[i]=right[i-1]+1
else:
right[i]=right[i-1]+1
print(left,right)
for i in range(time,len(security)-time):
if left[i]>=time:
if right[i+time]>=time:
result+=[i]
return result | find-good-days-to-rob-the-bank | Python solution | jessj3885 | 0 | 4 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,005 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1735518/WEEB-DOES-PYTHON-PREFIX-SUFFIX-SUM | class Solution:
def goodDaysToRobBank(self, nums: List[int], time: int) -> List[int]:
dpPrefix = [0] * len(nums)
dpSuffix = [0] * len(nums)
low, high = 1, len(nums)-2
while low < len(nums):
if nums[low-1] >= nums[low]:
dpPrefix[low] += dpPrefix[low-1] + 1
if nums[high] <= nums[high+1]:
dpSuffix[low] += dpSuffix[low-1] + 1
low += 1
high -= 1
result = []
for i in range(len(nums)):
if dpPrefix[i] >= time and dpSuffix[len(nums)-i-1] >= time:
result.append(i)
return result | find-good-days-to-rob-the-bank | WEEB DOES PYTHON PREFIX SUFFIX SUM | Skywalker5423 | 0 | 49 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,006 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1734638/python3-short-solution | class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
decreasing = [0] * len(security)
increasing = [0] * len(security)
for i in range(len(security)):
if i > 0 and security[i - 1] >= security[i]:
decreasing[i] = decreasing[i - 1] + 1
for i in reversed(range(len(security))):
if i < len(security) - 1 and security[i] <= security[i + 1]:
increasing[i] = increasing[i + 1] + 1
return [i for i in range(len(security)) if increasing[i] >= time and decreasing[i] >= time] | find-good-days-to-rob-the-bank | python3 short solution | svobodiannikov | 0 | 28 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,007 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1628644/Linear-solution-80-speed | class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
len_sec = len(security)
if time == 0:
return list(range(len_sec))
decreasing = [1] * len_sec
increasing = [1] * len_sec
for i in range(1, len_sec):
if security[i] <= security[i - 1]:
decreasing[i] += decreasing[i - 1]
for i in range(len_sec - 2, -1, -1):
if security[i] <= security[i + 1]:
increasing[i] += increasing[i + 1]
return [idx for idx, (d, i) in enumerate(zip(decreasing, increasing))
if d > time and i > time] | find-good-days-to-rob-the-bank | Linear solution, 80% speed | EvgenySH | 0 | 49 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,008 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1626966/Easy-python3-solution | class Solution:
def goodDaysToRobBank(self, l: List[int], time: int) -> List[int]:
left=[0]*len(l)
right=[0]*len(l)
n=len(l)
res=[]
for i in range(1,n):
if l[i]<=l[i-1]:
left[i]+=left[i-1]+1
else:
left[i]=0
for j in range(n-2,-1,-1):
if l[j]<=l[j+1]:
right[j]+=right[j+1]+1
else:
right[j]=0
for i in range(time,n-time):
if left[i]>=time and right[i]>=time:
res.append(i)
return res | find-good-days-to-rob-the-bank | Easy python3 solution | Karna61814 | 0 | 31 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,009 |
https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1624015/Python-simple-solution-but-Time-Limit-Exceeded-127-131-test-cases-passed | class Solution:
def goodDaysToRobBank(self, sec: List[int], time: int) -> List[int]:
result = []
n = len(sec) - 1
if time == 0:
copied = sec
copied.sort()
if copied == sec:
return list(range(n+1))
if n <= time:
return
else:
t = time
while t - time >= 0 and t + time <= n:
temp = time
s = t - time
u = t + time
flag = True
while temp:
if sec[s] < sec[s+1]:
flag = False
break
else:
s += 1
if sec[u] < sec[u-1]:
flag = False
break
else:
u -= 1
temp -= 1
if flag == True:
result.append(t)
t += 1
return result | find-good-days-to-rob-the-bank | Python simple solution but Time Limit Exceeded, 127 / 131 test cases passed | HunkWhoCodes | 0 | 36 | find good days to rob the bank | 2,100 | 0.492 | Medium | 29,010 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1870271/Python-Solution-that-you-want-%3A | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
if len(bombs)==1:
return 1
adlist={i:[] for i in range(len(bombs))}
for i in range(len(bombs)):
x1,y1,r1=bombs[i]
for j in range(i+1,len(bombs)):
x2,y2,r2=bombs[j]
dist=((x2-x1)**2+(y2-y1)**2)**(1/2)
if dist<=r1:
adlist[i].append(j)
if dist<=r2:
adlist[j].append(i)
def dfs(adlist,seen,start):
seen.add(start)
for i in adlist[start]:
if i not in seen:
dfs(adlist,seen,i)
maxx=1
for v in adlist:
seen=set()
seen.add(v)
dfs(adlist,seen,v)
maxx=max(maxx,len(seen))
return maxx | detonate-the-maximum-bombs | Python Solution that you want : | goxy_coder | 2 | 201 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,011 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1623343/Python3-digraph | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
graph = [[] for _ in bombs]
for i, (xi, yi, ri) in enumerate(bombs):
for j, (xj, yj, rj) in enumerate(bombs):
if i < j:
dist2 = (xi-xj)**2 + (yi-yj)**2
if dist2 <= ri**2: graph[i].append(j)
if dist2 <= rj**2: graph[j].append(i)
def fn(x):
"""Return connected components of x."""
ans = 1
seen = {x}
stack = [x]
while stack:
u = stack.pop()
for v in graph[u]:
if v not in seen:
ans += 1
seen.add(v)
stack.append(v)
return ans
return max(fn(x) for x in range(len(bombs))) | detonate-the-maximum-bombs | [Python3] digraph | ye15 | 2 | 115 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,012 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1667114/Python3-solution-commented-or-faster-than-90-or-dfs | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
def dfs(graph, node, been):
for i in range(len(graph[node])):
if (graph[node][i]) not in been:
been.add(graph[node][i])
dfs(graph, graph[node][i], been)
if len(bombs) == 0: return 0
# l = length between 2 centers
d = {} # d = graph | nodes = centers(x,y) | node A is connected(can reach) with node B if A has a radius bigger or equal with the distance between the 2 points
for i in range(len(bombs)):
d[i] = []
for i in range(len(bombs)):
for j in range(i+1, len(bombs)):
l = math.sqrt((bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2) # distance between 2 points
if l <= bombs[i][2]: # you can reach node J from node I
d[i].append(j)
if l <= bombs[j][2]: # you can reach node I from node J
d[j].append(i)
max_bombs = 1 # if len(bombs) > 0 at least 1 bomb explodes
for i, element in enumerate(d):
been = set()
been.add(element)
dfs(d, element, been)
if len(been) == len(bombs): # special case when the all bombs explode | no need to search more
return len(been)
max_bombs = max(max_bombs, len(been))
return max_bombs | detonate-the-maximum-bombs | Python3 solution commented | faster than 90% | dfs | FlorinnC1 | 1 | 233 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,013 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/2804039/Python3-BFS-Solution | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
groups = []
for i in range(len(bombs)):
ix, iy, dis = bombs[i]
target = []
for j in range(len(bombs)):
jx, jy, disj = bombs[j]
if (ix - jx)**2 + (iy - jy)**2 <= dis**2:
target.append(j)
groups.append(target)
res = 1
for i in range(len(bombs)):
visited = set()
visited.add(i)
start = [i]
while start:
new_start = []
for element in start:
for target in groups[element]:
if target not in visited:
new_start.append(target)
visited.add(target)
start = new_start
res = max(res, len(visited))
return res | detonate-the-maximum-bombs | Python3 BFS Solution | xxHRxx | 0 | 8 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,014 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/2692296/My-Python-DFS-Solution-Using-Directional-Graph | class Solution:
def distance(self, b1, b2):
x1, y1, r1 = b1
x2, y2, r2 = b2
d = (x1-x2)**2 + (y1-y2)**2
c1 = r1 ** 2 >= d
c2 = r2 ** 2 >= d
return (c1, c2)
def dfs(self, graph, idx):
q = collections.deque([idx])
visited = set([idx])
while q:
node = q.popleft()
for nxt in graph[node]:
if nxt in visited: continue
visited.add(nxt)
q.append(nxt)
return visited
def maximumDetonation(self, bombs: List[List[int]]) -> int:
N = len(bombs)
graph = [[] for _ in range(N)]
for i in range(N):
for j in range(i+1, N):
c1, c2 = self.distance(bombs[i], bombs[j])
if c1: graph[i].append(j)
if c2: graph[j].append(i)
result = 0
visited = set()
for i in range(N):
if i in visited: continue
vi = self.dfs(graph, i)
result = max(result, len(vi))
visited.update(vi)
return result | detonate-the-maximum-bombs | My Python DFS Solution Using Directional Graph | MonQiQi | 0 | 17 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,015 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/2597662/Python-Simple-DFS-with-Memorization-No-TLE-~640ms | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
# make a dict to connect bombs
connections = {idx: set() for idx in range(len(bombs))}
# make the computations
for id1, (x1, y1, r1) in enumerate(bombs):
for id2, (x2, y2, r2) in enumerate(bombs[id1+1:], id1+1):
# compute the distance
distance = (x1-x2)**2 + (y1-y2)**2
# check whether they are within radius
if distance <= r1**2:
connections[id1].add(id2)
if distance <= r2**2:
connections[id2].add(id1)
# make the DFS
self.max = 0
# save bombs we already solved
self.solved = {}
# start at every bomb
for idx in range(len(bombs)):
# get the reachable bombs
visited = set([idx])
self.dfs(idx, visited, connections)
# save the reachable bombs
self.solved[idx] = visited
# count reachable bombs
self.max = max(self.max, len(visited))
return self.max
def dfs(self, current, visited, connections):
# check if we already solved for this bomb
if current in self.solved:
# extend our path
visited.update(self.solved[current])
return
# go deeper
for idx in connections[current]:
if idx not in visited:
# update visited
visited.add(idx)
# go deeper
self.dfs(idx, visited, connections) | detonate-the-maximum-bombs | [Python] - Simple DFS with Memorization - No TLE ~640ms | Lucew | 0 | 36 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,016 |
https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1628522/Detonate-each-bomb-to-trigger-chain-90-speed | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
graph = defaultdict(set)
for i, (x, y, r) in enumerate(bombs):
for j, (a, b, _) in enumerate(bombs):
if i != j and pow(x - a, 2) + pow(y - b, 2) <= r * r:
graph[i].add(j)
max_bombs = 1
for start in graph:
detonated = set()
layer = {start}
while layer:
new_layer = set()
for current_bomb in layer:
if current_bomb not in detonated:
detonated.add(current_bomb)
if current_bomb in graph:
new_layer.update(graph[current_bomb])
layer = new_layer
max_bombs = max(max_bombs, len(detonated))
return max_bombs | detonate-the-maximum-bombs | Detonate each bomb to trigger chain, 90% speed | EvgenySH | 0 | 107 | detonate the maximum bombs | 2,101 | 0.413 | Medium | 29,017 |
https://leetcode.com/problems/rings-and-rods/discuss/2044864/Python-simple-solution | class Solution:
def countPoints(self, r: str) -> int:
ans = 0
for i in range(10):
i = str(i)
if 'R'+i in r and 'G'+i in r and 'B'+i in r:
ans += 1
return ans | rings-and-rods | Python simple solution | StikS32 | 7 | 353 | rings and rods | 2,103 | 0.814 | Easy | 29,018 |
https://leetcode.com/problems/rings-and-rods/discuss/2570849/SIMPLE-PYTHON3-SOLUTION | class Solution:
def countPoints(self, rings: str) -> int:
d = dict()
ct = 0
l = 0
r=1
while r<len(rings):
if rings[r] in d:
d[rings[r]].add(rings[l])
else:
d[rings[r]] = set()
d[rings[r]].add(rings[l])
l=r+1
r+=2
for i in d:
if len(d[i]) == 3:
ct+=1
return ct | rings-and-rods | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ | rajukommula | 2 | 91 | rings and rods | 2,103 | 0.814 | Easy | 29,019 |
https://leetcode.com/problems/rings-and-rods/discuss/1882465/Python-beginners-solution | class Solution:
def countPoints(self, rings: str) -> int:
r = []
g = []
b = []
ring_nums = set()
count = 0
for i in range(0, len(rings)):
if rings[i] == 'R':
r.append(int(rings[i+1]))
if rings[i+1] not in ring_nums:
ring_nums.add(int(rings[i+1]))
elif rings[i] == 'G':
g.append(int(rings[i+1]))
if rings[i+1] not in ring_nums:
ring_nums.add(int(rings[i+1]))
elif rings[i] == 'B':
b.append(int(rings[i+1]))
if rings[i+1] not in ring_nums:
ring_nums.add(int(rings[i+1]))
for i in ring_nums:
if i in r and i in g and i in b:
count += 1
return count | rings-and-rods | Python beginners solution | alishak1999 | 2 | 90 | rings and rods | 2,103 | 0.814 | Easy | 29,020 |
https://leetcode.com/problems/rings-and-rods/discuss/2478896/Python-simple-solution-using-defaultdict | class Solution:
def countPoints(self, rings: str) -> int:
count = 0
dic = collections.defaultdict(set)
for i in range(1,len(rings),2):
dic[rings[i]].add(rings[i-1])
for k,v in dic.items():
if len(v) == 3:
count += 1
return count | rings-and-rods | Python simple solution using defaultdict | aruj900 | 1 | 33 | rings and rods | 2,103 | 0.814 | Easy | 29,021 |
https://leetcode.com/problems/rings-and-rods/discuss/1929283/Python3-Simple-Solution | class Solution:
def countPoints(self, rings: str) -> int:
counts = [[False for i in range(3)] for j in range(10)]
for i in range(0, len(rings), 2):
if rings[i] == 'B':
counts[int(rings[i+1])][0] = True
elif rings[i] == 'R':
counts[int(rings[i+1])][1] = True
elif rings[i] == 'G':
counts[int(rings[i+1])][2] = True
return sum([1 for c in counts if sum(c) == 3]) | rings-and-rods | [Python3] Simple Solution | terrencetang | 1 | 95 | rings and rods | 2,103 | 0.814 | Easy | 29,022 |
https://leetcode.com/problems/rings-and-rods/discuss/1891367/Python-Solution-or-HashMap-Based-or-Iterative-or-100-Faster | class Solution:
def countPoints(self, rings: str) -> int:
count = 0
store = defaultdict(set)
for ring,rod in zip(range(0,len(rings),2),range(1,len(rings),2)):
store[int(rings[rod])].add(rings[ring])
for val in store.values():
if len(val) == 3:
count += 1
return count | rings-and-rods | Python Solution | HashMap Based | Iterative | 100% Faster | Gautam_ProMax | 1 | 122 | rings and rods | 2,103 | 0.814 | Easy | 29,023 |
https://leetcode.com/problems/rings-and-rods/discuss/1891269/Python-solution-using-dictionary | class Solution:
def countPoints(self, rings: str) -> int:
dic = {}
count = 0
for i in range(1,len(rings),2):
if rings[i] not in dic:
dic[rings[i]] = [rings[i-1]]
else:
dic[rings[i]].append(rings[i-1])
for key in dic:
if 'R' in dic[key] and 'B' in dic[key] and 'G' in dic[key]:
count += 1
return count | rings-and-rods | Python solution using dictionary | lrg365 | 1 | 36 | rings and rods | 2,103 | 0.814 | Easy | 29,024 |
https://leetcode.com/problems/rings-and-rods/discuss/1736233/Simple-python-solution-or-Memory-Usage%3A-13.9-MB-less-than-98.97-of-Python3 | class Solution:
def countPoints(self, rings: str) -> int:
lst = []
for i in range(0,len(rings),2):
lst.append(rings[i:i+2])
res = 0
for i in range(10):
if (f'R{i}' in lst) and (f'G{i}' in lst) and (f'B{i}' in lst):
res += 1
return res | rings-and-rods | Simple python solution | Memory Usage: 13.9 MB, less than 98.97% of Python3 | Coding_Tan3 | 1 | 83 | rings and rods | 2,103 | 0.814 | Easy | 29,025 |
https://leetcode.com/problems/rings-and-rods/discuss/1627592/Python-one-liner | class Solution:
def countPoints(self, rings: str) -> int:
return len((*filter(lambda c: len(c) == 3, ((rods := {}), [rods.setdefault(rings[i+1], set()).add(rings[i]) for i in range(0, len(rings), 2)])[0].values()),)) | rings-and-rods | Python one-liner | kingjonathan310 | 1 | 120 | rings and rods | 2,103 | 0.814 | Easy | 29,026 |
https://leetcode.com/problems/rings-and-rods/discuss/1624230/Python3-using-bits | class Solution:
def countPoints(self, rings: str) -> int:
mp = dict(zip("RGB", range(3)))
mask = [0]*10
for i in range(0, len(rings), 2):
mask[int(rings[i+1])] |= 1 << mp[rings[i]]
return sum(x == 7 for x in mask) | rings-and-rods | [Python3] using bits | ye15 | 1 | 82 | rings and rods | 2,103 | 0.814 | Easy | 29,027 |
https://leetcode.com/problems/rings-and-rods/discuss/2850000/Map-or-Python | class Solution:
def countPoints(self, rings: str) -> int:
ringDict = defaultdict(set)
for i in range(1, len(rings), 2):
ringDict[rings[i]].add(rings[i - 1])
ans = 0
for key in ringDict:
if len(ringDict[key]) == 3:
ans += 1
return ans | rings-and-rods | Map | Python | joshua_mur | 0 | 2 | rings and rods | 2,103 | 0.814 | Easy | 29,028 |
https://leetcode.com/problems/rings-and-rods/discuss/2848821/Dictionary-solution-on-Python3 | class Solution:
def countPoints(self, rings: str) -> int:
dic1 = {}
for i in range(0, len(rings), 2):
if rings[i+1] not in dic1.keys():
dic1[rings[i+1]] = set(rings[i])
else:
dic1[rings[i+1]].add(rings[i])
return len([v for v in dic1.values() if len(v) == 3]) | rings-and-rods | Dictionary solution on Python3 | DNST | 0 | 2 | rings and rods | 2,103 | 0.814 | Easy | 29,029 |
https://leetcode.com/problems/rings-and-rods/discuss/2764864/Python-solution-using-dictionary-and-set | class Solution:
def countPoints(self, rings: str) -> int:
dict_num_colors = {}
for i in range(0,len(rings) - 1, 2):
if rings[i + 1] not in dict_num_colors:
dict_num_colors[rings[i + 1]] = [rings[i]]
else:
dict_num_colors[rings[i + 1]].append(rings[i])
count = 0
for k, v in dict_num_colors.items():
set_v = set(v)
if len(set_v) > 2 and "R" in set_v and "B" in set_v and "G" in set_v:
count += 1
else:
count += 0
return count | rings-and-rods | Python solution using dictionary and set | samanehghafouri | 0 | 1 | rings and rods | 2,103 | 0.814 | Easy | 29,030 |
https://leetcode.com/problems/rings-and-rods/discuss/2753665/Python3-Solution-with-using-hashmap | class Solution:
def countPoints(self, rings: str) -> int:
d = collections.defaultdict(set)
for idx in range(1, len(rings), 2):
d[rings[idx]].add(rings[idx - 1])
res = 0
for road in d:
if len(d[road]) == 3:
res += 1
return res | rings-and-rods | [Python3] Solution with using hashmap | maosipov11 | 0 | 1 | rings and rods | 2,103 | 0.814 | Easy | 29,031 |
https://leetcode.com/problems/rings-and-rods/discuss/2735950/Python3-Solution | class Solution:
def countPoints(self, rings: str) -> int:
# rings = list(set([rings[i:i+2] for i in range(0, len(rings), 2)]))
i = 0
ans = 0
while i < 10:
R = True if 'R' + str(i) in rings else False
G = True if 'G' + str(i) in rings else False
B = True if 'B' + str(i) in rings else False
ans = ans + 1 if R*G*B == 1 else ans
i += 1
return ans | rings-and-rods | Python3 Solution | sipi09 | 0 | 1 | rings and rods | 2,103 | 0.814 | Easy | 29,032 |
https://leetcode.com/problems/rings-and-rods/discuss/2728960/Python-direct-solution-using-dictionary | class Solution:
def countPoints(self, rings: str) -> int:
dic = {}
for i in range( 0 , len(rings) , 2 ):
if rings[i+1] in dic :
dic[rings[i+1]] += str(rings[i])
else :
dic[rings[i+1]] = str(rings[i])
goal = 'BGR'
res = 0
for k , v in dic.items() :
if ''.join (sorted(list(set(v)))) == goal :
res += 1
return res | rings-and-rods | Python direct solution using dictionary | mohamedWalid | 0 | 1 | rings and rods | 2,103 | 0.814 | Easy | 29,033 |
https://leetcode.com/problems/rings-and-rods/discuss/2721114/Python-or-Easy-and-Fastest-Solution-or-Time-O(n)-Space-O(1)-or-2-Ways | class Solution:
def countPoints(self, rings: str) -> int:
rings = "".join(set([rings[i:i+2] for i in range(0, len(rings), 2)]))
count = 0
for x in range(0,10):
if rings.count(str(x))==3:
count+=1
return count | rings-and-rods | ✅ Python | Easy & Fastest Solution | Time O(n) Space O(1) | 2 Ways | keioon | 0 | 2 | rings and rods | 2,103 | 0.814 | Easy | 29,034 |
https://leetcode.com/problems/rings-and-rods/discuss/2627151/Python-or-Simple-or-O(n) | class Solution:
def countPoints(self, rings: str) -> int:
dict_ = {str(key):[] for key in range(10)}
for idx in range(0,len(rings),2):
rode = rings[idx+1]
color = rings[idx]
dict_[rode].append(color)
counter = 0
for key in dict_:
if len(set(dict_[key]))==3:
counter += 1
return counter | rings-and-rods | Python | Simple | O(n) | anurag899 | 0 | 7 | rings and rods | 2,103 | 0.814 | Easy | 29,035 |
https://leetcode.com/problems/rings-and-rods/discuss/2513663/python-using-dict | class Solution:
def countPoints(self, rings: str) -> int:
my_dict = {}
for i in range(0, len(rings), 2):
if rings[i+1] in my_dict:
my_dict[rings[i+1]].append(rings[i])
else:
my_dict[rings[i+1]] = [rings[i]]
count = 0
for el in my_dict:
if 'R' in my_dict[el] and 'B' in my_dict[el] and 'G' in my_dict[el]:
count += 1
return count | rings-and-rods | python using dict | nika_macharadze | 0 | 10 | rings and rods | 2,103 | 0.814 | Easy | 29,036 |
https://leetcode.com/problems/rings-and-rods/discuss/2418725/Python-one-liner-easy | class Solution:
def countPoints(self, rings: str) -> int:
total = 0
for i in range(10):
i = str(i)
if 'R'+i in rings and 'G'+i in rings and 'B'+i in rings:
total += 1
return total | rings-and-rods | ✅Python one-liner easy🔥 | blest | 0 | 25 | rings and rods | 2,103 | 0.814 | Easy | 29,037 |
https://leetcode.com/problems/rings-and-rods/discuss/2418725/Python-one-liner-easy | class Solution:
def countPoints(self, rings: str) -> int:
return len([i for i in map(str, range(10)) if 'R'+i in rings and 'G'+i in rings and 'B'+i in rings]) | rings-and-rods | ✅Python one-liner easy🔥 | blest | 0 | 25 | rings and rods | 2,103 | 0.814 | Easy | 29,038 |
https://leetcode.com/problems/rings-and-rods/discuss/2059820/Python-Solution | class Solution:
def countPoints(self, rings: str) -> int:
data = {}
for i in range(0, len(rings), 2):
data[rings[i + 1]] = data.get(rings[i + 1], set()) | {rings[i]}
return len(list(filter(lambda x: len(x) > 2, data.values()))) | rings-and-rods | Python Solution | hgalytoby | 0 | 96 | rings and rods | 2,103 | 0.814 | Easy | 29,039 |
https://leetcode.com/problems/rings-and-rods/discuss/2059820/Python-Solution | class Solution:
def countPoints(self, rings: str) -> int:
data = defaultdict(set)
for i in range(0, len(rings), 2):
data[rings[i + 1]].add(rings[i])
return len(list(filter(lambda x: len(x) > 2, data.values()))) | rings-and-rods | Python Solution | hgalytoby | 0 | 96 | rings and rods | 2,103 | 0.814 | Easy | 29,040 |
https://leetcode.com/problems/rings-and-rods/discuss/1829252/python3-98-faster | class Solution:
def countPoints(self, rings: str) -> int:
pos={str(i):[] for i in range(0,10)}
count=0
ans_poll=[]
for i in range(1,len(rings),2):
if rings[i] in pos and rings[i] not in ans_poll :
if rings[i-1] not in pos[rings[i]]:
pos[rings[i]].append(rings[i-1])
if (len(pos[rings[i]]))==3:
ans_poll.append(pos[rings[i]])
return(len(ans_poll)) | rings-and-rods | python3 98% faster | p_a | 0 | 40 | rings and rods | 2,103 | 0.814 | Easy | 29,041 |
https://leetcode.com/problems/rings-and-rods/discuss/1702557/Understandable-code-for-beginners-like-me-in-python-!! | class Solution:
def countPoints(self, rings: str) -> int:
spclRods=0
ringRods={}
rings_len=len(rings)
for index in range(1,rings_len,2):
if rings[index] not in ringRods:
ringRods[rings[index]]=str()
ringRods[rings[index]]+=rings[index-1]
else:
if(rings[index-1] not in ringRods[rings[index]]):
ringRods[rings[index]]+=rings[index-1]
for rod,ring in ringRods.items():
if(len(ring)==3):
spclRods+=1
return spclRods | rings-and-rods | Understandable code for beginners like me in python !! | kabiland | 0 | 83 | rings and rods | 2,103 | 0.814 | Easy | 29,042 |
https://leetcode.com/problems/rings-and-rods/discuss/1697557/Python3-accepted-solution | class Solution:
def countPoints(self, rings: str) -> int:
num = list(set([i for i in rings if(i.isnumeric())]))
colors = []
for j in num:
colors.append("".join([rings[i-1] for i in range(len(rings)) if(rings[i]==j)]))
return len([num[i] for i in range(len(num)) if("".join(sorted(set(colors[i])))=="BGR")]) | rings-and-rods | Python3 accepted solution | sreeleetcode19 | 0 | 66 | rings and rods | 2,103 | 0.814 | Easy | 29,043 |
https://leetcode.com/problems/rings-and-rods/discuss/1670054/Python-four-liner-using-bit-operator-oror-O(1)-space-oror-O(n) | class Solution:
def countPoints(self, rings: str) -> int:
ring_arr = [0]*10
bit_map = { "R": 0b100,"G":0b010,"B":0b001 }
for i in range(0,len(rings),2):
ring_arr[int(rings[i+1])] = ring_arr[int(rings[i+1])] | bit_map[rings[i]]
return ring_arr.count(7) | rings-and-rods | Python four liner using bit operator || O(1) space || O(n) | snagsbybalin | 0 | 70 | rings and rods | 2,103 | 0.814 | Easy | 29,044 |
https://leetcode.com/problems/rings-and-rods/discuss/1647001/Simple-Python-solution-O(n) | class Solution:
def countPoints(self, rings: str) -> int:
rods = defaultdict(set)
for i in range(0, len(rings), 2):
color, rod = rings[i:i+2]
rods[rod].add(color)
return sum(len(colors) == 3 for colors in rods.values()) | rings-and-rods | Simple Python solution, O(n) | emwalker | 0 | 82 | rings and rods | 2,103 | 0.814 | Easy | 29,045 |
https://leetcode.com/problems/rings-and-rods/discuss/1639260/Python-the-simplest-solution | class Solution:
def countPoints(self, rings: str) -> int:
cnt = [defaultdict(int) for _ in range(10)]
for i in range(1, len(rings), 2):
cnt[int(rings[i])][rings[i-1]] += 1
res = 0
for c in cnt:
if len(c) == 3:
res += 1
return res | rings-and-rods | Python the simplest solution | byuns9334 | 0 | 112 | rings and rods | 2,103 | 0.814 | Easy | 29,046 |
https://leetcode.com/problems/rings-and-rods/discuss/1631585/Python3-Dict-of-Sets | class Solution:
def countPoints(self, rings: str) -> int:
rods_colors = defaultdict(set)
for i in range(0, len(rings), 2):
rods_colors[rings[i+1]].add(rings[i])
return len(list(filter(lambda x: len(x[1]) == 3, rods_colors.items()))) | rings-and-rods | [Python3] - Dict of Sets | patefon | 0 | 45 | rings and rods | 2,103 | 0.814 | Easy | 29,047 |
https://leetcode.com/problems/rings-and-rods/discuss/1627854/Understandable-brute-force-Python3 | class Solution:
def countPoints(self, rings: str) -> int:
# rods numbered 0 through 9
# ring = string with color RGB and 0 indexed rod its on
# we want to return the number of rods that have all three colors RGB on them.
from collections import defaultdict
d = defaultdict(set)
i = 0
j = 2
while i < len(rings):
tmp = rings[i:j]
color, rod = tmp[0], tmp[1]
d[rod].add(color)
i += 2
j += 2
count = 0
for _, colors in d.items():
if len(colors) == 3:
count += 1
return count | rings-and-rods | Understandable brute force Python3 | normalpersontryingtopayrent | 0 | 47 | rings and rods | 2,103 | 0.814 | Easy | 29,048 |
https://leetcode.com/problems/rings-and-rods/discuss/1624677/Easy-python3-solution | class Solution:
def countPoints(self, rings: str) -> int:
from collections import defaultdict
mydict=defaultdict(list)
res=0
for i in range(1,len(rings),2):
mydict[rings[i]].append(rings[i-1])
for key in mydict:
if len(set(mydict[key]))==3:
res+=1
return res | rings-and-rods | Easy python3 solution | Karna61814 | 0 | 57 | rings and rods | 2,103 | 0.814 | Easy | 29,049 |
https://leetcode.com/problems/rings-and-rods/discuss/1624505/Python-setting-bits | class Solution:
def countPoints(self, rings: str) -> int:
colors = {'R': 0, 'G': 1, 'B': 2}
bits = 0
for i in range(0, len(rings), 2):
color = rings[i]
rod = int(rings[i+1])
bits |= 1 << 3*rod + colors[color]
result = 0
while bits:
result += (bits & 7 == 7)
bits >>= 3
return result | rings-and-rods | Python, setting bits | blue_sky5 | 0 | 73 | rings and rods | 2,103 | 0.814 | Easy | 29,050 |
https://leetcode.com/problems/rings-and-rods/discuss/1624505/Python-setting-bits | class Solution:
def countPoints(self, rings: str) -> int:
colors = {'R': 0, 'G': 1, 'B': 2}
result = 0
rods = [0] * 10
for i in range(0, len(rings), 2):
color = rings[i]
rod = int(rings[i+1])
if rods[rod] != 7:
rods[rod] |= 1 << colors[color]
if rods[rod] == 7:
result += 1
return result | rings-and-rods | Python, setting bits | blue_sky5 | 0 | 73 | rings and rods | 2,103 | 0.814 | Easy | 29,051 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624416/Python3-stack | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
def fn(op):
"""Return min sum (if given gt) or max sum (if given lt)."""
ans = 0
stack = []
for i in range(len(nums) + 1):
while stack and (i == len(nums) or op(nums[stack[-1]], nums[i])):
mid = stack.pop()
ii = stack[-1] if stack else -1
ans += nums[mid] * (i - mid) * (mid - ii)
stack.append(i)
return ans
return fn(lt) - fn(gt) | sum-of-subarray-ranges | [Python3] stack | ye15 | 17 | 3,900 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,052 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1732394/Python-3-two-monotonic-stacks-O(n)-time-O(n)-space | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
res = 0
min_stack, max_stack = [], []
n = len(nums)
nums.append(0)
for i, num in enumerate(nums):
while min_stack and (i == n or num < nums[min_stack[-1]]):
top = min_stack.pop()
starts = top - min_stack[-1] if min_stack else top + 1
ends = i - top
res -= starts * ends * nums[top]
min_stack.append(i)
while max_stack and (i == n or num > nums[max_stack[-1]]):
top = max_stack.pop()
starts = top - max_stack[-1] if max_stack else top + 1
ends = i - top
res += starts * ends * nums[top]
max_stack.append(i)
return res | sum-of-subarray-ranges | Python 3, two monotonic stacks, O(n) time, O(n) space | dereky4 | 11 | 2,600 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,053 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2044554/Python3-oror-Monotonic-Stack-oror-O(n)-time-complexity | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
mon = monotonicStack()
# for each element, check in how many sub-arrays arrays, it can be max
# find the prev and next greater element
# for each element, check in how many sub-arrays arrays, it can be min
# find the prev and next smaller element
nse_l = mon.nextSmaller_left_idx(nums)
nse_r = mon.nextSmaller_right_idx(nums)
nge_l = mon.nextGreater_left_idx(nums)
nge_r = mon.nextGreater_right_idx(nums)
ans = 0
for idx in range(len(nums)):
smaller_left, smaller_right = nse_l[idx], nse_r[idx]
greater_left, greater_right = nge_l[idx], nge_r[idx]
if smaller_right == -1:
smaller_right = len(nums)
if greater_right == -1:
greater_right = len(nums)
min_val = (idx - smaller_left) * (smaller_right - idx) * nums[idx]
max_val = (idx - greater_left) * (greater_right - idx) * nums[idx]
ans += (max_val - min_val)
return ans
class monotonicStack:
def nextGreater_right_idx(self,arr):
ans = [None] * len(arr)
stack = []
for idx in range(len(arr)-1,-1,-1):
while stack and arr[stack[-1]] < arr[idx]:
stack.pop()
if not stack:
#no greater element
ans[idx] = -1
else:
ans[idx] = stack[-1]
stack.append(idx)
return ans
def nextGreater_left_idx(self,arr):
ans = [None] * len(arr)
stack = []
for idx in range(len(arr)):
while stack and arr[stack[-1]] <= arr[idx]:
stack.pop()
if not stack:
#no greater element
ans[idx] = -1
else:
ans[idx] = stack[-1]
stack.append(idx)
return ans
def nextSmaller_right_idx(self,arr):
ans = [None] * len(arr)
stack = []
for idx in range(len(arr)-1,-1,-1):
while stack and arr[stack[-1]] > arr[idx]:
stack.pop()
if not stack:
#no smaller element
ans[idx] = -1
else:
ans[idx] = stack[-1]
stack.append(idx)
return ans
def nextSmaller_left_idx(self,arr):
ans = [None] * len(arr)
stack = []
for idx in range(len(arr)):
while stack and arr[stack[-1]] >= arr[idx]:
stack.pop()
if not stack:
#no smaller element
ans[idx] = -1
else:
ans[idx] = stack[-1]
stack.append(idx)
return ans | sum-of-subarray-ranges | Python3 || Monotonic Stack || O(n) time complexity | s_m_d_29 | 5 | 1,100 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,054 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1844039/Python-3%3A-Monotonic-Stack-Solution%3A-O(n)-Time-O(n)-Aux-Space | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
# Reference: https://cybergeeksquad.co/2022/02/shipment-imbalance-amazon-oa.html#SOLUTION
# count number of times each number is used as a maximum and minimum
gl = [None] * len(nums) # greater left
gr = [None] * len(nums) # greater right
ll = [None] * len(nums) # lesser left
lr = [None] * len(nums) # lesser right
s = [(0, math.inf)]
for i in range(len(nums)):
while len(s) != 0 and s[-1][-1] < nums[i]:
s.pop()
s.append((i+1, nums[i]))
gl[i] = s[-1][0] - s[-2][0]
s = [(len(nums), math.inf)]
for i in range(len(nums)-1, -1, -1):
while len(s) != 0 and s[-1][-1] <= nums[i]:
s.pop()
s.append((i, nums[i]))
gr[i] = s[-2][0] - s[-1][0]
s = [(0, -math.inf)]
for i in range(len(nums)):
while len(s) != 0 and s[-1][-1] > nums[i]:
s.pop()
s.append((i+1, nums[i]))
ll[i] = s[-1][0] - s[-2][0]
s = [(len(nums), -math.inf)]
for i in range(len(nums)-1, -1, -1):
while len(s) != 0 and s[-1][-1] >= nums[i]:
s.pop()
s.append((i, nums[i]))
lr[i] = s[-2][0] - s[-1][0]
g = [gl[i]*gr[i] for i in range(len(nums))] # number of times nums[i] is maximum
l = [ll[i]*lr[i] for i in range(len(nums))] # number of times nums[i] is minimum
return sum([(g[i]-l[i])*nums[i] for i in range(len(nums))]) | sum-of-subarray-ranges | Python 3: Monotonic Stack Solution: O(n) Time; O(n) Aux Space | DheerajGadwala | 2 | 1,100 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,055 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2849991/Simple-Brute-force-solution-in-python | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
summ = 0
for i in range(len(nums)):
maxx = nums[i]
minn = nums[i]
for j in range(i+1, len(nums)):
maxx = max(maxx, nums[j])
minn = min(minn, nums[j])
summ += (maxx-minn)
return summ | sum-of-subarray-ranges | Simple Brute force solution in python | Tonmoy-saha18 | 0 | 1 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,056 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2834725/easy-python-solution | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
output = 0
for i in range(len(nums)) :
curr_max, curr_min = nums[i], nums[i]
for j in range(i+1, len(nums)) :
if nums[j] > curr_max :
curr_max = nums[j]
if nums[j] < curr_min :
curr_min = nums[j]
output += curr_max - curr_min
return output | sum-of-subarray-ranges | easy python solution | sghorai | 0 | 2 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,057 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2709236/O(n)-easier-to-understand-python3-solution | class Solution:
# O(n) time,
# O(n) space,
# Approach: monotonic stack, array
def subArrayRanges(self, nums: List[int]) -> int:
def findSubarrayMinSum(nums: List[int]) -> int:
tot = 0
stack = [] # monotonic(non decreasing) stack
for index, num in enumerate(nums):
while stack and num <= nums[stack[-1]]:
popped_index = stack.pop()
left_offset = stack[-1] if stack else -1
right_offset = index
num_subarrays = (popped_index-left_offset) * (right_offset-popped_index)
tot += nums[popped_index] * num_subarrays
stack.append(index)
right_offset = len(nums)
while stack:
popped_index = stack.pop()
left_offset = stack[-1] if stack else -1
num_subarrays = (popped_index-left_offset) * (right_offset-popped_index)
tot += nums[popped_index] * num_subarrays
return tot
def findSubarrayMaxSum(nums: List[int]) -> int:
tot = 0
stack = [] # monotonic(non increasing) stack
for index, num in enumerate(nums):
while stack and num >= nums[stack[-1]]:
popped_index = stack.pop()
left_offset = stack[-1] if stack else -1
right_offset = index
num_subarrays = (popped_index-left_offset) * (right_offset-popped_index)
tot += nums[popped_index] * num_subarrays
stack.append(index)
right_offset = len(nums)
while stack:
popped_index = stack.pop()
left_offset = stack[-1] if stack else -1
num_subarrays = (popped_index-left_offset) * (right_offset-popped_index)
tot += nums[popped_index] * num_subarrays
return tot
return findSubarrayMaxSum(nums) - findSubarrayMinSum(nums) | sum-of-subarray-ranges | O(n) easier to understand python3 solution | destifo | 0 | 17 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,058 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2707658/O(N)-python-code-2-loops-append-element-at-the-end-to-simplify-thought-process | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
result = 0
if not nums:
return result
min_sum = 0
max_sum = 0
stack = []
smallest = min(nums) - 1
largest = max(nums) + 1
nums.append(smallest)
stack = [-1]
for right, num in enumerate(nums):
while num < nums[stack[-1]]:
i = stack.pop()
min_sum += nums[i] * (right-i) * (i - stack[-1])
stack.append(right)
del nums[-1]
nums.append(largest)
stack = [-1]
for right, num in enumerate(nums):
while num > nums[stack[-1]]:
i = stack.pop()
max_sum += nums[i] * (right-i) * (i - stack[-1])
stack.append(right)
del nums[-1]
return max_sum - min_sum | sum-of-subarray-ranges | O(N) python code, 2 loops, append element at the end to simplify thought process | veecos1 | 0 | 9 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,059 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2678201/easy-solution-O(N2) | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
ans =0
def recur(k):
nonlocal nums, ans
mx,mn = nums[k],nums[k]
for i in nums[k+1:]:
mx = max(i,mx)
mn = min(i,mn)
ans+= mx-mn
for i in range(len(nums)):
recur(i)
return ans | sum-of-subarray-ranges | easy solution O(N^2) | abhi2411 | 0 | 18 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,060 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2671234/Python-5-pass-Monotonic-Stack-for-O(n)-runtime | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
total = 0
n = len(nums)
stack = []
nextSmallerRight = [n] * n
for i in range(n):
while stack and nums[stack[-1]] > nums[i]:
nextSmallerRight[stack.pop()] = i
stack.append(i)
stack = []
nextSmallerLeft = [-1] * n
for i in range(n-1,-1,-1):
while stack and nums[stack[-1]] >= nums[i]:
nextSmallerLeft[stack.pop()] = i
stack.append(i)
stack = []
nextLargerRight = [n] * n
for i in range(n):
while stack and nums[stack[-1]] <= nums[i]:
nextLargerRight[stack.pop()] = i
stack.append(i)
stack = []
nextLargerLeft = [-1] * n
for i in range(n-1,-1,-1):
while stack and nums[stack[-1]] < nums[i]:
nextLargerLeft[stack.pop()] = i
stack.append(i)
sumMax = 0
sumMin = 0
for i in range(n):
leftMaxRange = i-(nextLargerLeft[i]+1) + 1
rightMaxRange = nextLargerRight[i]-1-i + 1
sumMax += nums[i] * leftMaxRange * rightMaxRange
leftMinRange = i-(nextSmallerLeft[i]+1) + 1
rightMinRange = nextSmallerRight[i]-1-i + 1
sumMin += nums[i] * leftMinRange * rightMinRange
return sumMax - sumMin | sum-of-subarray-ranges | [Python] 5-pass Monotonic Stack for O(n) runtime | ngnhatnam188 | 0 | 18 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,061 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2652794/monotonic-stack-to-get-the-index-of-left-and-right-max-or-min-values. | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
# questions: how equal values are handled?
stack_min = [] # index of monotonic increasing stack of values in nums.
stack_max = [] # index of monotonic decreasing stack of values in nums.
res = 0
for i in range(len(nums) + 1):
while stack_min and (i == len(nums) or nums[stack_min[-1]] > nums[i]):
idx = stack_min.pop()
left_min = stack_min[-1] if stack_min else -1
right_min = i
res -= nums[idx] * (idx - left_min) * (i - idx)
stack_min.append(i)
while stack_max and (i == len(nums) or nums[stack_max[-1]] < nums[i]):
idx = stack_max.pop()
left_max = stack_max[-1] if stack_max else -1
right_max = i
res += nums[idx] * (idx - left_max) * (i - idx)
stack_max.append(i)
return res | sum-of-subarray-ranges | monotonic stack to get the index of left and right max or min values. | michaelniki | 0 | 27 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,062 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2516108/Python3-Easy-to-Understand-Using-Monotonic-Stack | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
n=len(nums)
stack=[]
res=0
nextSmaller=[n]*n
for i in range(n):
while stack and nums[stack[-1]]>=nums[i]:
nextSmaller[stack[-1]]=i
stack.pop()
stack.append(i)
while stack:
stack.pop()
prevSmaller=[-1]*n
for i in range(n-1,-1,-1):
while stack and nums[stack[-1]]>nums[i]:
prevSmaller[stack[-1]]=i
stack.pop()
stack.append(i)
while stack:
stack.pop()
nextGreater=[n]*n
for i in range(n):
while stack and nums[stack[-1]]<=nums[i]:
nextGreater[stack[-1]]=i
stack.pop()
stack.append(i)
while stack:
stack.pop()
prevGreater=[-1]*n
for i in range(n-1,-1,-1):
while stack and nums[stack[-1]]<nums[i]:
prevGreater[stack[-1]]=i
stack.pop()
stack.append(i)
for i in range(n):
l=prevGreater[i]
r=nextGreater[i]
res+=nums[i]*(i-l)*(r-i)
for i in range(n):
l=prevSmaller[i]
r=nextSmaller[i]
res-=nums[i]*(i-l)*(r-i)
return res | sum-of-subarray-ranges | [Python3] Easy to Understand Using Monotonic Stack | Jason_Zhong | 0 | 187 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,063 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2498030/Python3-or-5-lines-or-Easy-way-with-Memoization | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
@cache
def dfs(i, maxVal, minVal):
if i >= len(nums): return maxVal-minVal
return dfs(i+1, max(maxVal, nums[i]), min(minVal, nums[i])) + (maxVal-minVal)
return sum(dfs(i, val, val) for i, val in enumerate(nums)) | sum-of-subarray-ranges | Python3 | 5 lines | Easy way with Memoization | minhmanho | 0 | 117 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,064 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2475743/Python-runtime-81.74-memory-42.98 | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
ans = 0
for first in range(len(nums)):
mini = maxi = nums[first]
for sec in range(first, len(nums)):
if nums[sec] > maxi:
maxi = nums[sec]
elif nums[sec] < mini:
mini = nums[sec]
diff = maxi - mini
ans += diff
return ans | sum-of-subarray-ranges | Python, runtime 81.74% memory 42.98% | tsai00150 | 0 | 207 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,065 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2475743/Python-runtime-81.74-memory-42.98 | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
# sum of all maxes in subarray - sum of all mins in subarray
# use monotonous increase stack to implement
min_nums = [-float('inf')] + nums + [-float('inf')]
min_stack = []
mins = 0
for i in range(len(min_nums)):
while min_stack and min_nums[i]<min_nums[min_stack[-1]]:
target = min_stack.pop()
left = target - min_stack[-1]
right = i - target
mins += min_nums[target] * left * right
min_stack.append(i)
max_nums = [float('inf')] + nums + [float('inf')]
max_stack = []
maxs = 0
for i in range(len(max_nums)):
while max_stack and max_nums[i]>max_nums[max_stack[-1]]:
target = max_stack.pop()
left = target - max_stack[-1]
right = i - target
maxs += max_nums[target] * left * right
max_stack.append(i)
return maxs-mins | sum-of-subarray-ranges | Python, runtime 81.74% memory 42.98% | tsai00150 | 0 | 207 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,066 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/2092508/Brute-Force-O(N2)-Python-Solution | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
ans = 0
for i in range(len(nums)):
mx = nums[i]
mn = nums[i]
for j in range(i,len(nums)):
mx = max(mx,nums[j])
mn = min(mn,nums[j])
ans += mx - mn
return ans | sum-of-subarray-ranges | Brute Force O(N2) Python Solution | DietCoke777 | 0 | 154 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,067 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1856764/Two-Stack-o(n) | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
min_s, max_s = [-1], [-1]
ret = 0
for i, n in enumerate(nums):
while len(min_s) > 1 and n <= nums[min_s[-1]]:
top = min_s.pop(-1)
val = nums[top] * (i - top) * (top - min_s[-1])
ret -= val
min_s.append(i)
while len(max_s) > 1 and n >= nums[max_s[-1]]:
top = max_s.pop(-1)
val = nums[top] * (i - top) * (top - max_s[-1])
ret += val
max_s.append(i)
length = len(nums)
while len(min_s) > 1:
top = min_s.pop(-1)
ret -= nums[top] * (length - top) * (top - min_s[-1])
while len(max_s) > 1:
top = max_s.pop(-1)
ret += nums[top] * (length - top) * (top - max_s[-1])
return ret | sum-of-subarray-ranges | Two Stack o(n) | BichengWang | 0 | 846 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,068 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624688/Easy-python3-solution | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
res=0
n=len(nums)
for i in range(n):
mx=nums[i]
mn=nums[i]
for j in range(i+1,n):
if nums[j]>mx:
mx=nums[j]
elif nums[j]<mn:
mn=nums[j]
res+=(mx-mn)
return res | sum-of-subarray-ranges | Easy python3 solution | Karna61814 | 0 | 313 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,069 |
https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1741748/Solution-using-python3 | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
result = 0
n = len(nums)
for i in range(n) :
Min, Max = nums[i], nums[i]
for j in range(i, n, 1) :
Min = min(Min, nums[j])
Max = max(Max, nums[j])
result -= Max - Min
return abs(result) | sum-of-subarray-ranges | Solution using python3 | shakilbabu | -1 | 379 | sum of subarray ranges | 2,104 | 0.602 | Medium | 29,070 |
https://leetcode.com/problems/watering-plants-ii/discuss/1624252/Python3-2-pointers | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
ans = 0
lo, hi = 0, len(plants)-1
canA, canB = capacityA, capacityB
while lo < hi:
if canA < plants[lo]: ans += 1; canA = capacityA
canA -= plants[lo]
if canB < plants[hi]: ans += 1; canB = capacityB
canB -= plants[hi]
lo, hi = lo+1, hi-1
if lo == hi and max(canA, canB) < plants[lo]: ans += 1
return ans | watering-plants-ii | [Python3] 2 pointers | ye15 | 8 | 340 | watering plants ii | 2,105 | 0.501 | Medium | 29,071 |
https://leetcode.com/problems/watering-plants-ii/discuss/1625775/Python-3-two-pointers-O(n) | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
a, b = 0, len(plants) - 1
waterA, waterB = capacityA, capacityB
res = 0
while a < b:
if waterA < plants[a]:
res += 1
waterA = capacityA
waterA -= plants[a]
a += 1
if waterB < plants[b]:
res += 1
waterB = capacityB
waterB -= plants[b]
b -= 1
if a == b and waterA < plants[a] and waterB < plants[a]:
res += 1
return res | watering-plants-ii | Python 3 two pointers O(n) | dereky4 | 1 | 51 | watering plants ii | 2,105 | 0.501 | Medium | 29,072 |
https://leetcode.com/problems/watering-plants-ii/discuss/1624324/Python-Solution-Two-PointersO(N)-solution | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
alice,bob = 0,len(plants)-1
result,capacity_A,capacity_B = 0,capacityA,capacityB
while alice < bob:
if capacity_A < plants[alice]:
capacity_A = capacityA
result += 1
capacity_A -= plants[alice]
if capacity_B < plants[bob]:
capacity_B = capacityB
result += 1
capacity_B -= plants[bob]
alice += 1
bob -= 1
if alice == bob:
max_capacity = max(capacity_A,capacity_B)
if max_capacity < plants[alice]: result += 1
return result | watering-plants-ii | Python Solution Two Pointers[O(N) solution] | pratushah | 1 | 32 | watering plants ii | 2,105 | 0.501 | Medium | 29,073 |
https://leetcode.com/problems/watering-plants-ii/discuss/2604881/Python-Readable-and-easy-Solution | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
# check whether they will reach the same plant (uneven array length)
same_plant = len(plants) % 2 == 1
# get the middle plant
mid_plant = len(plants)//2
# make the two buckets
a_bucket = capacityA
b_bucket = capacityB
fillups = 0
for idx in range(mid_plant):
# check alice
if a_bucket >= plants[idx]:
a_bucket -= plants[idx]
else:
fillups += 1
a_bucket = capacityA - plants[idx]
# check bob
if b_bucket >= plants[-idx-1]:
b_bucket -= plants[-idx-1]
else:
fillups += 1
b_bucket = capacityB - plants[-idx-1]
# check whether we meet at the same place and need to refill there
leftover_plant = plants[mid_plant]
if same_plant and a_bucket < leftover_plant and b_bucket < leftover_plant:
fillups += 1
return fillups | watering-plants-ii | [Python] - Readable and easy Solution | Lucew | 0 | 7 | watering plants ii | 2,105 | 0.501 | Medium | 29,074 |
https://leetcode.com/problems/watering-plants-ii/discuss/2479469/Python-Solution-optimization-is-important-oror-clean-code | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
n=len(plants)
if n==1:
if capacityA>=plants[0] or capacityB>=plants[0]:
return 0
else:
return 1
s=0
pa=capacityA
pb=capacityB
length=n
if n%2!=0:
length=n+1
for i in range(1,length//2):
da=capacityA-plants[i-1]
db=capacityB-plants[n-i]
if i==n-i-1:
if da>=plants[i] or db>=plants[i]:
return s
else:
return s+1
if da>=plants[i]:
capacityA=da
else:
s+=1
capacityA=pa
if db>=plants[n-i-1]:
capacityB=db
else:
s+=1
capacityB=pb
return s | watering-plants-ii | Python Solution - optimization is important || clean code | T1n1_B0x1 | 0 | 9 | watering plants ii | 2,105 | 0.501 | Medium | 29,075 |
https://leetcode.com/problems/watering-plants-ii/discuss/1701980/Python-Wrong-answer-or-Help-debug | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
ans = 0
lo, hi = 0, len(plants)-1
canA, canB = capacityA, capacityB
while lo < hi:
if canA < plants[lo]:
ans += 1
canA = capacityA
canA -= plants[lo]
if canB < plants[hi]:
ans += 1
canB = capacityB
canB -= plants[hi]
lo, hi = lo+1, hi-1
if lo == hi and max(canA, canB) < plants[lo]: ans += 1
return ans | watering-plants-ii | Python Wrong answer | Help debug | abkc1221 | 0 | 49 | watering plants ii | 2,105 | 0.501 | Medium | 29,076 |
https://leetcode.com/problems/watering-plants-ii/discuss/1648820/Python-very-easy-explained | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
a, b, cp1, cp2, self.cnt = 0, len(plants)-1, capacityA, capacityB, 0
def refill(name):
self.cnt += 1
return capacityA if name == 'Alice' else capacityB
while a <= b:
if a == b:
mx = max(cp1,cp2)
if plants[a] > mx: refill('Anyone')
break
if cp1 < plants[a]: cp1 = refill('Alice')
cp1 -= plants[a]
if cp2 < plants[b]: cp2 = refill('Bob')
cp2 -= plants[b]
a += 1
b -= 1
return self.cnt | watering-plants-ii | ✅ Python very easy explained | dhananjay79 | 0 | 51 | watering plants ii | 2,105 | 0.501 | Medium | 29,077 |
https://leetcode.com/problems/watering-plants-ii/discuss/1629679/Linear-solution-80-speed | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
len_plants = len(plants)
len1 = len_plants - 1
can_a, can_b = capacityA, capacityB
refills = 0
for i in range(len_plants // 2):
if can_a < plants[i]:
refills += 1
can_a = capacityA
can_a -= plants[i]
if can_b < plants[len1 - i]:
refills += 1
can_b = capacityB
can_b -= plants[len1 - i]
if len_plants % 2 and can_a < plants[len_plants // 2] > can_b:
refills += 1
return refills | watering-plants-ii | Linear solution, 80% speed | EvgenySH | 0 | 38 | watering plants ii | 2,105 | 0.501 | Medium | 29,078 |
https://leetcode.com/problems/watering-plants-ii/discuss/1624685/Easy-python3-solution | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
i=0
j=len(plants)-1
A=capacityA
B=capacityB
refill=0
while i<=j:
if i==j:
if capacityA==capacityB:
if capacityA<plants[i]:
refill+=1
i+=1
else:
if capacityA>capacityB:
if capacityA<plants[i]:
refill+=1
i+=1
else:
if capacityB<plants[i]:
refill+=1
j-=1
else:
if plants[i]<=capacityA:
capacityA-=plants[i]
i+=1
else:
refill+=1
capacityA=A
capacityA-=plants[i]
i+=1
if plants[j]<=capacityB:
capacityB-=plants[j]
j-=1
else:
refill+=1
capacityB=B
capacityB-=plants[j]
j-=1
return refill | watering-plants-ii | Easy python3 solution | Karna61814 | 0 | 16 | watering plants ii | 2,105 | 0.501 | Medium | 29,079 |
https://leetcode.com/problems/watering-plants-ii/discuss/1624328/Two-Pointers-or-Easy-to-Understand | class Solution:
def minimumRefill(self, nums: List[int], capacityA: int, capacityB: int) -> int:
n = len(nums)
i = 0
j = n-1
canA = capacityA
canB = capacityB
count = 0
while(i<j):
# water the left plant
if canA < nums[i]:
canA = capacityA
count += 1
canA -= nums[i]
i += 1
# water the right plant
if canB < nums[j]:
canB = capacityB
count += 1
canB -= nums[j]
j -= 1
# if both point to same plant in cases (it'll only happen if n is odd)
if i==j:
if canA > canB:
if canA < nums[i]:
canA = capacityA
count += 1
canA -= nums[i]
else:
if canB < nums[j]:
canB = capacityB
count += 1
canB -= nums[j]
return count | watering-plants-ii | Two Pointers | Easy to Understand | CaptainX | 0 | 43 | watering plants ii | 2,105 | 0.501 | Medium | 29,080 |
https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/discuss/1624294/Sliding-Window-or-Prefix-Suffix-Sum-or-Easy-to-understand | class Solution:
def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
fruitMap = defaultdict(int)
for position, amount in fruits:
fruitMap[position] = amount
if k == 0:
return fruitMap[startPos]
totalLeft = 0 # max sum if we go k steps to the left
totalRight = 0 # max sum if we go k steps to the right
inBetween = 0 # max sum if we go x steps to the left & k steps to the right (ensuring that we don't move more than k steps in total)
dp = dict()
for i in range(startPos,startPos-k-1, -1):
totalLeft += fruitMap[i]
dp[i] = totalLeft
for i in range(startPos,startPos+k+1):
totalRight += fruitMap[i]
dp[i] = totalRight
leftSteps = 1
rightSteps = k-2
while rightSteps > 0:
currAmount = 0
# go right & collect
currAmount += dp[startPos-leftSteps]
# go left & collect
currAmount += dp[startPos+rightSteps]
inBetween = max(inBetween, currAmount-fruitMap[startPos])
leftSteps += 1
rightSteps -= 2
leftSteps = k-2
rightSteps = 1
while leftSteps > 0:
currAmount = 0
# go right & collect
currAmount += dp[startPos-leftSteps]
# go left & collect
currAmount += dp[startPos+rightSteps]
inBetween = max(inBetween, currAmount-fruitMap[startPos])
leftSteps -= 2
rightSteps += 1
return max(totalLeft, totalRight, inBetween) | maximum-fruits-harvested-after-at-most-k-steps | ✅ Sliding Window | Prefix Suffix Sum | Easy to understand | CaptainX | 1 | 268 | maximum fruits harvested after at most k steps | 2,106 | 0.351 | Hard | 29,081 |
https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/discuss/1625511/Python3-sliding-window | class Solution:
def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
ans = rsm = ii = 0
for i, (p, x) in enumerate(fruits):
if p > startPos + k: break
rsm += x
if p <= startPos: fn = lambda ii: startPos - fruits[ii][0]
else: fn = lambda ii: min(2*(p-startPos) + (startPos-fruits[ii][0]), (p-startPos) + 2*(startPos-fruits[ii][0]))
while ii <= i and fn(ii) > k:
rsm -= fruits[ii][1]
ii += 1
ans = max(ans, rsm)
return ans | maximum-fruits-harvested-after-at-most-k-steps | [Python3] sliding window | ye15 | 0 | 58 | maximum fruits harvested after at most k steps | 2,106 | 0.351 | Hard | 29,082 |
https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/discuss/1625507/Python-3-Hint-solution | class Solution:
def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
f = [0] * (2 * 10**5 + 1)
for a, b in fruits:
f[a] = b
f_acc = list(accumulate(f, initial=0))
n = len(f_acc)
startPos += 1
left_only = f_acc[startPos] - f_acc[max(0, startPos - k - 1)]
right_only = f_acc[min(n - 1, startPos + k)] - f_acc[startPos - 1]
ans = max(left_only, right_only)
# turn left and then right
for i in range(1, (k - 1) // 2 + 1):
first_left = f_acc[startPos] - f_acc[max(0, startPos - i - 1)]
then_right = f_acc[min(n - 1, startPos + k-2*i)] - f_acc[startPos]
first_right = f_acc[min(n - 1, startPos + i)] - f_acc[startPos - 1]
then_left = f_acc[startPos - 1] - f_acc[max(0, startPos - (k - 2*i) - 1)]
ans = max(ans, first_left + then_right, first_right + then_left)
return ans | maximum-fruits-harvested-after-at-most-k-steps | [Python 3] Hint solution | chestnut890123 | 0 | 53 | maximum fruits harvested after at most k steps | 2,106 | 0.351 | Hard | 29,083 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2022159/Python-Clean-and-Simple-%2B-One-Liner! | class Solution:
def firstPalindrome(self, words):
for word in words:
if word == word[::-1]: return word
return "" | find-first-palindromic-string-in-the-array | Python - Clean and Simple + One-Liner! | domthedeveloper | 3 | 128 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,084 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2022159/Python-Clean-and-Simple-%2B-One-Liner! | class Solution:
def firstPalindrome(self, words):
for word in words:
if self.isPalindrome(word): return word
return ""
def isPalindrome(self, word):
l, r = 0, len(word)-1
while l < r:
if word[l] != word[r]: return False
l += 1
r -= 1
return True | find-first-palindromic-string-in-the-array | Python - Clean and Simple + One-Liner! | domthedeveloper | 3 | 128 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,085 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2022159/Python-Clean-and-Simple-%2B-One-Liner! | class Solution:
def firstPalindrome(self, words):
return next((word for word in words if word==word[::-1]), "") | find-first-palindromic-string-in-the-array | Python - Clean and Simple + One-Liner! | domthedeveloper | 3 | 128 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,086 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/1635153/Python3-1-line | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
return next((word for word in words if word == word[::-1]), "") | find-first-palindromic-string-in-the-array | [Python3] 1-line | ye15 | 3 | 325 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,087 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/1647011/Python-one-liner | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
return next(s for s in words + [''] if s == s[::-1]) | find-first-palindromic-string-in-the-array | Python one-liner | emwalker | 2 | 84 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,088 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/1635020/Easy-and-explained-Python-Solution-! | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
def checkPalindrome(word):
N = len(word)
front = 0
back = N-1
while front<back:
if word[front] == word[back]:
front+=1
back-=1
else:
return False
return True
for word in words:
flag = checkPalindrome(word)
if flag:
return word
return "" | find-first-palindromic-string-in-the-array | Easy and explained Python Solution ! | mostlyAditya | 2 | 214 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,089 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2221629/Python-solution-for-beginners-by-beginner. | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for i in words:
if i == i[::-1]:
return i
return '' | find-first-palindromic-string-in-the-array | Python solution for beginners by beginner. | EbrahimMG | 1 | 50 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,090 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2161104/Simple-Logic-in-python | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
return next((word for word in words if word == word[::-1]), '') | find-first-palindromic-string-in-the-array | Simple Logic in python | writemeom | 1 | 47 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,091 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/1856795/Python-lightweight-solution | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for i in words:
if i == i[::-1]:
return i
return "" | find-first-palindromic-string-in-the-array | Python lightweight solution | alishak1999 | 1 | 61 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,092 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2839351/Easy-solution | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for x in words:
if x == x[::-1]:
return x
break
return "" | find-first-palindromic-string-in-the-array | Easy solution | _debanjan_10 | 0 | 4 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,093 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2821357/PYTHON-SIMPLE-SOLUTION-in-just-4-lines | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for i in words:
if i==i[::-1]:
return i
break
return "" | find-first-palindromic-string-in-the-array | PYTHON SIMPLE SOLUTION in just 4 lines | ameenusyed09 | 0 | 3 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,094 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2818592/Fast-and-Simple-Python-Solution | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for word in words:
if word[::-1] == word:
return word
return "" | find-first-palindromic-string-in-the-array | Fast and Simple Python Solution | PranavBhatt | 0 | 3 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,095 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2791030/Simple-Python3-Soln-Use-palindrome-code-98.45-faster | class Solution:
def firstPalindrome(self, words):
for word in words:
size = len(word)
mid_size = size//2
first_halve = word[0:mid_size][::-1]
second_halve = word[mid_size if size % 2 == 0 else ((mid_size)+1):]
if first_halve == second_halve:
return word
return "" | find-first-palindromic-string-in-the-array | Simple Python3 Soln-Use palindrome code-98.45% faster | alamwasim29 | 0 | 4 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,096 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2753993/Simplest-solution-Python3-! | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for word in words:
if word == word[::-1]:
return word
break
else:
continue
return "" | find-first-palindromic-string-in-the-array | Simplest solution Python3 ! | avs-abhishek123 | 0 | 2 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,097 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2722650/Python-oneliner | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
return [i for i in words if i == i[::-1]][0] if [i for i in words if i == i[::-1]] else "" | find-first-palindromic-string-in-the-array | Python oneliner | iakylbek | 0 | 1 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,098 |
https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2719549/Python-Solution | class Solution:
def firstPalindrome(self, words: List[str]) -> str:
for word in words:
if word == word[::-1]:
return word
return "" | find-first-palindromic-string-in-the-array | Python Solution | danishs | 0 | 4 | find first palindromic string in the array | 2,108 | 0.786 | Easy | 29,099 |
Subsets and Splits