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-closest-number-to-zero/discuss/2192384/Python-Solution-2-solutions | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
res=[abs(ele) for ele in nums]
a=(min(res))
if a in nums:
return a
else:
return a*-1 | find-closest-number-to-zero | Python Solution 2 solutions | SakshiMore22 | 1 | 88 | find closest number to zero | 2,239 | 0.458 | Easy | 31,000 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1954191/O(n-)-time-and-O(1)-space-complexity-easy-solution | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
closest = 0
if 0 in nums:
return 0
for i in range(len(nums)):
if closest == 0 :
closest = nums[i]
elif nums[i] > 0 and nums[i] <= abs(closest):
closest = nums[i]
elif nums[i] < 0 and nums[i] < abs(closest) and abs(nums[i]) < abs(closest):
closest = nums[i]
return closest
``` | find-closest-number-to-zero | O(n ) time and O(1) space complexity easy solution | onefleabag | 1 | 40 | find closest number to zero | 2,239 | 0.458 | Easy | 31,001 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1953746/Python-3-(150ms)-or-Dictionary-Solution-O(n)-and-O(n) | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
d={}
for i in range(len(nums)):
if abs(nums[i]) in d:
d[abs(nums[i])]=max(d[abs(nums[i])],nums[i])
else:
d[abs(nums[i])]=nums[i]
return d[min(d.keys())] | find-closest-number-to-zero | Python 3 (150ms) | Dictionary Solution O(n) & O(n) | MrShobhit | 1 | 104 | find closest number to zero | 2,239 | 0.458 | Easy | 31,002 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2844511/Using-reduce | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
def fn(a, b):
if abs(a) < abs(b):
return a
elif abs(a) == abs(b):
return max(a, b)
else:
return b
return reduce(fn, nums) | find-closest-number-to-zero | Using reduce | Mik-100 | 0 | 1 | find closest number to zero | 2,239 | 0.458 | Easy | 31,003 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2672778/Two-Approaches-or-Easy-to-Understand-or-Python | class Solution(object):
def findClosestNumber(self, nums):
diff, ans = 0, 0
for i in range(len(nums)):
if i == 0:
diff = abs(nums[i] - 0)
ans = nums[i]
else:
if diff > abs(nums[i] - 0):
diff, ans = abs(nums[i] - 0), nums[i]
if diff == abs(nums[i] - 0) and ans < nums[i]:
ans = nums[i]
return ans | find-closest-number-to-zero | Two Approaches | Easy to Understand | Python | its_krish_here | 0 | 35 | find closest number to zero | 2,239 | 0.458 | Easy | 31,004 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2672778/Two-Approaches-or-Easy-to-Understand-or-Python | class Solution(object):
def findClosestNumber(self, nums):
nums.sort()
neg, pos, max_, min_ = False, False, 0, 0
for n in nums:
if 0 > n:
neg = True
max_ = n
else:
pos = True
min_ = n
break
if pos and neg:
if (max_ + min_) == 0: return min_
else: return max_ if abs(max_) < min_ else min_
return max_ if neg else min_ | find-closest-number-to-zero | Two Approaches | Easy to Understand | Python | its_krish_here | 0 | 35 | find closest number to zero | 2,239 | 0.458 | Easy | 31,005 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2640763/100-EASY-TO-UNDERSTANDSIMPLECLEAN | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
smallest = 0
for i in nums:
if abs(i) == 0:
return 0
elif smallest == 0 or abs(i) < abs(smallest):
smallest = i
elif abs(i) == abs(smallest):
if i > smallest:
smallest = i
return smallest | find-closest-number-to-zero | 🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥 | YuviGill | 0 | 72 | find closest number to zero | 2,239 | 0.458 | Easy | 31,006 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2547678/Pythone-One-Liner-(reduce) | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
return reduce(lambda a,b : max(a,b) if abs(a) == abs(b) else a if abs(a) < abs(b) else b, nums) | find-closest-number-to-zero | Pythone One Liner (reduce) | Norelaxation | 0 | 58 | find closest number to zero | 2,239 | 0.458 | Easy | 31,007 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2402377/Easy-and-Clear-python-3-solution | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
close=nums[0]
for r in range(1,len(nums)):
if abs(nums[r])<abs(close):
close=nums[r]
if abs(nums[r])==abs(close) and nums[r]>0:
close=nums[r]
return close | find-closest-number-to-zero | Easy and Clear python 3 solution | moazmar | 0 | 99 | find closest number to zero | 2,239 | 0.458 | Easy | 31,008 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2380632/Minimum-absolute-value-Python | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
d = 100001
ans= -100001
for i in nums:
x=abs(i)
if x==0:
return 0
elif x<d:
d=x
ans=i
elif x==d:
if i>ans:
ans=i
return ans | find-closest-number-to-zero | Minimum absolute value [Python] | sunakshi132 | 0 | 72 | find closest number to zero | 2,239 | 0.458 | Easy | 31,009 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2323192/JavaC%2B%2BPythonJavaScriptKotlin1LINE-O(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022 | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
m = 10 ** 6
for i in nums:
x = abs(i-0)
if x < m:
m = x
val = i
elif x == m and val < i:
val = i
return val | find-closest-number-to-zero | [Java/C++/Python/JavaScript/Kotlin]1LINE O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022 | cucerdariancatalin | 0 | 72 | find closest number to zero | 2,239 | 0.458 | Easy | 31,010 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2276448/Python-Simple-Python-Solution-By-Checking-Distance | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
number = 1000000
distance = 1000000
for i in nums:
current_distance = abs(i)
if current_distance <= distance:
if abs(i) == abs(number):
number = max(i,number)
elif abs(i) < abs(number):
number = i
distance = current_distance
return number | find-closest-number-to-zero | [ Python ] ✅✅ Simple Python Solution By Checking Distance 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 131 | find closest number to zero | 2,239 | 0.458 | Easy | 31,011 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2120140/Python-oror-Easy-Approach | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
nums_min = nums[0]
ans = nums[0]
for x in nums:
if abs(nums_min) > abs(x):
nums_min = abs(x)
ans = x
elif abs(nums_min) == abs(x):
if ans < x:
ans = x
return ans | find-closest-number-to-zero | ✅Python || Easy Approach | chuhonghao01 | 0 | 52 | find closest number to zero | 2,239 | 0.458 | Easy | 31,012 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2085013/Python-or-Very-Easy-and-simple-89-faster | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
min_ = nums[0]
for num in nums:
if abs(num) == abs(min_):
min_ = max(min_,num)
elif abs(num) < abs(min_):
min_ = num
return min_ | find-closest-number-to-zero | Python | Very Easy and simple 89% faster | __Asrar | 0 | 78 | find closest number to zero | 2,239 | 0.458 | Easy | 31,013 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/2038683/Python-simple-solution | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans = 10**5+1
for i in range(len(nums)):
if abs(nums[i]) == abs(ans):
ans = max(nums[i], ans)
if abs(nums[i]) < abs(ans):
ans = nums[i]
return ans | find-closest-number-to-zero | Python simple solution | StikS32 | 0 | 88 | find closest number to zero | 2,239 | 0.458 | Easy | 31,014 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1984803/Python-Solution-%2B-One-Liner-(x2)! | class Solution:
def findClosestNumber(self, nums):
distances = {k:abs(k) for k in nums}
shortest_distance = min(distances.values())
shortest_distances = [k for k,v in distances.items() if v == shortest_distance]
return max(shortest_distances) | find-closest-number-to-zero | Python - Solution + One-Liner (x2)! | domthedeveloper | 0 | 86 | find closest number to zero | 2,239 | 0.458 | Easy | 31,015 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1984803/Python-Solution-%2B-One-Liner-(x2)! | class Solution:
def findClosestNumber(self, nums):
return min(nums, key=lambda x: (abs(x), -x)) | find-closest-number-to-zero | Python - Solution + One-Liner (x2)! | domthedeveloper | 0 | 86 | find closest number to zero | 2,239 | 0.458 | Easy | 31,016 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1984803/Python-Solution-%2B-One-Liner-(x2)! | class Solution:
def findClosestNumber(self, nums):
return max(nums, key=lambda x: (-abs(x), x)) | find-closest-number-to-zero | Python - Solution + One-Liner (x2)! | domthedeveloper | 0 | 86 | find closest number to zero | 2,239 | 0.458 | Easy | 31,017 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1962772/Python-easy-solution-for-beginners | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
diff = -1
res = []
for i in sorted(nums):
if diff == -1 or abs(i) <= diff:
diff = abs(i)
res.append(i)
return max(res) | find-closest-number-to-zero | Python easy solution for beginners | alishak1999 | 0 | 128 | find closest number to zero | 2,239 | 0.458 | Easy | 31,018 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1957556/java-python-simple-easy-small-and-fast | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
neg = -100001
pos = 100001
for i in range (len(nums)) :
if nums[i] == 0 : return 0
if nums[i] < 0 :
if nums[i] > neg : neg = nums[i]
elif nums[i] < pos : pos = nums[i]
if -neg < pos : return neg
return pos | find-closest-number-to-zero | java, python - simple, easy, small & fast | ZX007java | 0 | 61 | find closest number to zero | 2,239 | 0.458 | Easy | 31,019 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1954911/Python-Fastest-Solution-Faster-Than-100-Easy-To-Understand-With-Comments | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
# init the min with the first element
mn = nums[0]
for i in nums[1:]:
# if the current element smaller in term of abs value update mn
if abs(i) < abs(mn):
mn = i
# if they are equal in term of abs value, do compare them without abs
elif abs(i) == abs(mn):
if i > mn:
mn = i
return mn | find-closest-number-to-zero | Python Fastest Solution, Faster Than 100%, Easy To Understand With Comments | Hejita | 0 | 58 | find closest number to zero | 2,239 | 0.458 | Easy | 31,020 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1954134/2-Lines-Python-Solution-oror-100-Faster-oror-Memory-less-than-90 | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
nums.sort() ; idx=bisect_left(nums,0,0,len(nums)-1)
return nums[idx-1] if abs(nums[idx-1])<nums[idx] else nums[idx] | find-closest-number-to-zero | 2-Lines Python Solution || 100% Faster || Memory less than 90% | Taha-C | 0 | 52 | find closest number to zero | 2,239 | 0.458 | Easy | 31,021 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1954123/Python3-or-Simple-Approach | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans = float("-inf")
distance = float("inf")
for num in nums:
if distance > abs(num):
ans = num
distance = abs(num)
elif distance == abs(num):
if ans < num:
ans = num
return ans | find-closest-number-to-zero | Python3 | Simple Approach | goyaljatin9856 | 0 | 22 | find closest number to zero | 2,239 | 0.458 | Easy | 31,022 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1954068/Python-simple-easy-solution-oror-170-ms | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
mini=float('inf')
nums.sort()
x=0
for i in nums:
if abs(i-0)<=mini:
mini=abs(i-0)
x=i
return x | find-closest-number-to-zero | Python simple easy solution || 170 ms | Aniket_liar07 | 0 | 50 | find closest number to zero | 2,239 | 0.458 | Easy | 31,023 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1953932/Python-easy-sort-O(n-log-n)-time-O(n)-space | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
vals = [(abs(num), num) for num in nums]
vals.sort(key = lambda x: [x[0], -x[1]])
return vals[0][1] | find-closest-number-to-zero | [Python] easy sort, O(n log n) time, O(n) space | emersonexus | 0 | 60 | find closest number to zero | 2,239 | 0.458 | Easy | 31,024 |
https://leetcode.com/problems/find-closest-number-to-zero/discuss/1953885/Python | class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
result = nums[0]
for n in nums:
if abs(n) < abs(result):
result = n
elif n == -result and n > 0:
result = n
return result | find-closest-number-to-zero | Python | blue_sky5 | 0 | 63 | find closest number to zero | 2,239 | 0.458 | Easy | 31,025 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1962778/Python-easy-solution-faster-than-90 | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
if total < cost1 and total < cost2:
return 1
ways = 0
if cost1 > cost2:
for i in range(0, (total // cost1)+1):
rem = total - (i * cost1)
ways += (rem // cost2) + 1
return ways
for i in range(0, (total // cost2)+1):
rem = total - (i * cost2)
ways += (rem // cost1) + 1
return ways | number-of-ways-to-buy-pens-and-pencils | Python easy solution faster than 90% | alishak1999 | 2 | 84 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,026 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1953957/python-easy-O(budget-max(cost1-cost2))-time-O(1)-space | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
result = 0
budget = total
cost1, cost2 = sorted([cost1, cost2], reverse = True)
for i in range((budget // cost1) + 1):
budget = total
budget -= (i * cost1)
j = max(budget // cost2, 0)
result += j + 1
return result | number-of-ways-to-buy-pens-and-pencils | [python] easy, O(budget // max(cost1, cost2)) time, O(1) space | emersonexus | 1 | 60 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,027 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/2340070/Python-simple-math | class Solution:
def waysToBuyPensPencils(self, t: int, m: int, n: int) -> int:
a = t // m
res = 0
for x in range(0, a + 1):
res += 1 + (t-m*x)//n
return res | number-of-ways-to-buy-pens-and-pencils | Python simple math | byuns9334 | 0 | 32 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,028 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/2244260/2-line-mathematic-solution-in-Python-O(total-max(cost1-cost2)) | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
c, C = sorted((cost1, cost2))
return sum((total - i * C) // c + 1 for i in range(total // C + 1)) | number-of-ways-to-buy-pens-and-pencils | 2-line mathematic solution in Python, O(total // max(cost1, cost2)) | mousun224 | 0 | 45 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,029 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/2244260/2-line-mathematic-solution-in-Python-O(total-max(cost1-cost2)) | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
if cost1 < cost2:
cost1, cost2 = cost2, cost1
ans = 0
for i in range(total // cost1 + 1):
for _ in range((total - i * cost1) // cost2 + 1):
ans += 1
return ans | number-of-ways-to-buy-pens-and-pencils | 2-line mathematic solution in Python, O(total // max(cost1, cost2)) | mousun224 | 0 | 45 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,030 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/2120135/Python-oror-Easy-Approach | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
num1 = int(total / cost1) + 1
num2 = [0] * num1
ans = 0
for i in range(0, num1, 1):
num2[i] =int((total-cost1 * i) / cost2) + 1
ans = sum(num2)
return ans | number-of-ways-to-buy-pens-and-pencils | ✅Python || Easy Approach | chuhonghao01 | 0 | 43 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,031 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1979924/python-3-oror-one-line-oror-O(n) | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
return sum((total - pens*cost1) // cost2 + 1 for pens in range(total // cost1 + 1)) | number-of-ways-to-buy-pens-and-pencils | python 3 || one line || O(n) | dereky4 | 0 | 97 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,032 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1954186/3-Lines-Python-Solution-oror-100-Faster-oror-Memory-less-than-50 | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
ans=0
for i in range(1+total//cost1): ans+=1+max(total-i*cost1,0)//cost2
return ans | number-of-ways-to-buy-pens-and-pencils | 3-Lines Python Solution || 100% Faster || Memory less than 50% | Taha-C | 0 | 18 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,033 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1953884/Python3-naive-approach | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
if cost1 < cost2:
return self.waysToBuyPensPencils(total, cost2, cost1)
result = total // cost1 + total // cost2 + 1
number_of_cost1 = 1
while number_of_cost1 * cost1 < total:
amount = total - number_of_cost1 * cost1
result += amount // cost2
number_of_cost1 += 1
return result | number-of-ways-to-buy-pens-and-pencils | Python3 naive approach | AlphaMonkey9 | 0 | 13 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,034 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1953803/Python-3-(900ms)-or-Simple-Maths-OP-or-5-Lines-Solution | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
i=0
ans=0
while total>=(i*cost1):
t=total-(i*cost1)
ans+=(t//cost2)+1
i+=1
return ans | number-of-ways-to-buy-pens-and-pencils | Python 3 (900ms) | Simple Maths OP | 5 Lines Solution | MrShobhit | 0 | 38 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,035 |
https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1953792/Python3-Solution-or-O(n) | class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
p = total // cost1
ways = 0
for i in range(p + 1):
t = total - i * cost1
ways += (t // cost2) + 1
return ways | number-of-ways-to-buy-pens-and-pencils | ✅ Python3 Solution | O(n) | chetankalra11 | 0 | 23 | number of ways to buy pens and pencils | 2,240 | 0.57 | Medium | 31,036 |
https://leetcode.com/problems/maximum-score-of-a-node-sequence/discuss/1984916/Python3-O(orEor)-solution | class Solution:
def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:
connection = {}
for source, target in edges:
if source not in connection: connection[source] = [target]
else: connection[source].append(target)
if target not in connection: connection[target] = [source]
else: connection[target].append(source)
res = -1
max_dict = {}
for key, value in connection.items():
max1, max2, max3 = -sys.maxsize, -sys.maxsize, -sys.maxsize
n1, n2, n3 = None, None, None
for element in value:
if scores[element] > max1:
max1, max2, max3 = scores[element], max1, max2
n1, n2, n3 = element, n1, n2
elif scores[element] > max2:
max2, max3 = scores[element], max2
n2, n3 = element, n2
elif scores[element] > max3:
max3 = scores[element]
n3 = element
max_dict[key] = []
if n1 != None: max_dict[key].append(n1)
if n2 != None: max_dict[key].append(n2)
if n3 != None: max_dict[key].append(n3)
for source, target in edges:
base = scores[source] + scores[target]
n_s = max_dict[source]
n_t = max_dict[target]
if len(n_s) == 1 or len(n_t) == 1:
pass
else:
new_n_s = [x for x in n_s if x != target]
new_n_t = [x for x in n_t if x != source]
if new_n_s[0] != new_n_t[0]:
res = max(res, base + scores[new_n_s[0]] + scores[new_n_t[0]])
else:
if len(new_n_s) > 1:
res = max(res, base + scores[new_n_s[1]] + scores[new_n_t[0]])
if len(new_n_t) > 1:
res = max(res, base + scores[new_n_s[0]] + scores[new_n_t[1]])
return res | maximum-score-of-a-node-sequence | Python3 O(|E|) solution | xxHRxx | 2 | 239 | maximum score of a node sequence | 2,242 | 0.375 | Hard | 31,037 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955460/Python3-elegant-pythonic-clean-and-easy-to-understand | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
set_3 = [s[i:i+k] for i in range(0, len(s), k)]
s = ''
for e in set_3:
val = 0
for n in e:
val += int(n)
s += str(val)
return s | calculate-digit-sum-of-a-string | Python3 elegant pythonic clean and easy to understand | Tallicia | 10 | 881 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,038 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955344/Simple-Python-Solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
def divideString(s: str, k: int) -> List[str]: # Utility function to return list of divided groups.
l, n = [], len(s)
for i in range(0, n, k):
l.append(s[i:min(i + k, n)])
return l
while len(s)>k: # Till size of s is greater than k
arr, temp = divideString(s, k), [] # arr is the list of divided groups, temp will be the list of group sums
for group in arr: # Traverse the group and add its digits
group_sum = 0
for digit in group:
group_sum += int(digit)
temp.append(str(group_sum)) # Sum of digits of current group
s = ''.join(temp) # s is replaced by the group digit sum for each group.
return s | calculate-digit-sum-of-a-string | Simple Python Solution | anCoderr | 5 | 629 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,039 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2425989/Python-Elegant-and-Short-or-Pythonic-or-Iterative-%2B-Recursive | class Solution:
def digitSum(self, s: str, k: int) -> str:
"""Iterative version"""
while len(s) > k:
s = self.round(s, k)
return s
def digitSum(self, s: str, k: int) -> str:
"""Recursive version"""
if len(s) <= k:
return s
return self.digitSum(self.round(s, k), k)
@classmethod
def round(cls, s: str, k: int) -> str:
return ''.join(map(cls.add_digits, cls.slice(s, k)))
@staticmethod
def add_digits(s: str) -> str:
return str(sum(int(d) for d in s))
@staticmethod
def slice(s: str, k: int):
for i in range(0, len(s), k):
yield s[i:i + k] | calculate-digit-sum-of-a-string | Python Elegant & Short | Pythonic | Iterative + Recursive | Kyrylo-Ktl | 2 | 96 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,040 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1988068/Python-easy-iterative-solution-for-beginners | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
groups = [s[x:x+k] for x in range(0, len(s), k)]
temp = ""
for i in groups:
dig = [int(y) for y in i]
temp += str(sum(dig))
s = temp
return s | calculate-digit-sum-of-a-string | Python easy iterative solution for beginners | alishak1999 | 2 | 127 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,041 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2572453/Python-simple-solution-both-recursive-and-iterative | class Solution:
def digitSum(self, s: str, k: int) -> str:
def str_sum(s):
return str(sum([int(i) for i in s]))
if len(s) <= k:
return s
tmp = []
for i in range(0, len(s), k):
tmp.append(str_sum(s[i:i + k]))
s = ''.join(tmp)
return self.digitSum(s, k) | calculate-digit-sum-of-a-string | Python simple solution both recursive and iterative | Mark_computer | 1 | 19 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,042 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2572453/Python-simple-solution-both-recursive-and-iterative | class Solution:
def digitSum(self, s: str, k: int) -> str:
def str_sum(s):
return str(sum([int(i) for i in s]))
while len(s) > k:
tmp = []
for i in range(0, len(s), k):
tmp.append(str_sum(s[i:i + k]))
s = ''.join(tmp)
return s | calculate-digit-sum-of-a-string | Python simple solution both recursive and iterative | Mark_computer | 1 | 19 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,043 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2328376/Python3-O(n%2Bk)-oror-O(n)-Runtime%3A-52ms-41.96-oror-Memory%3A-13.0mb-70.32 | class Solution:
# O(n+k) where n is the elements present in the string
# and k is the number of steps
# O(N) space
# Runtime: 52ms 41.96% || Memory: 13.0mb 70.32%
def digitSum(self, string: str, k: int) -> str:
if not string:
return string
stringLength = len(string)
k %= stringLength
if stringLength == k or k == 0 or k == 1:
return string
return helper(string, k)
def helper(string, k):
newStringList = list(string)
newNum = 0
tempList = list()
for i in range(0, len(newStringList), k):
newNum = sum(map(int, newStringList[i:k+i]))
tempList += list(str(newNum))
result = ''.join(tempList)
if len(result) > k:
return helper(result, k)
return result | calculate-digit-sum-of-a-string | Python3 O(n+k) || O(n) Runtime: 52ms 41.96% || Memory: 13.0mb 70.32% | arshergon | 1 | 35 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,044 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1966412/Python-or-Simple-Simulation-solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
groups = [s[i:i+k] for i in range(0, len(s), k)]
s = ""
for g in groups:
tot = sum(int(n) for n in g)
s += str(tot)
return s | calculate-digit-sum-of-a-string | [Python] | Simple Simulation solution | gregalletti | 1 | 85 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,045 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1957518/5-Lines-Python-Solution-oror-100-Faster-oror-Memory-less-than-85 | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s)>k:
tmp=''
for i in range(0,len(s),k): tmp+=str(sum([int(d) for d in s[i:i+k]]))
s=tmp
return s | calculate-digit-sum-of-a-string | 5-Lines Python Solution || 100% Faster || Memory less than 85% | Taha-C | 1 | 48 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,046 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1957518/5-Lines-Python-Solution-oror-100-Faster-oror-Memory-less-than-85 | class Solution:
def digitSum(self, s: str, k: int) -> str:
return self.digitSum(''.join(str(sum(int(d) for d in s[i:i+k])) for i in range(0,len(s),k)), k) if len(s) > k else s | calculate-digit-sum-of-a-string | 5-Lines Python Solution || 100% Faster || Memory less than 85% | Taha-C | 1 | 48 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,047 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2814590/Python-99-faster | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s)>k:
r=[]
x=0
while x+k < len(s):
r+=[s[x:x+k]]
x+=k
r+=[s[x:]]
print(r)
for i in range(len(r)):
r[i]=sum(list(map(int,r[i])))
print(r)
s=''.join(map(str,r))
return s | calculate-digit-sum-of-a-string | Python 99% faster | sarvajnya_18 | 0 | 1 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,048 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2791294/62-faster-Python-code-easily-understandable. | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s)>k:
s2 = ""
for i in range(0,len(s),k):
j = 0
count = 0
s1 = s[i:i+k]
while j < min(k,len(s1)):
count += int(s1[j])
j += 1
s2 += str(count)
s = s2
return s | calculate-digit-sum-of-a-string | 62% faster Python code easily understandable. | sudharshan1706 | 0 | 1 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,049 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2739036/Python-98-Faster | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
string = ''
currentSum = 0
count = 0
res = ''
for num in s:
currentSum += int(num)
string += num # string variable will be useful while calculating left over numbers.
count += 1
if count == k: #reset everything and transfer the currentSum to res.
res += str(currentSum)
currentSum = 0
string = ''
count = 0
# Add the numbers which are outside the K boundary
if len(string):
s = res + str(currentSum)
else:
s = res
return s | calculate-digit-sum-of-a-string | Python 98% Faster | theReal007 | 0 | 3 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,050 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2727571/Easy-python-solution-with-explanation-using-comments | class Solution:
def digitSum(self, s: str, k: int) -> str:
# Initially to check the length of the string. As mentioned in criteria if its more then proceed with the process
if len(s)>k:
op=[]
i=0
# Loop to make consecutive groups based on the input
while i < len(s)-k:
op.append(s[i:i+k])
i+=k
# To append remaining characters after grouping
op.append(s[i:])
fl_op=''
# To calculate sum of each group
for i in op:
sm=0
for j in i:
sm+=int(j)
fl_op+=str(sm)
# After round 1 if still length of the string is more go for round2
if len(fl_op)>k:
return self.digitSum(fl_op,k)
# After round 1 if length of the string is less than the input no then return it
else:
return fl_op
# Return input string as is length of string is already less than the input
return s | calculate-digit-sum-of-a-string | Easy python solution with explanation using comments | BAparna97 | 0 | 1 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,051 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2583413/Python-Easy-and-readable-solution-without-slicing | class Solution:
def digitSum(self, s: str, k: int) -> str:
# stop condition
while len(s) > k:
# initialize the sum for k digits
summed = 0
# initialize temporal string
tmp = ""
# save the string length
s_length = len(s) - 1
# iterate through all characters
for idx, ch in enumerate(s):
# add the current number
summed += int(ch)
# save and reset the sum
if idx % k == k-1 or idx == s_length:
tmp += str(summed)
summed = 0
# overwrite s
s = tmp
return s | calculate-digit-sum-of-a-string | [Python] - Easy and readable solution without slicing | Lucew | 0 | 22 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,052 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2544276/Python-Simple-Python-Solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
def TotalSum(num):
s = 0
for i in num:
s = s + int(i)
return s
while len(s) > k:
current_number = ''
for i in range(0,len(s),k):
current_number = current_number + str(TotalSum(s[i : i + k]))
s = current_number
return s | calculate-digit-sum-of-a-string | [ Python ] ✅✅ Simple Python Solution 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 24 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,053 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2320795/easiest-python-solution | class Solution:
def sum_of_digit(self, num) :
ans = 0
for n in num :
ans += int(n)
return ans
def digitSum(self, s: str, k: int) -> str:
while len(s) > k :
num_list = []
num = ""
for i in range(len(s)) :
num += s[i]
if len(num) == k :
num_list.append(num)
num = ""
if num != "" :
num_list.append(num)
# print(num_list)
s = ""
for num in num_list :
s += str(self.sum_of_digit(num))
# print(s)
return s | calculate-digit-sum-of-a-string | easiest python solution | sghorai | 0 | 25 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,054 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2308707/Python3-solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
def sumofdigits(N):
t = 0
while N > 0:
t = t + (N % 10)
N = N // 10
return str(t)
while len(s) > k:
s = "".join([sumofdigits(int(s[i : i + k])) for i in range(0, len(s), k)])
return s | calculate-digit-sum-of-a-string | Python3 solution | mediocre-coder | 0 | 24 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,055 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2217963/Python-simple-solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
def spl_k(s, k):
tmp = s
arr = []
for i in range(len(s)//k+1):
arr += [tmp[:k]]
tmp = tmp[k:]
return arr
while len(s) > k:
s = ''.join([str(sum(map(int,list(x)))) for x in spl_k(s, k) if x])
return s | calculate-digit-sum-of-a-string | Python simple solution | StikS32 | 0 | 74 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,056 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/2116213/Python-Easy-to-understand-Solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
l = len(s)
n = int(l/k)
r = l - n * k
list_s = list(s)
list_int = list(map(int, list_s))
s_string= s
while l > k:
list_s = list(s_string)
list_int = list(map(int, list_s))
list_divid = [0] * (n + 1)
for i in range(0, n, 1):
list_divid[i] = sum((list_int[(i * k):((i+1) * k )]))
if r == 0:
list_divid.pop()
elif r != 0:
list_divid[n] = sum(list_int[(n * k):])
s_string = ''.join([str(x) for x in list_divid])
l = len(s_string)
n = int(l/k)
r = l - n * k
return s_string | calculate-digit-sum-of-a-string | ✅Python Easy-to-understand Solution | chuhonghao01 | 0 | 34 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,057 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1973597/Python-Simple-Solution-Faster-Than-90 | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
s_new = ""
for i in range(0, len(s), k):
s_new += str(sum([int(j) for j in s[i : i + k]]))
s = s_new
return s | calculate-digit-sum-of-a-string | Python Simple Solution, Faster Than 90% | Hejita | 0 | 74 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,058 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1968105/Python3-simulation | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
s = "".join(str(sum(map(int, s[i:i+k]))) for i in range(0, len(s), k))
return s | calculate-digit-sum-of-a-string | [Python3] simulation | ye15 | 0 | 33 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,059 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1967324/python-3-oror-iterative-simulation | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
newS = ''
for i in range(0, len(s), k):
groupSum = 0
for j in range(i, min(len(s), i + k)):
groupSum += int(s[j])
newS += str(groupSum)
s = newS
return s | calculate-digit-sum-of-a-string | python 3 || iterative simulation | dereky4 | 0 | 43 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,060 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1963607/java-python-strightward-solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k :
temp = ''
i = 0
while i != len(s) :
num = 0
lim = min(len(s), i + k)
while i != lim :
num += int(s[i])
i += 1
temp += str(num)
s = temp
return s; | calculate-digit-sum-of-a-string | java, python - strightward solution | ZX007java | 0 | 44 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,061 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1962120/Python-dollarolution | class Solution:
def digitSum(self, s: str, k: int) -> str:
r, i, count = '', 1, int(s[0])
while len(s) > k:
if i % k == 0 and i < len(s):
r += str(count)
count = int(s[i])
elif i > len(s)-1:
r += str(count)
s, r, i = r, '', 0
count = int(s[i])
else:
count += int(s[i])
i += 1
return s | calculate-digit-sum-of-a-string | Python $olution | AakRay | 0 | 29 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,062 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1960882/Python-4-lines-recursive | class Solution:
def digitSum(self, s: str, k: int) -> str:
nums = [s[i:i+k] for i in range(0, len(s), k)]
nums = [sum(map(int, n)) for n in nums]
n = ''.join(map(str, nums))
return self.digitSum(n, k) if len(s) > k else s | calculate-digit-sum-of-a-string | Python 4 lines recursive | SmittyWerbenjagermanjensen | 0 | 30 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,063 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1960025/Calculate-Digit-Sum-of-a-String | class Solution:
def sums(self,st: str) -> int:
su=0
st=int(st)
while st>0:
su+=st%10
st=st//10
return su
def digitSum(self, s: str, k: int) -> str:
while len(s)>k:
l=[]
""" Storing slices of string in a list l"""
for x in range(0,len(s),k):
l.append(s[x:x+k])
sr=""
for j in l:
sr+=str(self.sums(j))
""" Taking sum of every slice and adding it to make a new string sr"""
s=sr
""" Copying sr to s """
return s
Please upvote if you find this solution helpful. | calculate-digit-sum-of-a-string | Calculate Digit Sum of a String | a_dityamishra | 0 | 40 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,064 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1958299/Python3-Simulation | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
count = 0
res = []
x = 0
for i in range(len(s)):
if count == k:
res.append(str(x))
count = 0
x = 0
count += 1
x += ord(s[i]) - 48
if x >= 0:res.append(str(x))
s = "".join(res)
return s | calculate-digit-sum-of-a-string | [Python3] Simulation | abhijeetmallick29 | 0 | 10 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,065 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1957222/Simulate-the-process-with-while-loop-100-speed | class Solution:
def digitSum(self, s: str, k: int) -> str:
len_s = len(s)
while len_s > k:
parts = []
for i in range(0, len_s, k):
if i + k <= len_s:
sum_part = sum(ord(s[j]) for j in range(i, i + k)) - 48 * k
parts.append(str(sum_part))
else:
sum_part = (sum(ord(s[j]) for j in range(i, len_s))
- 48 * (len_s - i))
parts.append(str(sum_part))
s = "".join(parts)
len_s = len(s)
return s | calculate-digit-sum-of-a-string | Simulate the process with while loop, 100% speed | EvgenySH | 0 | 16 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,066 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1957060/Python3-Easy-Understandable-Solution-or-100-beat-of-Run-time | class Solution:
def digitSum(self, s: str, k: int) -> str:
if len(s) <= k:
return s
ans = ""
while len(s) > k:
temp1 = ""
for i in range(0, len(s), k):
temp2 = 0
for j in s[i:i+k]:
temp2 += int(j)
temp1 += str(temp2)
s = temp1
ans = s
return ans | calculate-digit-sum-of-a-string | Python3 Easy Understandable Solution | 100 % beat of Run time | ArramBhaskar | 0 | 19 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,067 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1956372/Python-oror-beats-100-of-all-solution | class Solution:
def digitSum(self, s: str, k: int) -> str:
new_str = ""
while len(s) > k or len(new_str) > k:
if len(s) > k:
new_var = s[:k]
total_sum = 0
for i in new_var:
total_sum += int(i)
new_str += str(total_sum)
s = s[k:]
if len(s) <= k:
total_sum = 0
for i in s:
total_sum += int(i)
new_str += str(total_sum)
s = new_str
new_str = ""
return new_str if new_str != "" else s | calculate-digit-sum-of-a-string | Python || beats 100% of all solution | shasha7854 | 0 | 23 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,068 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955711/Python-nice-and-100-fast | class Solution:
def digitSum(self, s: str, k: int) -> str:
while len(s) > k:
s = "".join(str(sum(map(int, s[i:i+k]))) for i in range(0, len(s), k))
return s | calculate-digit-sum-of-a-string | Python, nice and 100% fast | blue_sky5 | 0 | 21 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,069 |
https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955432/Python-Simple-Solution-or-Simple-iteration | class Solution(object):
def digitSum(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
while len(s)>k:
t = ""
x = 0
a = 0
for i in range(len(s)):
if x==k:
x = 1
t+=str(a)
a = int(s[i])
else:
x+=1
a+=int(s[i])
t+=str(a)
print(t)
s = t
return s | calculate-digit-sum-of-a-string | Python Simple Solution | Simple iteration | AkashHooda | 0 | 26 | calculate digit sum of a string | 2,243 | 0.668 | Easy | 31,070 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955367/Well-Explained-Python-Solution | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
table, res = Counter(tasks), 0 # Counter to hold frequency of ith task and res stores the result.
for count in table.values():
if count <= 1: return -1 # If count <= 1 then it cannot follow the condition hence return -1.
res += ceil(count / 3) # Total number of groups increments after 3 values.
return res | minimum-rounds-to-complete-all-tasks | ⭐ Well Explained Python Solution | anCoderr | 4 | 184 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,071 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1969673/Python-easy-code-using-Hashmap | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
mp={}
# storing frequency of each element in mp
for i in tasks:
if i in mp:
mp[i]+=1
else:
mp[i]=1
cnt=0
for i in mp:
f=0
while mp[i]>3:
mp[i]-=3
f=1
cnt+=1
if mp[i]==2 or mp[i]==3:
cnt+=1
elif f==0:
return -1
else:
cnt+=1
return cnt | minimum-rounds-to-complete-all-tasks | Python easy code using Hashmap | aparnajha17 | 1 | 87 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,072 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1960040/Minimum-Rounds-to-Complete-All-Tasks | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
d=Counter(tasks)
c=0
""" If any task is present only once it cannot be completed"""
for v in d.values():
if v==1:
return -1
for k,v in d.items():
if v==2 or v==3:
c+=1
elif v>3:
c+=math.ceil(v/3)
return c
Please upvote if you find this helpful | minimum-rounds-to-complete-all-tasks | Minimum Rounds to Complete All Tasks | a_dityamishra | 1 | 23 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,073 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1957728/2-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-25 | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
C=Counter(tasks).values()
return sum([ceil(c/3) for c in C if c>1]) if 1 not in C else -1 | minimum-rounds-to-complete-all-tasks | 2-Lines Python Solution || 80% Faster || Memory less than 25% | Taha-C | 1 | 37 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,074 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955508/EZ-oror-Counter-oror-Python | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
count=Counter(tasks) ## Use Counter to get the frequency of each element
c=0 ## to store the rounds
for i in count: ## Loop through all the keys
v=count[i] ## get the value of each key
if v==1: ## if v==1 then return -1 bcoz it is not posible to complete this task
return -1
while v%3!=0: ## Complete task in batch of 2 till total value is not divisible by 3.
c+=1 ## Increase count by 1
v-=2 ## Decrease value by 2 as you are completing 2 tasks
c+=v//3 ## When come out of the loop take quotient of val//3 to get rounds
return c ## return the result | minimum-rounds-to-complete-all-tasks | EZ || Counter || Python | ashu_py22 | 1 | 16 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,075 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955312/Easy-Python3-Solution | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
res = 0
d = Counter(tasks)
for key, val in d.items():
if val==1:
return -1
if val%2==0 or val%3==0 or val%4==1 or val%4==2 or val%4==3:
if val%4==0:
res+=(val//3)
if val%3==1 or val%3==2:
res+=1
elif val%4==3:
res+=(val//3)
if val%3==1 or val%3==2:
res+=1
elif val%4==2:
res+=(val//3)
if val%3==1 or val%3==2:
res+=1
elif val%4==1:
res+=(val//3)
if val%3==2 or val%3==1:
res+=1
else:
return -1
return res | minimum-rounds-to-complete-all-tasks | Easy [Python3] Solution | ro_hit2013 | 1 | 45 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,076 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955306/Python-or-Greedy-or-Easy-to-Understand-or-With-Explanation | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
# idea: greedy
# find as many 3 as possible
counter = Counter(tasks)
steps = 0
for key, value in counter.items():
cur_step = self.composedBy(value)
if cur_step == -1:
return -1
else:
steps += cur_step
return steps
# find as many 3 as possible
# every time substract a 2 form the num and mod by 3
def composedBy(self, num):
final_step = -1
tmp_step = 0
while num > 0:
if num % 3 == 0:
final_step = num // 3 + tmp_step
return final_step
else:
num -= 2
tmp_step += 1
if num == 0:
return tmp_step
else:
return final_step | minimum-rounds-to-complete-all-tasks | Python | Greedy | Easy to Understand | With Explanation | Mikey98 | 1 | 36 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,077 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/2736514/Python3-Simple-Greedy-Approach-O(n) | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
res = 0
count = Counter(tasks) # count number of tasks per difficulty
for dif, n in count.items():
if n == 1: # not possible, can only remove 2 or 3 tasks
return -1
else: # rounds when removing 3 tasks + remainder
res += (n//3) + (1 if n%3 else 0)
return res | minimum-rounds-to-complete-all-tasks | Python3 Simple Greedy Approach O(n) | jonathanbrophy47 | 0 | 2 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,078 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/2728619/Python-simple-solution-greedy | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
c = Counter(tasks)
count = 0
for k, v in c.items():
if v == 1:
return -1
else:
count += (v // 3)
count += v % 3 != 0
return count | minimum-rounds-to-complete-all-tasks | Python simple solution - greedy | lmnvs | 0 | 3 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,079 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/2666512/Python3-just-rounding-up-is-enough | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
from collections import Counter
diff = Counter(tasks)
res = 0
for level in diff:
count = diff[level]
if count == 1:
return -1
elif count == 2:
res += 1
else:
res += math.ceil(count / 3)
return res | minimum-rounds-to-complete-all-tasks | Python3 - just rounding up is enough | user2595I | 0 | 1 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,080 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/2445447/Python3-Solution-with-using-greedy | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
c = collections.Counter(tasks)
res = 0
for cnt in c.values():
if cnt == 1:
return -1
res += (cnt + 2) // 3
return res | minimum-rounds-to-complete-all-tasks | [Python3] Solution with using greedy | maosipov11 | 0 | 15 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,081 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/2088529/Concise-Python-Code | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
c=Counter(tasks)
if 1 in c.values():
return -1
return sum([v//3 if v%3==0 else (v//3)+1 for v in c.values()]) | minimum-rounds-to-complete-all-tasks | Concise Python Code | guankiro | 0 | 32 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,082 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1968108/Python3-freq-table | class Solution:
def minimumRounds(self, nums: List[int]) -> int:
ans = 0
for v in Counter(nums).values():
if v == 1: return -1
ans += (v + 2)//3
return ans | minimum-rounds-to-complete-all-tasks | [Python3] freq table | ye15 | 0 | 19 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,083 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1967438/python-3-oror-counter-solution-oror-O(n)O(n) | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
counter = collections.Counter(tasks)
res = 0
for count in counter.values():
if count == 1:
return -1
q, r = divmod(count, 3)
res += q + (r > 0)
return res | minimum-rounds-to-complete-all-tasks | python 3 || counter solution || O(n)/O(n) | dereky4 | 0 | 49 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,084 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1963663/java-python-hashmap-(Time-On-space-On) | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
table = dict()
for t in tasks :
if t in table : table[t] += 1
else : table[t] = 1
ans = 0
for k in table :
val = table[k]
if val == 1 : return -1
ans += val // 3
if val%3 != 0 : ans += 1
return ans | minimum-rounds-to-complete-all-tasks | java, python - hashmap (Time On, space On) | ZX007java | 0 | 21 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,085 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1963267/Full-Explained-Solution-O(n) | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
mp = {}
for task in tasks:
mp[task] = mp.get(task,0) + 1
res = 0
for cnt in mp.values():
y = cnt//3
if cnt < 2:
return -1
if cnt%3!=0:
res+=(y+1)
else:
res+=y
return res | minimum-rounds-to-complete-all-tasks | Full Explained Solution O(n) | lakshy01 | 0 | 38 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,086 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1957017/Python-Solution-or-Hash-Table-or-O(n) | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
h = {}
for t in tasks:
h[t] = h.get(t, 0) + 1
r = 0
for v in h.values():
if v == 1:
return -1
if v % 3 == 0:
r += v // 3
else:
r += v // 3 + 1
return r | minimum-rounds-to-complete-all-tasks | ✅ Python Solution | Hash Table | O(n) | chetankalra11 | 0 | 18 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,087 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955418/The-absolute-cleanest-Python3-pythonic-very-simple-approach-O(n)-time-O(c)-space | class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
c = Counter(tasks)
step = 0
while any(x for x in c.values() if x is not None):
for x, i in c.items():
if i is None:
continue
if i < 2:
return -1
elif i == 2 or i == 3:
c[x] = None
step +=1
elif i == 4 or i == 5:
c[x] = None
step += 2
elif i >= 6:
c[x] -= 3
step += 1
return step | minimum-rounds-to-complete-all-tasks | The absolute cleanest Python3 pythonic very simple approach O(n) time O(c) space | Tallicia | 0 | 29 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,088 |
https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955401/Python-O(N)-Solution-or-Easy-approach-or-Greedy-method | lass Solution(object):
def minimumRounds(self, tasks):
"""
:type tasks: List[int]
:rtype: int
"""
d = {}
for i in tasks:
if i not in d:
d[i] = 1
else:
d[i]+=1
ans = 0
for i in d:
if d[i]<2:
return -1
else:
if d[i]%3==0:
ans+=d[i]//3
else:
ans += d[i]//3 +1
return ans | minimum-rounds-to-complete-all-tasks | Python O(N) Solution | Easy approach | Greedy method | AkashHooda | 0 | 14 | minimum rounds to complete all tasks | 2,244 | 0.575 | Medium | 31,089 |
https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1955502/Python-Prefix-Sum-O(m-*-n) | class Solution:
def maxTrailingZeros(self, grid: List[List[int]]) -> int:
ans = 0
m, n = len(grid), len(grid[0])
prefixH = [[[0] * 2 for _ in range(n + 1)] for __ in range(m)]
prefixV = [[[0] * 2 for _ in range(n)] for __ in range(m + 1)]
for i in range(m):
for j in range(n):
temp= grid[i][j]
while temp % 2 == 0:
prefixH[i][j + 1][0] += 1
prefixV[i + 1][j][0] += 1
temp //= 2
while temp % 5 == 0:
prefixH[i][j + 1][1] += 1
prefixV[i + 1][j][1] += 1
temp //= 5
for k in range(2):
prefixH[i][j + 1][k] += prefixH[i][j][k]
prefixV[i + 1][j][k] += prefixV[i][j][k]
for i in range(m):
for j in range(n):
left = prefixH[i][j]
up = prefixV[i][j]
right, down, center = [0] * 2, [0] * 2, [0] * 2
for k in range(2):
right[k] = prefixH[i][n][k] - prefixH[i][j + 1][k]
down[k] = prefixV[m][j][k] - prefixV[i + 1][j][k]
center[k] = prefixH[i][j + 1][k] - prefixH[i][j][k]
LU, LD, RU, RD = [0] * 2, [0] * 2, [0] * 2, [0] * 2
for k in range(2):
LU[k] += left[k] + up[k] + center[k]
LD[k] += left[k] + down[k] + center[k]
RU[k] += right[k] + up[k] + center[k]
RD[k] += right[k] + down[k] + center[k]
ans = max(ans,
min(LU[0], LU[1]),
min(LD[0], LD[1]),
min(RU[0], RU[1]),
min(RD[0], RD[1]))
return ans | maximum-trailing-zeros-in-a-cornered-path | [Python] Prefix Sum, O(m * n) | xil899 | 7 | 574 | maximum trailing zeros in a cornered path | 2,245 | 0.35 | Medium | 31,090 |
https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1968151/Python3-prefix-sums | class Solution:
def maxTrailingZeros(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f2 = [[0]*n for _ in range(m)]
f5 = [[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
x = grid[i][j]
while x % 2 == 0:
f2[i][j] += 1
x //= 2
x = grid[i][j]
while x % 5 == 0:
f5[i][j] += 1
x //= 5
h = [[[0, 0] for j in range(n+1)] for i in range(m+1)]
v = [[[0, 0] for j in range(n+1)] for i in range(m+1)]
for i in range(m):
for j in range(n):
h[i][j+1][0] = h[i][j][0] + f2[i][j]
h[i][j+1][1] = h[i][j][1] + f5[i][j]
v[i+1][j][0] = v[i][j][0] + f2[i][j]
v[i+1][j][1] = v[i][j][1] + f5[i][j]
ans = 0
for i in range(m):
for j in range(n):
hh = [h[i][n][0] - h[i][j][0], h[i][n][1] - h[i][j][1]]
vv = [v[m][j][0] - v[i][j][0], v[m][j][1] - v[i][j][1]]
ans = max(ans, min(h[i][j][0]+v[i][j][0]+f2[i][j], h[i][j][1]+v[i][j][1]+f5[i][j]))
ans = max(ans, min(h[i][j][0]+vv[0], h[i][j][1]+vv[1]))
ans = max(ans, min(hh[0]+v[i][j][0], hh[1]+v[i][j][1]))
ans = max(ans, min(hh[0]+vv[0]-f2[i][j], hh[1]+vv[1]-f5[i][j]))
return ans | maximum-trailing-zeros-in-a-cornered-path | [Python3] prefix sums | ye15 | 1 | 98 | maximum trailing zeros in a cornered path | 2,245 | 0.35 | Medium | 31,091 |
https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1970787/Python3-O(mn)-Verticalhorizontal-Prefix-Sum-Solution | class Solution:
def maxTrailingZeros(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
new_grid = [[[0, 0] for _ in range(n)] for _ in range(m)]
for i in range(m):
for j in range(n):
target = grid[i][j]
count2, count5 = 0, 0
while target % 2 == 0:
count2 += 1
target = target//2
while target % 5 == 0:
count5 += 1
target = target//5
new_grid[i][j] = [count2, count5]
verti_grid = [[[0, 0] for _ in range(n)] for _ in range(m)]
hori_grid = [[[0, 0] for _ in range(n)] for _ in range(m)]
for i in range(m):
sum2, sum5 = 0, 0
for j in range(n):
sum2 += new_grid[i][j][0]
sum5 += new_grid[i][j][1]
hori_grid[i][j] = [sum2, sum5]
for j in range(n):
sum2, sum5 = 0, 0
for i in range(m):
sum2 += new_grid[i][j][0]
sum5 += new_grid[i][j][1]
verti_grid[i][j] = [sum2, sum5]
res = -sys.maxsize
for i in range(m):
for j in range(n):
start2, start5 = hori_grid[i][j][0], hori_grid[i][j][1]
start2_up, start5_up = start2 + verti_grid[i][j][0] - new_grid[i][j][0], \
start5 + verti_grid[i][j][1] - new_grid[i][j][1]
start2_down, start5_down = start2 + verti_grid[-1][j][0] - verti_grid[i][j][0], \
start5 + verti_grid[-1][j][1] - verti_grid[i][j][1]
res = max([min(start2_up, start5_up), min(start2_down, start5_down), res])
for i in range(m):
for j in range(n):
if j != 0:
start2, start5 = hori_grid[i][-1][0] - hori_grid[i][j-1][0], \
hori_grid[i][-1][1] - hori_grid[i][j-1][1]
else:
start2, start5 = hori_grid[i][-1][0], hori_grid[i][-1][1]
start2_up, start5_up = start2 + verti_grid[i][j][0] - new_grid[i][j][0], \
start5 + verti_grid[i][j][1] - new_grid[i][j][1]
start2_down, start5_down = start2 + verti_grid[-1][j][0] - verti_grid[i][j][0], \
start5 + verti_grid[-1][j][1] - verti_grid[i][j][1]
res = max([min(start2_up, start5_up), min(start2_down, start5_down), res])
return res | maximum-trailing-zeros-in-a-cornered-path | Python3 O(mn) Vertical/horizontal Prefix Sum Solution | xxHRxx | 0 | 164 | maximum trailing zeros in a cornered path | 2,245 | 0.35 | Medium | 31,092 |
https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1956401/22-lines-python3-solution | class Solution:
def maxTrailingZeros(self, grid: List[List[int]]) -> int:
def check(grid, row_order=1, col_order=1):
above = [[0, 0] for i in range(len(grid[0]))]
ans = 0
for row in grid[::row_order]:
this_row = [0, 0]
for i, v in enumerate(row[::col_order]):
c2 = c5 = 0
while v % 2 == 0:
c2 += 1
v /= 2
while v % 5 == 0:
c5 += 1
v /= 5
this_row[0] += c2
this_row[1] += c5
ans = max(ans, min(this_row[0] + above[i][0], this_row[1] + above[i][1]))
above[i][0] += c2
above[i][1] += c5
return ans
return max(check(grid, ro, co) for ro in [-1, 1] for co in [-1, 1]) | maximum-trailing-zeros-in-a-cornered-path | 22 lines python3 solution | ShenTM | 0 | 22 | maximum trailing zeros in a cornered path | 2,245 | 0.35 | Medium | 31,093 |
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2494179/Python-oror-Faster-than-100-oror-Simple-DFS-oror-Easy-Explanation | class Solution:
def longestPath(self, par: List[int], s: str) -> int:
dit = {}
# store tree in dictionary
for i in range(len(par)):
if par[i] in dit:
dit[par[i]].append(i)
else:
dit[par[i]] = [i]
ans = 1
def dfs(n):
nonlocal ans
if n not in dit:
return 1
largest=0 # largest path lenght among all children
second_largest=0 # second largest path lenght among all children
for u in dit[n]:
curr = dfs(u)
if s[u]!=s[n]: # pick child path if child and parent both have different value
if curr>largest:
second_largest = largest
largest = curr
elif curr>second_largest:
second_largest = curr
ans = max(ans,largest+second_largest+1) # largest path including parent with at most two children
return largest+1 # return largest path end at parent
dfs(0)
return ans
``` | longest-path-with-different-adjacent-characters | Python || Faster than 100% || Simple DFS || Easy Explanation | Laxman_Singh_Saini | 10 | 359 | longest path with different adjacent characters | 2,246 | 0.453 | Hard | 31,094 |
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2843047/Python-DFS-solution-with-some-explanation-(similar-question-included) | class Solution:
def longestPath(self, parent: List[int], s: str) -> int:
tree = defaultdict(list)
for child, par in enumerate(parent):
tree[par].append(child)
max_length = 1
def maxLength(node):
nonlocal max_length
if not tree[node]:
return 1
heap = [-1,-1]
for child in tree[node]:
if s[child] != s[node]:
heappush(heap,-1*(maxLength(child) + 1))
else:
maxLength(child)
first_max= -heappop(heap)
second_max = -heappop(heap)
cur_max = first_max + second_max - 1
max_length = max(max_length,cur_max)
return first_max
maxLength(0)
return max_length | longest-path-with-different-adjacent-characters | [Python] DFS solution with some explanation (similar question included) | natnael_tadele | 0 | 5 | longest path with different adjacent characters | 2,246 | 0.453 | Hard | 31,095 |
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2842324/Python-simple-DFS | class Solution:
def longestPath(self, parent: List[int], s: str) -> int:
graph = defaultdict(set)
for i in range(len(parent)):
graph[parent[i]].add(i)
answer = [1]
def dfs(node):
if not graph[node]:
return 1, node
pathsFromChildren = []
for neigh in graph[node]:
path, ch = dfs(neigh)
if s[node] != s[ch]:
heappush(pathsFromChildren, -path)
i = 0
pathSumForTwoBranches = 0
maxChildPath = -pathsFromChildren[0] if pathsFromChildren else 0
while pathsFromChildren and i < 2:
pathSumForTwoBranches += -heappop(pathsFromChildren)
i += 1
answer[0] = max(answer[0], 1 + pathSumForTwoBranches)
return maxChildPath + 1, node
dfs(0)
return answer[0]
# time and space complexity
# time: O(V + Elog(E)), V = no of nodes, E = number of edges (len(parent))
# space: O(V) | longest-path-with-different-adjacent-characters | Python simple DFS | Yared_betsega | 0 | 2 | longest path with different adjacent characters | 2,246 | 0.453 | Hard | 31,096 |
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2598360/Simple-top-down-DFS-in-Python-fully-explained. | class Solution:
def dfs(self, v):
best, best_one, best_two = 1, 0, 0
for c in self.children[v]:
best_tmp, path_len = self.dfs(c)
best = max(best, best_tmp)
if self.s[v] != self.s[c]:
if path_len > best_one:
best_one, best_two = path_len, best_one
elif path_len > best_two:
best_two = path_len
return max(best, best_one + best_two + 1), best_one + 1
def longestPath(self, parent: List[int], s: str) -> int:
self.s = list(s)
self.children = defaultdict(set)
[self.children[p].add(c) for c, p in enumerate(parent) if p >= 0]
return self.dfs(0)[0] | longest-path-with-different-adjacent-characters | Simple top-down DFS in Python, fully explained. | metaphysicalist | 0 | 25 | longest path with different adjacent characters | 2,246 | 0.453 | Hard | 31,097 |
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2554783/Python3-or-Simple-DFS | class Solution:
def longestPath(self, parent: List[int], s: str) -> int:
n=len(parent)
adj=[[] for i in range(n)]
self.ans=0
for i in range(1,n):
adj[parent[i]].append(i)
def dfs(curr,adj):
mx,smx=0,0 #max and secondmax value child return to its parent if parent has children>2.
for it in adj[curr]:
new=dfs(it,adj)
if mx<new:
smx=mx
mx=new
elif smx<new:
smx=new
self.ans=max(self.ans,mx+smx+1)
if s[parent[curr]]==s[curr]:
return 0
else:
return mx+1
dfs(0,adj)
return self.ans | longest-path-with-different-adjacent-characters | [Python3] | Simple DFS | swapnilsingh421 | 0 | 45 | longest path with different adjacent characters | 2,246 | 0.453 | Hard | 31,098 |
https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/1968153/Python3-post-order-dfs | class Solution:
def longestPath(self, parent: List[int], s: str) -> int:
tree = [[] for _ in parent]
for i, x in enumerate(parent):
if x != -1: tree[x].append(i)
def fn(u):
"""Return longest depth."""
nonlocal ans
m0 = m1 = 0
for v in tree[u]:
val = fn(v)
if s[u] != s[v]:
if val >= m0: m0, m1 = val, m0
elif val > m1: m1 = val
ans = max(ans, 1 + m0 + m1)
return 1 + m0
ans = 0
fn(0)
return ans | longest-path-with-different-adjacent-characters | [Python3] post-order dfs | ye15 | 0 | 54 | longest path with different adjacent characters | 2,246 | 0.453 | Hard | 31,099 |
Subsets and Splits