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/number-of-laser-beams-in-a-bank/discuss/1895611/Python-easy-to-read-and-understand | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
prev, cnt = 0, 0
ans = 0
for curr in bank:
cnt = curr.count('1')
ans += prev*cnt
if cnt > 0:
prev = cnt
return ans | number-of-laser-beams-in-a-bank | Python easy to read and understand | sanial2001 | 0 | 36 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,400 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1886200/Simple-Python-Solution-or-Fater-Than-93.62-or-O(mn)-Time-Complexity | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
secDeviceCnt = [s.count('1') for s in bank]
beamCnt = 0
prevCnt = secDeviceCnt[0]
for c in secDeviceCnt[1:]:
if c:
beamCnt += (prevCnt * c)
prevCnt = c
return beamCnt | number-of-laser-beams-in-a-bank | Simple Python Solution | Fater Than 93.62% | O(mn) Time Complexity | harshnavingupta | 0 | 37 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,401 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1828470/Python-or-Iterative | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
r,c=len(bank),len(bank[0])
ans=0
for i in range(r):
if '1' in bank[i]:
cnt=0
firstLaser=True
for j in range(c):
if bank[i][j]=='1':
if firstLaser:
k=i+1
while k<r:
firstLaser=False
if '1' in bank[k]:
cnt=bank[k].count('1')
break
k+=1
ans+=cnt
return ans | number-of-laser-beams-in-a-bank | Python | Iterative | heckt27 | 0 | 15 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,402 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1808137/Python-simple-O(mn)-time-O(1)-space-solution | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
counts = []
res = 0
prev = 0
for b in bank:
c = b.count('1')
if c != 0:
res += c*prev
prev = c
return res | number-of-laser-beams-in-a-bank | Python simple O(mn) time, O(1) space solution | byuns9334 | 0 | 25 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,403 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1791935/python-easy-counting | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
n = len(bank)
count = prev = 0
# idea is to count 1's in each row and add the product of previous non empty row's count with current
for i in range(n):
c = bank[i].count("1")
if c > 0:
if i > 0:
count += c*prev
prev = c
return count | number-of-laser-beams-in-a-bank | python easy counting | abkc1221 | 0 | 20 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,404 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1664810/Python3-Simple-Solution-O(N*M)-time | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
prev, res = 0, 0
for lasers in bank:
num_ones = len(lasers.replace("0", ""))
if num_ones == 0:
continue
res += prev * num_ones
prev = num_ones
return res | number-of-laser-beams-in-a-bank | Python3 Simple Solution O(N*M) time | hcoderz | 0 | 45 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,405 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1664739/Python3-solution | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
m = len(bank)
n = len(bank[0])
c = 0
for i in range(m):
if '1' in bank[i]:
for j in range(i+1,m):
if '1' in bank[j]:
c += bank[i].count('1') * bank[j].count('1')
break
return c | number-of-laser-beams-in-a-bank | Python3 solution | EklavyaJoshi | 0 | 26 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,406 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1663824/Python-3-O(N*M)-time-O(1)-space-checking-each-row-with-comments | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
num_of_lasers = 0
prev_one_count = 0
# Iterate through like a matrix
for row in bank:
# We set a one count where we increment for the amount of times we see 1 in the current row
one_count = 0
for num in row:
if num == "1":
one_count += 1
# If we dont encounter any 1s, then the current row has no laser devices
if one_count == 0:
continue
# However, if we DO encounter 1s but we haven't previously encountered any 1s, we continue to
# search for more 1s below this row
if prev_one_count == 0:
prev_one_count = one_count
continue
# In the case that we do encounter 1s and have encountered 1s before means there's a laser between the preceding row
# and this row. The number of lasers between row1 and row2 is really just row1_lasers * row2_lasers.
num_of_lasers += one_count * prev_one_count
prev_one_count = one_count
# Fin
return num_of_lasers | number-of-laser-beams-in-a-bank | [Python 3] O(N*M) time, O(1) space - checking each row, with comments | sagyakwa | 0 | 36 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,407 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1662623/List-comprehension-90-speed | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
devices = [count for row in bank if (count := row.count("1")) > 0]
return (sum(a * b for a, b in zip(devices, devices[1:]))
if len(devices) > 1 else 0) | number-of-laser-beams-in-a-bank | List comprehension, 90% speed | EvgenySH | 0 | 27 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,408 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1661496/Python3-Solution-Easy-to-Understand-(Accepted)-(Commented)-(Clean) | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
//A laser at ith row can have a path with all the lasers which are directly available to it at the previous rows
prev = 0 //Keep a count of lasers that were available at the prev row if the row had atleast 1 laser
ans = 0 //Store the number of laser paths
for i in bank: //Iterate each row in the bank matrix
count = i.count('1') //Get the count of 1s in each row
ans += count*prev //Increment ans with count of 1s in the row with the count of prev
if count > 0: //If the row had atleast 1 laser then change the prev to count
prev = count
return ans | number-of-laser-beams-in-a-bank | Python3 Solution Easy to Understand (Accepted) (Commented) (Clean) | sdasstriver9 | 0 | 25 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,409 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1661340/Easy-Python-Solution-or-Finding-Product | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
Sum = 0
PrevNum = 0
for r in bank:
Val = r.count("1")
Sum += (PrevNum*Val)
if(Val != 0):
PrevNum = Val
return Sum | number-of-laser-beams-in-a-bank | Easy Python Solution | Finding Product | sunilsai1066 | 0 | 18 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,410 |
https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/1661152/Python-Simple-and-Easy-to-Understand-Solution | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
prev, res = 0, 0
for i in range(len(bank)):
ones = bank[i].count("1")
if ones == 0: continue #we can ignore rows without any "1"
if prev > 0: #if we have some 1's in prev row we multiply with current ones to get number of lasers
res += prev * ones
prev = ones #storing curr 1's to find lasers from current to next row
return res | number-of-laser-beams-in-a-bank | [Python] Simple and Easy to Understand Solution | Saksham003 | 0 | 24 | number of laser beams in a bank | 2,125 | 0.826 | Medium | 29,411 |
https://leetcode.com/problems/destroying-asteroids/discuss/1775912/Simple-python-solution-or-85-lesser-memory | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids = sorted(asteroids)
for i in asteroids:
if i <= mass:
mass += i
else:
return False
return True | destroying-asteroids | ✔Simple python solution | 85% lesser memory | Coding_Tan3 | 2 | 129 | destroying asteroids | 2,126 | 0.495 | Medium | 29,412 |
https://leetcode.com/problems/destroying-asteroids/discuss/2318584/Python-or-90-faster-than-other...-or-Greedy-Solution-very-intuitive-or-Using-sorting-technique | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
# ///// TC O(nlogn) //////
asteroids.sort()
for asteroid in asteroids:
if mass >= asteroid:
mass += asteroid
else:
return False
return True | destroying-asteroids | Python | 90% faster than other... | Greedy Solution very intuitive | Using sorting technique | __Asrar | 1 | 68 | destroying asteroids | 2,126 | 0.495 | Medium | 29,413 |
https://leetcode.com/problems/destroying-asteroids/discuss/1661138/Python3-Simple-(By-Sorting) | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
for i in range(len(asteroids)):
if mass>=asteroids[i]:
mass+=asteroids[i]
else:
return False
return True | destroying-asteroids | [Python3] Simple (By Sorting) | ro_hit2013 | 1 | 30 | destroying asteroids | 2,126 | 0.495 | Medium | 29,414 |
https://leetcode.com/problems/destroying-asteroids/discuss/1661001/Python3-greedy | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
for x in sorted(asteroids):
if mass < x: return False
mass += x
return True | destroying-asteroids | [Python3] greedy | ye15 | 1 | 111 | destroying asteroids | 2,126 | 0.495 | Medium | 29,415 |
https://leetcode.com/problems/destroying-asteroids/discuss/2848198/Python-greedy-approach-solution | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
for i in asteroids:
if mass >= i:
mass += i
else:
return False
return True | destroying-asteroids | Python greedy approach solution | ankurkumarpankaj | 0 | 1 | destroying asteroids | 2,126 | 0.495 | Medium | 29,416 |
https://leetcode.com/problems/destroying-asteroids/discuss/1791966/Python-sorting | class Solution:
def asteroidsDestroyed(self, mass: int, arr: List[int]) -> bool:
arr.sort() # sort to accummulate maximum smaller asteroids
for i in range(len(arr)):
if arr[i] <= mass:
mass += arr[i]
else:
return False # if still smaller than some asteroid then its not possible
return True | destroying-asteroids | Python sorting | abkc1221 | 0 | 59 | destroying asteroids | 2,126 | 0.495 | Medium | 29,417 |
https://leetcode.com/problems/destroying-asteroids/discuss/1734421/JavaPython-3-Simple-Solution-oror-Sort-and-Apply-Greedy-Algorithm | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
for i in asteroids:
if i > mass:
return False
mass = mass + i
return True | destroying-asteroids | [Java/Python 3] Simple Solution || Sort & Apply Greedy Algorithm | abhijeetmallick29 | 0 | 29 | destroying asteroids | 2,126 | 0.495 | Medium | 29,418 |
https://leetcode.com/problems/destroying-asteroids/discuss/1723066/Easy-Python-Solution | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
for i in range(len(asteroids)):
if asteroids[i]<=mass:
mass+=asteroids[i]
else:
return False
return True | destroying-asteroids | Easy Python Solution | Sneh17029 | 0 | 46 | destroying asteroids | 2,126 | 0.495 | Medium | 29,419 |
https://leetcode.com/problems/destroying-asteroids/discuss/1720881/Python3-accepted-solution | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids = sorted(asteroids)
for i in range(len(asteroids)):
if(mass >= asteroids[i]):
mass += asteroids[i]
else:
return False
return True | destroying-asteroids | Python3 accepted solution | sreeleetcode19 | 0 | 22 | destroying asteroids | 2,126 | 0.495 | Medium | 29,420 |
https://leetcode.com/problems/destroying-asteroids/discuss/1674022/Python-sorting | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
for a in sorted(asteroids):
if a > mass:
return False
mass += a
return True | destroying-asteroids | Python, sorting | blue_sky5 | 0 | 50 | destroying asteroids | 2,126 | 0.495 | Medium | 29,421 |
https://leetcode.com/problems/destroying-asteroids/discuss/1665029/Python3-O(n-log-n)-solution-Easy-to-Understand-(sorting-%2B-stack) | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort(reverse=True)
while asteroids:
asteroid = asteroids.pop()
if asteroid <= mass:
mass += asteroid
else:
return False
return True | destroying-asteroids | Python3 O(n log n) solution - Easy to Understand (sorting + stack) | hcoderz | 0 | 39 | destroying asteroids | 2,126 | 0.495 | Medium | 29,422 |
https://leetcode.com/problems/destroying-asteroids/discuss/1663761/Python-3-O(n-logn)-Time-and-O(n)-space-(Sorting-%2B-Greedy) | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
running_sum = mass
for num in asteroids:
if num > running_sum:
return False
running_sum += num
return True | destroying-asteroids | [Python 3] O(n logn) Time and O(n) space (Sorting + Greedy) | sagyakwa | 0 | 34 | destroying asteroids | 2,126 | 0.495 | Medium | 29,423 |
https://leetcode.com/problems/destroying-asteroids/discuss/1661521/Python3-Easy-Solution-(Accepted)-(Commented)-(Clean) | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
//Approach is to not destroy the planet so the smallest nubmer will be choosen first from the asteroids array so
//that the mass can be increased. Hence the asteroids array has to be sorted. Now iterate through the staeroids
//array and see if the element is greater than mass then return False else increase the mass by the value of the
//element
asteroids.sort() //Sort the array in ascending order
for i in asteroids: //Iterate through the asteroids array
if i <= mass: //If the element's value is less than or equal to the current value of mass then increment the value of mass by the element's value
mass += i
else: //Else the value of asteroid is greter than the current value of mass, hence asteroid cannot be destroyed, so return false
return False
return True | destroying-asteroids | Python3 Easy Solution (Accepted) (Commented) (Clean) | sdasstriver9 | 0 | 24 | destroying asteroids | 2,126 | 0.495 | Medium | 29,424 |
https://leetcode.com/problems/destroying-asteroids/discuss/1661127/Python-Easy-Solution-O(nlogn)-Solution-or-Beginner-Understandable | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort() #Sorting Given Array
for i in asteroids:
if(i <= mass):
mass += i
else:
return False
return True | destroying-asteroids | Python Easy Solution O(nlogn) Solution | Beginner Understandable | sunilsai1066 | 0 | 19 | destroying asteroids | 2,126 | 0.495 | Medium | 29,425 |
https://leetcode.com/problems/destroying-asteroids/discuss/1662370/Python3-Sort-and-Binary-Search-Solution | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids.sort()
while asteroids:
ind = bisect.bisect_right(asteroids, mass)
if ind == len(asteroids): return True
elif ind == 0: return False
else:
#it can collide with all asteroids before this index
mass += sum(asteroids[:ind])
asteroids = asteroids[ind:] | destroying-asteroids | Python3 Sort and Binary Search Solution | xxHRxx | -2 | 30 | destroying asteroids | 2,126 | 0.495 | Medium | 29,426 |
https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/discuss/1661041/Python3-quite-a-tedious-solution | class Solution:
def maximumInvitations(self, favorite: List[int]) -> int:
n = len(favorite)
graph = [[] for _ in range(n)]
for i, x in enumerate(favorite): graph[x].append(i)
def bfs(x, seen):
"""Return longest arm of x."""
ans = 0
queue = deque([x])
while queue:
for _ in range(len(queue)):
u = queue.popleft()
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
ans += 1
return ans
ans = 0
seen = [False]*n
for i, x in enumerate(favorite):
if favorite[x] == i and not seen[i]:
seen[i] = seen[x] = True
ans += bfs(i, {i, x}) + bfs(x, {i, x})
dp = [0]*n
for i, x in enumerate(favorite):
if dp[i] == 0:
ii, val = i, 0
memo = {}
while ii not in memo:
if dp[ii]:
cycle = dp[ii]
break
memo[ii] = val
val += 1
ii = favorite[ii]
else: cycle = val - memo[ii]
for k in memo: dp[k] = cycle
return max(ans, max(dp)) | maximum-employees-to-be-invited-to-a-meeting | [Python3] quite a tedious solution | ye15 | 5 | 1,000 | maximum employees to be invited to a meeting | 2,127 | 0.337 | Hard | 29,427 |
https://leetcode.com/problems/capitalize-the-title/discuss/1716077/Python-Easy-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
word = ""
for i in range(len(title)):
if len(title[i]) < 3:
word = word + title[i].lower() + " "
else:
word = word + title[i].capitalize() + " "
return word[:-1] | capitalize-the-title | Python Easy Solution | yashitanamdeo | 4 | 413 | capitalize the title | 2,129 | 0.603 | Easy | 29,428 |
https://leetcode.com/problems/capitalize-the-title/discuss/1716077/Python-Easy-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
word = []
for i in range(len(title)):
if len(title[i]) < 3:
word.append(title[i].lower())
else:
word.append(title[i].capitalize())
return " ".join(word) | capitalize-the-title | Python Easy Solution | yashitanamdeo | 4 | 413 | capitalize the title | 2,129 | 0.603 | Easy | 29,429 |
https://leetcode.com/problems/capitalize-the-title/discuss/2194296/Brute-force-and-optimised | class Solution:
def capitalizeTitle(self, title: str) -> str:
s = list(title.split(' '))
sfin = ''
for i in range(len(s)):
if len(s[i])>=3:
sfin += s[i][0].upper()
for j in range(1,len(s[i])):
if s[i][j].isupper():
sfin+=s[i][j].lower()
else:
sfin+=s[i][j]
if i+1!=len(s):
sfin+=' '
else:
for j in range(len(s[i])):
if s[i][j].isupper():
sfin +=s[i][j].lower()
else:
sfin+=s[i][j]
if i+1!=len(s):
sfin+=' '
return sfin | capitalize-the-title | Brute force and optimised | leonsuryaescanor | 1 | 29 | capitalize the title | 2,129 | 0.603 | Easy | 29,430 |
https://leetcode.com/problems/capitalize-the-title/discuss/2194296/Brute-force-and-optimised | class Solution:
def capitalizeTitle(self, title: str) -> str:
sfin = title.split(' ')
res=[]
s=''
for i in sfin:
if len(i)<=2:
s=i.lower()
elif sfin[0][0].islower() or sfin[0][0].isupper():
s=i[0][0].upper()
s+=i[1:].lower()
res.append(s)
return ' '.join(res) | capitalize-the-title | Brute force and optimised | leonsuryaescanor | 1 | 29 | capitalize the title | 2,129 | 0.603 | Easy | 29,431 |
https://leetcode.com/problems/capitalize-the-title/discuss/1864666/Python-one-liner!-Simple-and-Elegant!-Using-Map | class Solution(object):
def capitalizeTitle(self, title):
return " ".join(map(lambda x: x.title() if len(x)>2 else x.lower(), title.split())) | capitalize-the-title | Python - one liner! Simple and Elegant! Using Map | domthedeveloper | 1 | 74 | capitalize the title | 2,129 | 0.603 | Easy | 29,432 |
https://leetcode.com/problems/capitalize-the-title/discuss/1675348/Python-3-One-liner-using-title()-and-lower()-or-Straightforward | class Solution:
def capitalizeTitle(self, title):
return ' '.join(i.title() if len(i) > 2 else i.lower() for i in title.split()) | capitalize-the-title | [Python 3] One-liner using title() and lower() | Straightforward | JK0604 | 1 | 113 | capitalize the title | 2,129 | 0.603 | Easy | 29,433 |
https://leetcode.com/problems/capitalize-the-title/discuss/1675348/Python-3-One-liner-using-title()-and-lower()-or-Straightforward | class Solution:
def capitalizeTitle(self, title):
res = []
for i in title.split():
if len(i) < 3:
res.append(i.lower())
else:
res.append(i.title())
return ' '.join(res) | capitalize-the-title | [Python 3] One-liner using title() and lower() | Straightforward | JK0604 | 1 | 113 | capitalize the title | 2,129 | 0.603 | Easy | 29,434 |
https://leetcode.com/problems/capitalize-the-title/discuss/2845024/Easy-Approach | class Solution:
def capitalizeTitle(self, title: str) -> str:
l=title.split(" ")
ans=[]
if len(title)==0:
return ""
for i in range(len(l)):
string=""
if len(l[i])<=2:
for j in range(len(l[i])):
string+=l[i][j].lower()
ans.append(string)
else:
string+=l[i][0].capitalize()
for j in range(1,len(l[i])):
string+=l[i][j].lower()
ans.append(string)
return " ".join(ans) | capitalize-the-title | Easy Approach | 2003480100009_A | 0 | 2 | capitalize the title | 2,129 | 0.603 | Easy | 29,435 |
https://leetcode.com/problems/capitalize-the-title/discuss/2834446/Python-1-line%3A-Optimal-and-Clean-with-explanation-O(n)-time-and-O(n)-space | class Solution:
# O(n) time : O(n) space
def capitalizeTitle(self, title: str) -> str:
return " ".join([word.capitalize() if len(word) > 2 else word.lower() for word in title.split()]) | capitalize-the-title | Python 1 line: Optimal and Clean with explanation - O(n) time and O(n) space | topswe | 0 | 1 | capitalize the title | 2,129 | 0.603 | Easy | 29,436 |
https://leetcode.com/problems/capitalize-the-title/discuss/2799775/Simple-Python-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
ll = title.split()
for i in range(len(ll)):
if len(ll[i])<=2:
ll[i]= ll[i].lower()
else:
ll[i] = ll[i].capitalize()
return " ".join(ll) | capitalize-the-title | Simple Python solution | Rajeev_varma008 | 0 | 3 | capitalize the title | 2,129 | 0.603 | Easy | 29,437 |
https://leetcode.com/problems/capitalize-the-title/discuss/2765100/easy-and-faster | class Solution:
def capitalizeTitle(self, title: str) -> str:
d=title.split()
res=[]
for i in d:
if(len(i)<=2):
res.append(i.lower())
else:
res.append(i.title())
return " ".join(res) | capitalize-the-title | easy and faster | Raghunath_Reddy | 0 | 4 | capitalize the title | 2,129 | 0.603 | Easy | 29,438 |
https://leetcode.com/problems/capitalize-the-title/discuss/2764267/Python-or-LeetCode-or-2129.-Capitalize-the-Title | class Solution:
def capitalizeTitle(self, title: str) -> str:
s = ""
title = title.split()
for e in title:
if len(e) > 2:
s += e.capitalize()
s += " "
else:
s += e.lower()
s += " "
return s[:-1] | capitalize-the-title | Python | LeetCode | 2129. Capitalize the Title | UzbekDasturchisiman | 0 | 12 | capitalize the title | 2,129 | 0.603 | Easy | 29,439 |
https://leetcode.com/problems/capitalize-the-title/discuss/2764267/Python-or-LeetCode-or-2129.-Capitalize-the-Title | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
word = []
for i in range(len(title)):
if len(title[i]) < 3:
word.append(title[i].lower())
else:
word.append(title[i].capitalize())
return " ".join(word) | capitalize-the-title | Python | LeetCode | 2129. Capitalize the Title | UzbekDasturchisiman | 0 | 12 | capitalize the title | 2,129 | 0.603 | Easy | 29,440 |
https://leetcode.com/problems/capitalize-the-title/discuss/2735006/Python-simple-straight-forward-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
for i in range(len(title)):
if len(title[i]) <= 2:
title[i] = title[i].lower()
else:
title[i] = title[i].title()
return ' '.join(title) | capitalize-the-title | Python simple straight-forward solution | Mark_computer | 0 | 8 | capitalize the title | 2,129 | 0.603 | Easy | 29,441 |
https://leetcode.com/problems/capitalize-the-title/discuss/2718610/easy-approach-in-python | class Solution:
def capitalizeTitle(self, title: str) -> str:
p=title.split(' ')
t=[]
for i in p:
if len(i)<3:
i=i.lower()
t.append(i)
else:
i=i.capitalize()
t.append(i)
return ' '.join(t) | capitalize-the-title | easy approach in python | sindhu_300 | 0 | 7 | capitalize the title | 2,129 | 0.603 | Easy | 29,442 |
https://leetcode.com/problems/capitalize-the-title/discuss/2711189/100-EASY-TO-UNDERSTANDSIMPLECLEAN | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
titleList = ""
for i in title:
if len(i) <= 2:
i = i.lower()
titleList += i
titleList += " "
else:
i = i.lower()
i = i[0].upper() + i[1:]
titleList += i
titleList += " "
return titleList.rstrip() | capitalize-the-title | 🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥 | YuviGill | 0 | 7 | capitalize the title | 2,129 | 0.603 | Easy | 29,443 |
https://leetcode.com/problems/capitalize-the-title/discuss/2698681/Simple-Python-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
ans = ""
l = title.split()
for word in l:
if len(ans) >= 1:
ans += " "
if len(word)<=2:
ans += word.lower()
else:
ans += word[0].upper()
ans += word[1:].lower()
return ans | capitalize-the-title | Simple Python Solution | imkprakash | 0 | 4 | capitalize the title | 2,129 | 0.603 | Easy | 29,444 |
https://leetcode.com/problems/capitalize-the-title/discuss/2625202/one-liner-or-python3 | class Solution:
def capitalizeTitle(self, title: str) -> str:
return(" ".join([i[0].upper()+i[1:].lower() if len(i)>2 else i.lower() for i in title.split()])) | capitalize-the-title | one liner | python3 | lin11116459 | 0 | 16 | capitalize the title | 2,129 | 0.603 | Easy | 29,445 |
https://leetcode.com/problems/capitalize-the-title/discuss/2617157/Easy-One-Line-or-Python | class Solution:
def capitalizeTitle(self, title: str) -> str:
return " ".join([word.lower() if len(word)<3 else word.capitalize() for word in title.split()]) | capitalize-the-title | Easy One Line | Python | Abhi_-_- | 0 | 21 | capitalize the title | 2,129 | 0.603 | Easy | 29,446 |
https://leetcode.com/problems/capitalize-the-title/discuss/2584337/Python-3-multiple-ways-solution-1-liner-to-descriptive-95-ms | class Solution:
def capitalizeTitle(self, title: str) -> str:
#return " ".join([word.lower() if len(word) in {1,2} else word.capitalize() for word in title.split()])
"""
arr = title.split()
for i,word in enumerate(arr):
if len(word) in {1,2}:
arr[i] = arr[i].lower()
else:
arr[i] = arr[i][0].upper() + arr[i][1:].lower() # capitalize function
return " ".join(arr)
"""
# Two pointer
s = list()
i = prev = 0
word = ""
while i <= len(title):
if i == len(title) or title[i] == " " :
length = i - prev
prev = i + 1
if length in {1,2}:
s.append(word)
else:
s.append(word[0].upper() + word[1:])
word = ""
else:
word += title[i].lower()
i += 1
return " ".join(s) | capitalize-the-title | Python 3 multiple ways solution 1 liner to descriptive 95 ms | abhisheksanwal745 | 0 | 37 | capitalize the title | 2,129 | 0.603 | Easy | 29,447 |
https://leetcode.com/problems/capitalize-the-title/discuss/2564241/Simple-Python-Implementation | class Solution:
def capitalizeTitle(self, title: str) -> str:
titles = title.lower().strip().split()
for i,word in enumerate(titles):
if len(word) > 2:
titles[i] = word[0].upper() + word[1:]
return " ".join(titles) | capitalize-the-title | Simple Python Implementation ✔️ | spakash182 | 0 | 43 | capitalize the title | 2,129 | 0.603 | Easy | 29,448 |
https://leetcode.com/problems/capitalize-the-title/discuss/2551429/Python-Solution-ororSimple-and-Easy-Understanding-oror-Clean-code | class Solution:
def capitalizeTitle(self, title: str) -> str:
s = ""
lst = list(title.split())
for item in lst:
if(len(item) > 2):
item = item.capitalize()
s = s + item +" "
else:
s = s + item.lower() + " "
return s.rstrip() | capitalize-the-title | Python Solution ||Simple & Easy Understanding || Clean code | aayushcode07 | 0 | 34 | capitalize the title | 2,129 | 0.603 | Easy | 29,449 |
https://leetcode.com/problems/capitalize-the-title/discuss/2547655/Python-Simple-Python-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
result = ''
title = title.split()
for index in range(len(title)):
if len(title[index]) < 3:
result = result + title[index].lower() + ' '
else:
result = result + title[index].lower().capitalize() + ' '
result = result[:-1]
return result | capitalize-the-title | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 45 | capitalize the title | 2,129 | 0.603 | Easy | 29,450 |
https://leetcode.com/problems/capitalize-the-title/discuss/2368103/Fast-easy-python-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title=title.split()
for i,val in enumerate(title):
if len(val)<=2:
word=val.lower()
else:
word=""
for j,val1 in enumerate(val):
if j==0:
word+=val1.upper()
else:
word+=val1.lower()
title[i]=word
return " ".join(title) | capitalize-the-title | Fast easy python solution | sunakshi132 | 0 | 35 | capitalize the title | 2,129 | 0.603 | Easy | 29,451 |
https://leetcode.com/problems/capitalize-the-title/discuss/2329121/Using-split()-and-capitalize() | class Solution:
def capitalizeTitle(self, title: str) -> str:
# split the title by spaces (words)
# iterate each word
# all words must be lowered (lower())
# only capitalize words w/ len > 2 capitalize()
# modify by title list index update
# Time O(N) Space: O(N)
words = title.split()
for i, word in enumerate(words):
word = word.lower()
if len(word) > 2:
word = word.capitalize()
words[i] = word
return ' '.join(words) | capitalize-the-title | Using split() and capitalize() | andrewnerdimo | 0 | 26 | capitalize the title | 2,129 | 0.603 | Easy | 29,452 |
https://leetcode.com/problems/capitalize-the-title/discuss/2208699/Python3-simple-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
print(title)
for i in range(len(title)):
if 0 < len(title[i]) < 3:
title[i] = title[i].lower()
else:
title[i] = (title[i].lower())[0].upper() + title[i][1:].lower()
return ' '.join(title) | capitalize-the-title | Python3 simple solution | EklavyaJoshi | 0 | 22 | capitalize the title | 2,129 | 0.603 | Easy | 29,453 |
https://leetcode.com/problems/capitalize-the-title/discuss/2142332/faster-than-98.29-oror-Memory-Usage-less-than-96.20 | class Solution:
def capitalizeTitle(self, title: str) -> str:
return ' '.join([word.lower() if len(word) < 3 else word.title() for word in title.split()]) | capitalize-the-title | faster than 98.29% || Memory Usage less than 96.20% | writemeom | 0 | 36 | capitalize the title | 2,129 | 0.603 | Easy | 29,454 |
https://leetcode.com/problems/capitalize-the-title/discuss/2130100/Python-easy-to-understand-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
a = []
for i in title.split(" "):
if(len(i)>2):
a.append(i.capitalize())
else:
a.append(i.lower())
return ' '.join(a) | capitalize-the-title | Python easy to understand solution | yashkumarjha | 0 | 48 | capitalize the title | 2,129 | 0.603 | Easy | 29,455 |
https://leetcode.com/problems/capitalize-the-title/discuss/2024748/Thats-How-you-do-it | class Solution:
def capitalizeTitle(self, title: str) -> str:
s=title.split(' ')
res=[]
pp=''
for i in s:
if len(i)<=2:
pp=i.lower()
elif s[0][0].islower() or s[0][0].isupper():
pp=i[0][0].upper()
pp+=i[1:].lower()
res.append(pp)
return ' '.join(res) | capitalize-the-title | Thats How you do it | mailer2021rad | 0 | 26 | capitalize the title | 2,129 | 0.603 | Easy | 29,456 |
https://leetcode.com/problems/capitalize-the-title/discuss/2013845/Python-oneliner | class Solution:
def capitalizeTitle(self, title: str) -> str:
return ' '.join([x.title() if len(x) > 2 else x.lower() for x in title.split()]) | capitalize-the-title | Python oneliner | StikS32 | 0 | 58 | capitalize the title | 2,129 | 0.603 | Easy | 29,457 |
https://leetcode.com/problems/capitalize-the-title/discuss/1940871/Python-dollarolution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.title().split()
for i in range(len(title)):
if len(title[i]) < 3:
title[i] = title[i].lower()
return ' '.join(title) | capitalize-the-title | Python $olution | AakRay | 0 | 59 | capitalize the title | 2,129 | 0.603 | Easy | 29,458 |
https://leetcode.com/problems/capitalize-the-title/discuss/1872432/Beginner-Friendly-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
tmp=[]
res=[]
title=title.split(" ")
for i in title:
res.append(i.lower())
for i in res:
if len(i)>2:
tmp.append(i[0].upper() +i[1:])
else:
tmp.append(i.lower())
return " ".join(tmp) | capitalize-the-title | Beginner Friendly Solution | sangam92 | 0 | 37 | capitalize the title | 2,129 | 0.603 | Easy | 29,459 |
https://leetcode.com/problems/capitalize-the-title/discuss/1855135/Python-easy-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
title_split = title.split()
res = ""
for i in title_split:
if len(i) <= 2:
res += i.lower() + " "
else:
res += i.capitalize() + " "
return res.strip() | capitalize-the-title | Python easy solution | alishak1999 | 0 | 45 | capitalize the title | 2,129 | 0.603 | Easy | 29,460 |
https://leetcode.com/problems/capitalize-the-title/discuss/1696763/Python3-accepted-solution | class Solution:
def capitalizeTitle(self, s: str) -> str:
ans = ""
for i in s.split():
if(len(i)<=2):
i = (i.lower())
ans = ans + i + " "
else:
i = i.capitalize()
ans = ans + i + " "
return (ans[:-1]) | capitalize-the-title | Python3 accepted solution | sreeleetcode19 | 0 | 56 | capitalize the title | 2,129 | 0.603 | Easy | 29,461 |
https://leetcode.com/problems/capitalize-the-title/discuss/1695961/Python-3-easy-solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
res = ''
for word in title.split():
if len(word) <= 2:
res += word.lower() + ' '
else:
res += word.capitalize() + ' '
return res[:-1] | capitalize-the-title | Python 3 easy solution | dereky4 | 0 | 72 | capitalize the title | 2,129 | 0.603 | Easy | 29,462 |
https://leetcode.com/problems/capitalize-the-title/discuss/1694794/Easiest-Python-one-liner-(with-list-comprehension) | class Solution:
def capitalizeTitle(self, title: str) -> str:
return " ".join([w.lower() if len(w) <= 2 else w.title() for w in title.split()]) | capitalize-the-title | Easiest Python one-liner (with list comprehension) | eisaadil | 0 | 41 | capitalize the title | 2,129 | 0.603 | Easy | 29,463 |
https://leetcode.com/problems/capitalize-the-title/discuss/1690228/Python3-Faster-Than-95.01 | class Solution:
def capitalizeTitle(self, title: str) -> str:
s = ""
for word in title.split():
if len(word) < 3:
s += word.lower() + " "
else:
word = word.lower()
s += chr(ord(word[0]) - 32) + word[1:] + " "
return s[:-1] | capitalize-the-title | Python3 Faster Than 95.01% | Hejita | 0 | 49 | capitalize the title | 2,129 | 0.603 | Easy | 29,464 |
https://leetcode.com/problems/capitalize-the-title/discuss/1686940/Python-using-Single-Pointer-oror-O(n)-Time-Complexity | class Solution:
def capitalizeTitle(self, title: str) -> str:
result=""
l=[]
for i in range(len(title)):
if(title[i]==" "):
if(len(l)>2): #If length of word is greater than 2 then make first letter upper and rest in lower
result+=l[0].upper()
for x in range(1,len(l)):
result+=l[x].lower()
result+=" "
l.clear()
else: #If word length is less or equal to 2 make all letters lower
for x in range(0,len(l)):
result+=l[x].lower()
result+=" "
l.clear()
else:
l.append(title[i])
# For the last word
if(len(l)>2):
result+=l[0].upper()
for x in range(1,len(l)):
result+=l[x].lower()
else:
for x in range(0,len(l)):
result+=l[x].lower()
return result | capitalize-the-title | Python using Single Pointer || O(n) Time Complexity | HimanshuGupta_p1 | 0 | 33 | capitalize the title | 2,129 | 0.603 | Easy | 29,465 |
https://leetcode.com/problems/capitalize-the-title/discuss/1684282/Python3-string-processing | class Solution:
def capitalizeTitle(self, title: str) -> str:
ans = []
for word in title.split():
if len(word) > 2: word = word.capitalize()
else: word = word.lower()
ans.append(word)
return " ".join(ans) | capitalize-the-title | [Python3] string processing | ye15 | 0 | 20 | capitalize the title | 2,129 | 0.603 | Easy | 29,466 |
https://leetcode.com/problems/capitalize-the-title/discuss/1680993/Python3-Simple-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
res = []
arr = title.split(" ")
for i in arr:
if len(i) < 3:
res.append(i.lower())
else:
res.append(i.capitalize())
return " ".join(res) | capitalize-the-title | [Python3] Simple Solution | abhijeetmallick29 | 0 | 20 | capitalize the title | 2,129 | 0.603 | Easy | 29,467 |
https://leetcode.com/problems/capitalize-the-title/discuss/1675616/Python-one-liner | class Solution:
def capitalizeTitle(self, title: str) -> str:
return " ".join(w.lower() if len(w) <= 2 else w[0].upper() + w[1:].lower() for w in title.split()) | capitalize-the-title | Python, one-liner | blue_sky5 | 0 | 35 | capitalize the title | 2,129 | 0.603 | Easy | 29,468 |
https://leetcode.com/problems/capitalize-the-title/discuss/1675453/Python-Easy-Solution | class Solution:
def capitalizeTitle(self, title: str) -> str:
li=title.split()
ans=[]
for i in range(0,len(li)):
if len(li[i])==1 or len(li[i])==2:
li[i]=li[i].lower()
else:
li[i]=li[i].capitalize()
return " ".join(li) | capitalize-the-title | Python Easy Solution | aryanagrawal2310 | 0 | 41 | capitalize the title | 2,129 | 0.603 | Easy | 29,469 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676025/Need-to-know-O(1)-space-solution-in-Python | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
nums = []
curr = head
while curr:
nums.append(curr.val)
curr = curr.next
N = len(nums)
res = 0
for i in range(N // 2):
res = max(res, nums[i] + nums[N - i - 1])
return res | maximum-twin-sum-of-a-linked-list | Need-to-know O(1) space solution in Python | kryuki | 16 | 1,900 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,470 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676025/Need-to-know-O(1)-space-solution-in-Python | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
def reverse(head):
prev, curr = None, head
while curr:
next_node = curr.next
curr.next = prev
prev, curr = curr, next_node
return prev
slow, fast = head, head
while fast:
slow = slow.next
fast = fast.next.next
first = head
second = reverse(slow)
max_so_far = 0
while second:
summ = first.val + second.val
max_so_far = max(max_so_far, summ)
first, second = first.next, second.next
return max_so_far | maximum-twin-sum-of-a-linked-list | Need-to-know O(1) space solution in Python | kryuki | 16 | 1,900 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,471 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676108/Python-with-VISUAL-O(1)-Space-O(n)-Time-Easy-to-Understand | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
mid = self.find_mid(head)
rev = self.reverse(mid)
max = self.get_max(head, rev, -inf)
return max
def find_mid(self, list):
slow, fast = list, list
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
def get_max(self, a, b, cur_max):
if b is None:
return cur_max
sum = a.val + b.val
if sum > cur_max:
cur_max = sum
return self.get_max(a.next, b.next, cur_max)
def reverse(self, head):
cur, prev = head, None
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
``` | maximum-twin-sum-of-a-linked-list | Python with [VISUAL] O(1) Space O(n) Time Easy to Understand | matthewlkey | 5 | 328 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,472 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2227809/Python-stack | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
slow = fast = head
stack = []
while fast:
stack.append(slow.val)
slow = slow.next
fast = fast.next.next
result = -math.inf
while slow:
result = max(result, stack.pop() + slow.val)
slow = slow.next
return result | maximum-twin-sum-of-a-linked-list | Python, stack | blue_sky5 | 4 | 92 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,473 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1984974/python-3-oror-O(n)-time-oror-O(1)-space | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
# slow == n / 2 - 1, fast == n - 1
# reverse nodes from n / 2 to n - 1
prev, cur = None, slow.next
while cur:
cur.next, cur, prev = prev, cur.next, cur
twin1, twin2 = head, prev # 0, n - 1
res = 0
while twin2:
res = max(res, twin1.val + twin2.val)
twin1, twin2 = twin1.next, twin2.next
return res | maximum-twin-sum-of-a-linked-list | python 3 || O(n) time || O(1) space | dereky4 | 2 | 207 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,474 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2574448/Python-Simple-Clean-Easy-approach-beat-95-Easy-T%3A-O(N) | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
# Getting Middle Element
dummy = head
first, second = dummy, dummy
while second.next.next:
first, second = first.next, second.next.next
second_half = first.next
# Reversing second half
first, second, third = None, None, second_half
while third:
first, second, third = second, third, third.next
second.next = first
second_half = second
# Traversing over first and second half
max_sum = float('-inf')
while second_half and head:
max_sum = max(max_sum, second_half.val + head.val)
head, second_half = head.next, second_half.next
return max_sum | maximum-twin-sum-of-a-linked-list | ✅ [ Python ] Simple, Clean, Easy approach beat 95% Easy T: O(N) | girraj_14581 | 1 | 179 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,475 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2359433/Python3-oror-Easy-solution-using-two-pointer | class Solution:
def findMid(self, head):
# Find the middle of the linked list using two-pointer approach
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def reverselist(self, head):
#Reverse the second half of the linked list
previous = None
current = head
while current:
temp = current.next
current.next = previous
previous = current
current = temp
return previous
def pairSum(self, head: Optional[ListNode]) -> int:
if not head:
return True
mid = self.findMid(head) # Find the mid of the linkedlist
reverseheadt = self.reverselist(mid.next) #Reverse the second half of the linked list
res = 0
while(reverseheadt):
res = max(res, reverseheadt.val+head.val) #Keep checking the max of twin sum
head = head.next
reverseheadt = reverseheadt.next
return res | maximum-twin-sum-of-a-linked-list | Python3 || Easy solution using two pointer | Himanshu_Gupta19 | 1 | 40 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,476 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1765647/simple-python-solution-or-96.17-time-and-94.73-space | class Solution:
#Find MiddleNode in given Linked List
def middlenode(self,ll):
slow = fast = ll
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
#Reverse the half-Linked List
def reversell(self,ll):
prev = None
cur = ll
while cur:
n = cur.next
cur.next = prev
prev = cur
cur = n
return prev
#Compute the twin sum and return the max twinsum
def pairSum(self, head: Optional[ListNode]) -> int:
reversedllist = self.middlenode(head)
newll = self.reversell(reversedllist)
max_twin = 0
while newll:
if head.val+newll.val > max_twin:
max_twin = head.val+newll.val
head = head.next
newll = newll.next
return max_twin | maximum-twin-sum-of-a-linked-list | simple python solution | 96.17% time and 94.73% space | vijayvardhan6 | 1 | 95 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,477 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1746806/Python3-RunTime%3A-1069ms-74.69-Memory%3A-54.5mb-76.64 | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
if not head:return 0
res = list()
cur = head
while cur:
res.append(cur.val)
cur = cur.next
l, r = 0, len(res)-1
maxP = 0
while l < r:
sum_ = res[l] + res[r]
maxP = max(maxP, sum_)
l+=1
r-=1
return maxP | maximum-twin-sum-of-a-linked-list | Python3 RunTime: 1069ms 74.69% Memory: 54.5mb 76.64% | arshergon | 1 | 26 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,478 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1684289/Python3-reverse-list-O(1)-space | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
prev = None
while slow: slow.next, slow, prev = prev, slow.next, slow
ans = 0
while prev:
ans = max(ans, head.val + prev.val)
head = head.next
prev = prev.next
return ans | maximum-twin-sum-of-a-linked-list | [Python3] reverse list O(1) space | ye15 | 1 | 39 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,479 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2694833/Python3-or-Two-Pointers | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
ans=0
def reverseList(head):
prev=None
temp=head
while temp:
curr=temp.next
temp.next=prev
prev=temp
temp=curr
return prev
fast,slow=head,head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
head2=slow
last=reverseList(head2)
while last:
ans=max(ans,head.val+last.val)
head=head.next
last=last.next
return ans | maximum-twin-sum-of-a-linked-list | [Python3] | Two Pointers | swapnilsingh421 | 0 | 3 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,480 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2542055/Python3-Reverse-Second-Half-of-List-or-Beats-91.30-Solutions | class Solution:
def reverse_list(self, head: Optional[ListNode]) -> int:
prev = None
curr = head
while curr is not None:
next_ = curr.next
curr.next = prev
prev = curr
curr = next_
def pairSum(self, head: Optional[ListNode]) -> int:
# reverse second half of the linked list
# formally, use a fast pointer that travels 2x the speed of
# a slow pointer; then, reverse the list from the slow pointer.
s, f = head, head
while f.next is not None:
s = s.next
f = f.next
if f.next is not None:
f = f.next
self.reverse_list(s)
tail = f
max_twin_sum = -math.inf
curr1, curr2 = head, tail
while curr1 is not None and curr2 is not None:
twin_sum = curr1.val + curr2.val
max_twin_sum = max(max_twin_sum, twin_sum)
curr1 = curr1.next
curr2 = curr2.next
return max_twin_sum | maximum-twin-sum-of-a-linked-list | Python3 Reverse Second-Half of List | Beats 91.30% Solutions | jmyanxiang | 0 | 61 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,481 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2539389/Python-or-recursion-or-O(n)-Time-or-O(1)-Space | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
self.master = head
self.max = 0
def recur(node):
if not node:
return
recur(node.next)
self.max = max(self.max, self.master.val+node.val)
self.master = self.master.next
recur(head)
return self.max | maximum-twin-sum-of-a-linked-list | Python | recursion | O(n) Time | O(1) Space | coolakash10 | 0 | 12 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,482 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2318864/Python-Solution-Using-Two-Pointers | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
slow=ListNode(0,head)
fast=head
#Finding The Mid Node of the LL
while fast and fast.next:
slow=slow.next
fast=fast.next.next
second=slow.next
#Reversing the second half of Linked List
slow.next=prev=None
while second:
temp=second.next
second.next=prev
prev=second
second=temp
first,second=head,prev
res=0
#Adding the corresponding parts of the 2 divided linked list
while first:
res=max(res,first.val+second.val)
first=first.next
second=second.next
return res | maximum-twin-sum-of-a-linked-list | Python Solution Using Two Pointers | kanishktyagi11 | 0 | 65 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,483 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2313150/Simple-python-code | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
A = []
while head != None:
A.append(head.val)
head = head.next
best = 0
n = len(A)
for i in range(n):
best = max(best,(A[i] + A[n-1-i]))
return best | maximum-twin-sum-of-a-linked-list | Simple python code | thomanani | 0 | 23 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,484 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2237391/Python3-Variation-of-Palindrome | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
# Using slow and fast pointer
slow = fast = head
while fast and fast.next:
slow =slow.next
fast = fast.next.next
# reverse the second part
prev = None
curr = slow
nextt = None
while curr:
nextt = curr.next
curr.next = prev
prev = curr
curr = nextt
slow2 = head
maxv = -inf
while prev:
maxv = max(maxv, slow2.val + prev.val)
prev = prev.next
slow2 = slow2.next
return maxv | maximum-twin-sum-of-a-linked-list | [Python3] Variation of Palindrome | Gp05 | 0 | 16 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,485 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2171997/Easy-python-solution | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
arr = []
while head:
arr.append(head.val)
head = head.next
i, n = 0, len(arr) -1
mx = 0
while i<n:
if arr[i]+arr[n] > mx:
mx = arr[i]+arr[n]
i+=1
n-=1
return mx
``` | maximum-twin-sum-of-a-linked-list | Easy python solution | viraj252 | 0 | 46 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,486 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/2076311/Easy-Python-solution-with-explanation | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
# First step : Find middle of the Linkedlist
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
#Second Step: reverse the second Linked List
prev = None
while slow:
temp = slow
slow = slow.next
temp.next = prev
prev = temp
#Step 3: add the nodes and get the max
first = head
second = prev
maxi = 0
while first and second:
maxi = max(maxi, first.val + second.val)
first = first.next
second = second.next
return maxi
``` | maximum-twin-sum-of-a-linked-list | Easy Python solution with explanation | maj3r | 0 | 41 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,487 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1902113/Python-Iterative-Solution-oror-Time-O(N)-Space-O(1) | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
"""
time: O(n)
space: O(1)
"""
if not head.next:
return head.val
if not head.next.next:
return head.val + head.next.val
# find the middle node
slow, fast = head, head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
# slow now is the head of second half
# reverse the second half
curr, prev = slow, None
while curr:
curr.next, prev, curr = prev, curr, curr.next
# add both ends
fast, slow, max_twin_sum = head, prev, float('-inf')
while slow and fast:
twin_sum = slow.val + fast.val
if twin_sum > max_twin_sum:
max_twin_sum = twin_sum
# move along
slow, fast = slow.next, fast.next
return max_twin_sum | maximum-twin-sum-of-a-linked-list | Python Iterative Solution || Time - O(N), Space - O(1) | ChidinmaKO | 0 | 28 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,488 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1751797/Pyhton3-or-Constant-space-and-Variable-Space-Solution | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
li=[]
temp=head
max_sum= float('-inf')
while temp:
li.append(temp.val)
temp=temp.next
i,j=0,len(li)-1
while i<=j:
max_sum=max(max_sum,(li[i]+li[j]))
i+=1
j-=1
return(max_sum) | maximum-twin-sum-of-a-linked-list | Pyhton3 | Constant space and Variable Space Solution | shandilayasujay | 0 | 57 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,489 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1751797/Pyhton3-or-Constant-space-and-Variable-Space-Solution | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
def findMiddle(head: Optional[ListNode]):
slow=head
fast=head.next
while fast and fast.next:
slow=slow.next
fast=fast.next.next
return slow
def reverseList(head: Optional[ListNode] ):
prev_node=None
next_node=None
cur_node=head
while cur_node:
next_node=cur_node.next
cur_node.next=prev_node
prev_node=cur_node
cur_node=next_node
return prev_node
middle=findMiddle(head)
middle.next=reverseList(middle.next)
temp=middle.next
temp2=head
max_sum=float('-inf')
while temp:
max_sum=max(max_sum, (temp.val+temp2.val))
temp=temp.next
temp2=temp2.next
return max_sum | maximum-twin-sum-of-a-linked-list | Pyhton3 | Constant space and Variable Space Solution | shandilayasujay | 0 | 57 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,490 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1685318/python-recursion-one-pass-O(n) | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
def recur(head, i):
#corner case
if not head.next:
return 0, head, 0
count, node, res = recur(head.next, i+1)
# first half
if i<= count:
res = max(res, node.val+head.val)
return count+1, node.next, res
# second half
else:
return count+1, head, res
return recur(head,0)[2] | maximum-twin-sum-of-a-linked-list | python recursion one pass O(n) | chichi_x | 0 | 41 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,491 |
https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676379/Python3-O(1)-Space-(Beats-100)-or-O(n)-Time | class Solution:
def _findMid(self, head):
prev = None
fast = slow = head
while fast and fast.next:
prev, slow, fast = slow, slow.next, fast.next.next
if prev: prev.next = None
return slow
def _revList(self, head):
prev = None
while head:
head.next, prev, head = prev, head, head.next
return prev
def pairSum(self, head: Optional[ListNode]) -> int:
# Find 2nd middle node
mid = self._findMid(head)
#Reverse list from mid
tail = self._revList(mid)
mx = 0
while head:
mx = max(mx, head.val + tail.val)
head, tail = head.next, tail.next
return mx | maximum-twin-sum-of-a-linked-list | ✅ [Python3] O(1) Space (Beats 100%) | O(n) Time | PatrickOweijane | 0 | 45 | maximum twin sum of a linked list | 2,130 | 0.814 | Medium | 29,492 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772128/using-dictnory-in-TCN | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
dc=defaultdict(lambda:0)
for a in words:
dc[a]+=1
count=0
palindromswords=0
inmiddle=0
wds=set(words)
for a in wds:
if(a==a[::-1]):
if(dc[a]%2==1):
inmiddle=1
palindromswords+=(dc[a]//2)*2
elif(dc[a[::-1]]>0):
count+=(2*(min(dc[a],dc[a[::-1]])))
dc[a]=0
return (palindromswords+count+inmiddle)*2
`` | longest-palindrome-by-concatenating-two-letter-words | using dictnory in TC=N | droj | 5 | 349 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,493 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772455/Python-Simple-and-Easy-Way-to-Solve-with-Explanation-or-97-Faster | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
lookup = Counter(words)
p_len = 0
mid = 0
for word in lookup.keys():
if word[0] == word[1]:
if lookup[word]%2 == 0:
p_len += lookup[word]
else:
p_len += lookup[word]-1
mid = 1
elif word[::-1] in lookup:
p_len += min(lookup[word], lookup[word[::-1]])
return (p_len + mid) * 2 | longest-palindrome-by-concatenating-two-letter-words | ✔️ Python Simple and Easy Way to Solve with Explanation | 97% Faster 🔥 | pniraj657 | 3 | 253 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,494 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2775048/Python3-Solution-with-using-hashmap | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
c = collections.Counter(words)
res = 0
mid = 0
for key in c:
mirror = key[::-1]
if key == mirror:
res += 2 * (c[key] // 2)
mid |= c[key] % 2
else:
if c[mirror] != 0:
res += min(c[key], c[mirror])
return res * 2 + (2 if mid else 0) | longest-palindrome-by-concatenating-two-letter-words | [Python3] Solution with using hashmap | maosipov11 | 1 | 21 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,495 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773265/Simple-Solution-with-Dict | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
d = defaultdict(int)
ans = f = 0
for w in words:
d[w] += 1
for k, v in d.items():
x,y = k
if x == y:
if v&1 and not f: f = 2
ans += 2*(v//2)
elif y+x in d:
ans += min(d[k], d[y+x])
return 2*ans+f | longest-palindrome-by-concatenating-two-letter-words | Simple Solution with Dict | Mencibi | 1 | 6 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,496 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772663/Easy-python-solution | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
### count the frequency of each word in words
counter = Counter(words)
### initialize res and mid.
### mid represent if result is in case1 (mid=1) or case2 (mid=0)
res = mid = 0
for word in counter.keys():
if word[0]==word[1]:
### increase the result by the word frequency
res += counter[word] if counter[word]%2==0 else counter[word]-1
### set mid to 1 if frequency is odd (using bit-wise OR to make it short)
mid |= counter[word]%2
elif word[::-1] in counter:
### increase the result by the minimum frequency of the word and its reverse
### we do not do *2 because we will see its reverse later
res += min(counter[word],counter[word[::-1]])
### since we only count the frequency of the selected word
### times 2 to get the length of the palindrome
return (res + mid) * 2 | longest-palindrome-by-concatenating-two-letter-words | Easy python solution | avs-abhishek123 | 1 | 76 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,497 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2260110/Python3-oror-96-Faster-O(n)-Intuitive-Sol.-oror-Explained | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
m = {}
for c in words:
if c not in m: m[c] = 0
m[c] += 1
single = False
res = 0
for c in m:
if c == c[::-1]:
if m[c] == 1 and not single:
res += 2
single = True
else:
if m[c] % 2:
if not single:
res += (m[c])*2
single = True
else:
res += (m[c]-1)*2
else:
res += (m[c])*2
m[c] = 0
elif c[::-1] in m:
res += (min(m[c], m[c[::-1]]))*4
m[c] = 0
m[c[::-1]] = 0
return res | longest-palindrome-by-concatenating-two-letter-words | Python3 || 96% Faster O(n) Intuitive Sol. || Explained | Dewang_Patil | 1 | 214 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,498 |
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/1675436/Simple-PythonO(n)-with-explanation | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
length = 0
duplicate = 0
pali = dict()
for word in words:
# keep track on the number of the word with duplicated alphabet
if word[0] == word[1]:
duplicate += 1
if word in pali:
length += 4
pali[word] -= 1
if pali[word] == 0:
del pali[word]
if word[0] == word[1]:
duplicate -= 2
else:
# re stands for the reversed word
re = word[1] + word[0]
if re in pali:
pali[re] += 1
else:
pali[re] = 1
if duplicate > 0:
length += 2
return length | longest-palindrome-by-concatenating-two-letter-words | Simple Python|O(n) with explanation | gg21aping | 1 | 114 | longest palindrome by concatenating two letter words | 2,131 | 0.491 | Medium | 29,499 |
Subsets and Splits