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/minimum-total-distance-traveled/discuss/2783378/O(n3)-solution-sort-%2B-shift-the-minimum-subarray-of-assignments
class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: robot.sort() factory.sort() cap = [] for x, limit in factory: cap.extend([x] * limit) m = len(robot) n = len(cap) indices = list(range(m)) ans = sum(abs(x - y) for x, y in zip(robot, cap)) def increment(i): diff = 0 while i < m: if indices[i] + 1 < n: diff -= abs(robot[i] - cap[indices[i]]) diff += abs(robot[i] - cap[indices[i] + 1]) else: return math.inf, i + 1 if i + 1 < m and indices[i] + 1 == indices[i + 1]: i += 1 else: return diff, i + 1 for i in reversed(range(m)): while True: diff, j = increment(i) if diff <= 0: ans += diff for x in range(i, j): indices[x] += 1 else: break return ans
minimum-total-distance-traveled
O(n^3) solution, sort + shift the minimum subarray of assignments
chuan-chih
1
50
minimum total distance traveled
2,463
0.397
Hard
33,800
https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2787810/My-Python3-solution
class Solution: def minimumTotalDistance(self, A: List[int], B: List[List[int]]) -> int: n, m = len(A), len(B) dp = [inf] * (n + 1) dp[n] = 0 A.sort() B.sort() for j in range(m-1,-1,-1): for i in range(n): cur = 0 for k in range(1, min(B[j][1], n - i) + 1): cur += abs(A[i + k - 1] - B[j][0]) dp[i] = min(dp[i], dp[i + k] + cur) return dp[0]
minimum-total-distance-traveled
My Python3 solution
Chiki1601
0
8
minimum total distance traveled
2,463
0.397
Hard
33,801
https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783549/python3-O(N-3)-dp-solution
class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: robot.sort() factory.sort() m, n = len(robot), len(factory) @lru_cache(None) def dp(i, j, k): if i >= m: # all robots fixed return 0 if j >= n: # not all robots get fixed but run out of factories. return math.inf if k <= 0: # the factory uses up repair limit if j + 1 < n: # use next factory if it's valid return dp(i, j + 1, factory[j + 1][1]) else: # no more factory to use, return inf return math.inf dist = abs(robot[i] - factory[j][0]) # cost to use current factory # Use current factory or skip it return min(dist + dp(i + 1, j, k - 1), dp(i, j, -1)) return dp(0, 0, factory[0][1])
minimum-total-distance-traveled
[python3] O(N ^ 3) dp solution
caijun
0
20
minimum total distance traveled
2,463
0.397
Hard
33,802
https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783490/Python-DP-Solution-with-explanation
class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: m = len(robot) n = len(factory) factory.sort() robot.sort() opt = [[float('inf') for j in range(n + 1)] for i in range(m + 1)] for j in range(n + 1): opt[0][j] = 0 for i in range(1, m + 1): for j in range(1, n + 1): cur = 0 for x in range(min(factory[j - 1][1], i) + 1): opt[i][j] = min(opt[i][j], opt[i-x][j-1] + cur) cur += abs(factory[j-1][0] - robot[i-1-x]) return opt[-1][-1]
minimum-total-distance-traveled
[Python] DP Solution with explanation
codenoob3
0
22
minimum total distance traveled
2,463
0.397
Hard
33,803
https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783254/Memorized-DFS
class Solution: def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int: @cache def dfs(i, j, k): if j == 0: #no robot available return 0 if i == 0: #no factory available return float('inf') if k == 0: #the ith factory has 0 spot to use if i == 1: #if there'ls only one factory left return float('inf') return dfs(i - 1, j, factory[i - 2][1]) #since the ith factory has no spot, we have to not use it result1 = dfs(i - 1, j, factory[i - 2][1]) if i >= 2 else float('inf') #condition 1: don't use the ith factory result2 = dfs(i, j - 1, k - 1) + abs(robot[j - 1] - factory[i - 1][0])#condition 2: use the ith factory result = min(result1, result2) return result m, n = len(robot), len(factory) robot.sort() factory.sort() result = dfs(n, m, factory[n - 1][1]) return result
minimum-total-distance-traveled
Memorized DFS
zhanghaotian19
0
30
minimum total distance traveled
2,463
0.397
Hard
33,804
https://leetcode.com/problems/number-of-distinct-averages/discuss/2817811/Easy-Python-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: av=[] nums.sort() while nums: av.append((nums[-1]+nums[0])/2) nums.pop(-1) nums.pop(0) return len(set(av))
number-of-distinct-averages
Easy Python Solution
Vistrit
2
75
number of distinct averages
2,465
0.588
Easy
33,805
https://leetcode.com/problems/number-of-distinct-averages/discuss/2831078/Python3-set
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() seen = set() for i in range(len(nums)//2): seen.add((nums[i] + nums[~i])/2) return len(seen)
number-of-distinct-averages
[Python3] set
ye15
1
4
number of distinct averages
2,465
0.588
Easy
33,806
https://leetcode.com/problems/number-of-distinct-averages/discuss/2818793/Python-oror-Easy-oror-Sorting-oror-O(nlogn)-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: n=len(nums) i=0 j=n-1 s=set() nums.sort() while i<=j: s.add((nums[i]+nums[j])/2) i+=1 j-=1 return len(s)
number-of-distinct-averages
Python || Easy || Sorting || O(nlogn) Solution
DareDevil_007
1
13
number of distinct averages
2,465
0.588
Easy
33,807
https://leetcode.com/problems/number-of-distinct-averages/discuss/2808058/Python-Simple-Python-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: a=[] for i in range(len(nums)//2): a.append((max(nums)+min(nums))/2) nums.remove(max(nums)) nums.remove(min(nums)) b=set(a) print(a) print(b) return len(b)
number-of-distinct-averages
✅✅[ Python ] 🐍🐍 Simple Python Solution ✅✅
sourav638
1
26
number of distinct averages
2,465
0.588
Easy
33,808
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807918/Python-Answer-Heap-and-Set-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: h1 = nums.copy() h2 = [-i for i in nums.copy()] ans = set() heapify(h1) heapify(h2) while h1 and h2: n1 = heappop(h1) n2= - heappop(h2) ans.add(mean([n2,n1])) return len(ans)
number-of-distinct-averages
[Python Answer🤫🐍🐍🐍] Heap and Set Solution
xmky
1
13
number of distinct averages
2,465
0.588
Easy
33,809
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807189/easy-python-solutionoror-easy-to-understand
class Solution: def distinctAverages(self, nums: List[int]) -> int: lis = [] while nums!=[]: if (min(nums)+max(nums))/2 not in lis: lis.append((min(nums)+max(nums))/2) nums.remove(max(nums)) nums.remove(min(nums)) return len(lis)
number-of-distinct-averages
✅✅easy python solution|| easy to understand
chessman_1
1
30
number of distinct averages
2,465
0.588
Easy
33,810
https://leetcode.com/problems/number-of-distinct-averages/discuss/2849863/90-speed-python-solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: ans = set() while nums: ans.add((nums.pop(nums.index(min(nums))) + nums.pop(nums.index(max(nums))))/2) return len(ans)
number-of-distinct-averages
90% speed python solution
StikS32
0
1
number of distinct averages
2,465
0.588
Easy
33,811
https://leetcode.com/problems/number-of-distinct-averages/discuss/2849228/easy-python-sort.-Detailed-explanation.
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() avg_list=[] while nums: _len = len(nums) temp = [nums[0],nums[-1]] nums = nums[1:_len-1] avg_list.append(sum(temp)/2) return len(set(avg_list))
number-of-distinct-averages
easy python - sort. Detailed explanation.
ATHBuys
0
1
number of distinct averages
2,465
0.588
Easy
33,812
https://leetcode.com/problems/number-of-distinct-averages/discuss/2843315/Python-Two-Pointers-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() print(nums) left, right = 0, len(nums) - 1 visited = set() while left < right: avg = (nums[left] + nums[right]) / 2 if avg not in visited: visited.add(avg) left += 1 right -= 1 return len(visited)
number-of-distinct-averages
Python Two Pointers Solution
Vayne1994
0
1
number of distinct averages
2,465
0.588
Easy
33,813
https://leetcode.com/problems/number-of-distinct-averages/discuss/2839775/Python-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: s=set() l=nums n=len(l) while(n>0): s.add((max(l)+min(l))/2) l.remove(max(l)) l.remove(min(l)) n=len(l) return len(s)
number-of-distinct-averages
Python Solution
CEOSRICHARAN
0
5
number of distinct averages
2,465
0.588
Easy
33,814
https://leetcode.com/problems/number-of-distinct-averages/discuss/2839542/Python3-Unreadable-One-Liner-with-Sorting-1-Line
class Solution: def distinctAverages(self, nums: List[int]) -> int: return len({(num+nums[idx])/2 for idx, num in enumerate(reversed(nums[len(nums)//2:]))}) if nums.sort() is None else 0
number-of-distinct-averages
[Python3] - Unreadable One-Liner with Sorting - 1 Line
Lucew
0
3
number of distinct averages
2,465
0.588
Easy
33,815
https://leetcode.com/problems/number-of-distinct-averages/discuss/2834349/Python-(Simple-Maths)
class Solution: def dfs(self, arr): n = len(arr) n1, n2 = min(arr), max(arr) arr.remove(n1) arr.remove(n2) return (n1+n2)/2 def distinctAverages(self, nums): n, ans = len(nums), set() while n: ans.add(self.dfs(nums)) n -= 2 return len(ans)
number-of-distinct-averages
Python (Simple Maths)
rnotappl
0
5
number of distinct averages
2,465
0.588
Easy
33,816
https://leetcode.com/problems/number-of-distinct-averages/discuss/2831884/Python-Solution-Clean-Code-oror-set-min-max-oror-contest-question
class Solution: def distinctAverages(self, nums: List[int]) -> int: n=len(nums) l=[] while n!=0: mi=min(nums) ma=max(nums) l.append((mi+ma)/2) if mi==ma: nums.remove(mi) else: nums.remove(mi) nums.remove(ma) n=len(nums) return len(set(l))
number-of-distinct-averages
Python Solution - Clean Code || set , min , max || contest question
T1n1_B0x1
0
4
number of distinct averages
2,465
0.588
Easy
33,817
https://leetcode.com/problems/number-of-distinct-averages/discuss/2824119/Easy-understanding-beginner-friendly
class Solution: def distinctAverages(self, nums: List[int]) -> int: d = set() left = 0 right = len(nums)-1 nums = sorted(nums) while left < right: num = (nums[left] + nums[right])/2 d.add(num) left += 1 right -= 1 print(num) #print(d) return len(d) #count = 0 #for i in d: #count += 1 #return count
number-of-distinct-averages
Easy understanding - beginner friendly
Asselina94
0
2
number of distinct averages
2,465
0.588
Easy
33,818
https://leetcode.com/problems/number-of-distinct-averages/discuss/2816758/Python-code
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() reslist=[] zero_list = [x for x in nums if x==0] if zero_list == nums: return 1 while nums: print("Nums:",nums) if(nums[0] and nums[-1]): avg = (nums[0]+nums[-1])/2 del nums[0] del nums[-1] reslist.append(avg) elif nums[0]: avg = nums[0]/2 del nums[0] del nums[-1] reslist.append(avg) elif nums[-1]: avg = nums[-1]/2 del nums[-1] del nums[0] reslist.append(avg) else: break reslist=set(reslist) print(reslist) return (len(reslist))
number-of-distinct-averages
Python code
user1079z
0
4
number of distinct averages
2,465
0.588
Easy
33,819
https://leetcode.com/problems/number-of-distinct-averages/discuss/2816420/Number-of-Distinct-Averages(Solution)
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() x,l = [],len(nums) for i in range(l//2) : x.append((nums[i]+nums[l-i-1])/2) return len(set(x))
number-of-distinct-averages
Number of Distinct Averages(Solution)
NIKHILTEJA
0
1
number of distinct averages
2,465
0.588
Easy
33,820
https://leetcode.com/problems/number-of-distinct-averages/discuss/2812981/Python-solution
class Solution(object): def distinctAverages(self, nums): """ :type nums: List[int] :rtype: int """ s=set() nums.sort() i=0 j=len(nums)-1 while i<j: avg=(float(nums[i])+float(nums[j]))/2 s.add(avg) i+=1 j-=1 return len(s)
number-of-distinct-averages
Python solution
indrajitruidascse
0
3
number of distinct averages
2,465
0.588
Easy
33,821
https://leetcode.com/problems/number-of-distinct-averages/discuss/2811254/Sort-and-pick-up-pairs-100-speed
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() len_nums = len(nums) len_nums1 = len_nums - 1 return len(set(nums[i] + nums[len_nums1 - i] for i in range(len_nums // 2)))
number-of-distinct-averages
Sort and pick up pairs, 100% speed
EvgenySH
0
7
number of distinct averages
2,465
0.588
Easy
33,822
https://leetcode.com/problems/number-of-distinct-averages/discuss/2810106/Python3-easy-to-understand
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() i, j = 0, len(nums) - 1 res = set() while i < j: res.add((nums[i] + nums[j]) / 2) i += 1 j -= 1 return len(res)
number-of-distinct-averages
Python3 - easy to understand
mediocre-coder
0
5
number of distinct averages
2,465
0.588
Easy
33,823
https://leetcode.com/problems/number-of-distinct-averages/discuss/2810096/Python%3A-sort%2Bzip-average-is-not-important
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() return len(set([x+y for x,y in zip(nums,nums[::-1])]))
number-of-distinct-averages
Python: sort+zip - average is not important
Leox2022
0
2
number of distinct averages
2,465
0.588
Easy
33,824
https://leetcode.com/problems/number-of-distinct-averages/discuss/2809774/Two-pointers-Python3
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() i,j=0,len(nums)-1 vi=set() while i<j: vi.add((nums[i]+nums[j])/2) i+=1 j-=1 return len(vi)
number-of-distinct-averages
Two pointers Python3 ✅
Xhubham
0
5
number of distinct averages
2,465
0.588
Easy
33,825
https://leetcode.com/problems/number-of-distinct-averages/discuss/2809183/Efficient-solution-using-sorting-and-two-pointers
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() hash_dict = {} i = 0 j = len(nums) - 1 while i < j: min_element = nums[i] max_element = nums[j] avg = (min_element + max_element)/2 hash_dict[avg] = 1 i += 1 j -= 1 return len(hash_dict)
number-of-distinct-averages
Efficient solution using sorting and two-pointers
akashp2001
0
4
number of distinct averages
2,465
0.588
Easy
33,826
https://leetcode.com/problems/number-of-distinct-averages/discuss/2809172/python-easy-solution-using-sorting
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() hash_dict = {} while len(nums) > 0: min_element = nums[0] max_element = nums[len(nums) - 1] avg = (min_element + max_element)/2 hash_dict[avg] = 1 nums.pop(0) nums.pop() return len(hash_dict)
number-of-distinct-averages
python easy solution using sorting
akashp2001
0
1
number of distinct averages
2,465
0.588
Easy
33,827
https://leetcode.com/problems/number-of-distinct-averages/discuss/2809074/Python-Using-set-beats-100.00
class Solution: def distinctAverages(self, nums): avgs = set() while len(nums): a, b = max(nums), min(nums) avgs.add(a+b) # sum is sufficient, dividing by 2 not necessary nums.remove(a) nums.remove(b) return len(avgs)
number-of-distinct-averages
[Python] Using set, beats 100.00%
U753L
0
7
number of distinct averages
2,465
0.588
Easy
33,828
https://leetcode.com/problems/number-of-distinct-averages/discuss/2808885/Python-solution-using-Queues
class Solution: def distinctAverages(self, nums: List[int]) -> int: memo = set() nums.sort() queue = deque(nums) while queue: average = (queue[-1] + queue[0])/2 if average not in memo: memo.add(average) queue.pop() queue.popleft() return len(memo)
number-of-distinct-averages
Python solution using Queues
dee7
0
4
number of distinct averages
2,465
0.588
Easy
33,829
https://leetcode.com/problems/number-of-distinct-averages/discuss/2808331/Number-of-Distinct-Averages-Python-Easy-Approach!!!!
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums=sorted(nums) lst=[] if(len(nums)==2): return 1 while(len(nums)!=0): x=nums[0]+nums[-1] lst.append(x) del nums[0] del nums[-1] s=set(lst) return len(s)
number-of-distinct-averages
Number of Distinct Averages Python Easy Approach!!!!
knock_knock47
0
3
number of distinct averages
2,465
0.588
Easy
33,830
https://leetcode.com/problems/number-of-distinct-averages/discuss/2808294/Python-3-solution%3A
class Solution: def distinctAverages(self, nums: List[int]) -> int: i=0 l=[] while(i<len(nums)): avg=(max(nums)+min(nums))/2 if avg not in l: l.append(avg) nums.pop(nums.index(max(nums))) nums.pop(nums.index(min(nums))) return len(l)
number-of-distinct-averages
Python 3 solution:
CharuArora_
0
3
number of distinct averages
2,465
0.588
Easy
33,831
https://leetcode.com/problems/number-of-distinct-averages/discuss/2808179/Python-sort-%2B-set
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() return len(set((nums[i] + nums[-i-1])/2 for i in range(len(nums)//2)))
number-of-distinct-averages
Python, sort + set
blue_sky5
0
6
number of distinct averages
2,465
0.588
Easy
33,832
https://leetcode.com/problems/number-of-distinct-averages/discuss/2808062/Easy-Python-Solution-explained
class Solution: def distinctAverages(self, nums: List[int]) -> int: d={} nums.sort() for i in range(len(nums)//2): # set.add(nums[i]+nums[len(nums)-i-1]) d[nums[i]+nums[len(nums)-i-1]]=1//checks uniqueness return len(d)
number-of-distinct-averages
Easy Python Solution explained
yashleetcode123
0
2
number of distinct averages
2,465
0.588
Easy
33,833
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807762/Faster-than-100-Simple-Python3-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: averages = set() while len(nums) != 0: min_num = min(nums) nums.remove(min_num) max_num = max(nums) nums.remove(max_num) averages.add((max_num + min_num) / 2) return len(averages)
number-of-distinct-averages
Faster than 100% Simple Python3 Solution
y-arjun-y
0
5
number of distinct averages
2,465
0.588
Easy
33,834
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807521/Python-5-lines-use-fast-bitwise-operators
class Solution: def distinctAverages(self, nums: List[int]) -> int: avgs = set() nums.sort() for i in range(len(nums) >> 1): avgs.add((nums[i] + nums[~i]) / 2) return len(avgs)
number-of-distinct-averages
Python 5 lines - use fast bitwise operators
SmittyWerbenjagermanjensen
0
3
number of distinct averages
2,465
0.588
Easy
33,835
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807480/Python-or-JavaScript-2-Pointers-with-sort
class Solution: def distinctAverages(self, nums: List[int]) -> int: result = set() sortedNums = sorted(nums) left = 0 right = len(sortedNums) - 1 while left < right: result.add((sortedNums[left] + sortedNums[right]) / 2) left += 1 right -= 1 return len(result)
number-of-distinct-averages
[Python | JavaScript] 2 Pointers with sort
ChaseDho
0
13
number of distinct averages
2,465
0.588
Easy
33,836
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807426/pythonjava-easy-to-understand
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() seen = set() for i in range(len(nums) // 2): seen.add((nums[i] + nums[len(nums) - 1 - i]) / 2) print(seen) return len(seen) class Solution { public int distinctAverages(int[] nums) { Arrays.sort(nums); Set<Float> seen = new HashSet<>(); for (int i = 0; i < nums.length / 2; i ++) { seen.add((float)(nums[i] + nums[nums.length - 1 - i]) / 2); System.out.println(seen); } return seen.size(); } }
number-of-distinct-averages
python/java easy to understand
akaghosting
0
5
number of distinct averages
2,465
0.588
Easy
33,837
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807335/Python-Progress-from-O(NlogN)-to-O(N)-solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: avgs = set() sorted_nums = collections.deque(sorted(nums)) while sorted_nums: lo, hi = sorted_nums.popleft(), sorted_nums.pop() avgs.add((lo+hi)/2) return len(avgs)
number-of-distinct-averages
[Python] Progress from O(NlogN) to O(N) solution
sc1233
0
10
number of distinct averages
2,465
0.588
Easy
33,838
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807335/Python-Progress-from-O(NlogN)-to-O(N)-solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: freq_by_num = collections.Counter(nums) lo, hi = min(nums), max(nums) avgs = set() while len(freq_by_num) > 0: if lo not in freq_by_num: lo += 1 continue if hi not in freq_by_num: hi -= 1 continue avgs.add((lo+hi)/2) freq_by_num[lo] -= 1 freq_by_num[hi] -= 1 if freq_by_num[lo] == 0: del freq_by_num[lo] if freq_by_num[hi] == 0: del freq_by_num[hi] return len(avgs)
number-of-distinct-averages
[Python] Progress from O(NlogN) to O(N) solution
sc1233
0
10
number of distinct averages
2,465
0.588
Easy
33,839
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807308/Easy-Python-Solution-oror-100
class Solution: def distinctAverages(self, nums: List[int]) -> int: avgList = [] nums.sort() while nums: maxNumber = nums.pop(0) minNumber = nums.pop(-1) avgList.append((maxNumber + minNumber) / 2) avgList = set(avgList) return len(avgList)
number-of-distinct-averages
Easy Python Solution || 100%
arefinsalman86
0
8
number of distinct averages
2,465
0.588
Easy
33,840
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807285/Easy-Solution-O(nlog(n))-and-O(1)
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() q=collections.deque(nums) s=set() while len(q)>0: s.add(q.popleft()+q.pop()) return len(s)
number-of-distinct-averages
Easy Solution O(nlog(n)) and O(1)
Motaharozzaman1996
0
5
number of distinct averages
2,465
0.588
Easy
33,841
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807278/Python3-Two-Lines
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() return len({(nums[i]+nums[-i-1])/2 for i in range(len(nums)//2)})
number-of-distinct-averages
Python3, Two Lines
Silvia42
0
8
number of distinct averages
2,465
0.588
Easy
33,842
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807278/Python3-Two-Lines
class Solution02: def distinctAverages(self, nums: List[int]) -> int: s=set() nums.sort() for i in range(len(nums)//2): x = (nums[i]+nums[-i-1])/2 s.add(x) return len(s)
number-of-distinct-averages
Python3, Two Lines
Silvia42
0
8
number of distinct averages
2,465
0.588
Easy
33,843
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807271/Python-Solution
class Solution: def distinctAverages(self, nums: List[int]) -> int: nums.sort() avgs = [] for i in range(len(nums)//2): avgs.append((nums[i]+nums[-i-1])/2) return len(set(avgs))
number-of-distinct-averages
Python Solution
saivamshi0103
0
6
number of distinct averages
2,465
0.588
Easy
33,844
https://leetcode.com/problems/number-of-distinct-averages/discuss/2807235/Simple-Python%3A-Queue-%2B-Set
class Solution: def distinctAverages(self, nums: List[int]) -> int: ans = set() nums.sort() queue = deque(nums) while queue: low = queue.popleft() high = queue.pop() ans.add((low+high)/2) return len(ans)
number-of-distinct-averages
Simple Python: Queue + Set
pokerandcode
0
15
number of distinct averages
2,465
0.588
Easy
33,845
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2813134/Easy-solution-from-Recursion-to-memoization-oror-3-approaches-oror-PYTHON3
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: def recursive(s,ans): if len(s)>=low and len(s)<=high: ans+=[s] if len(s)>high: return recursive(s+"0"*zero,ans) recursive(s+"1"*one,ans) return ans=[] recursive("",ans) return len(ans)
count-ways-to-build-good-strings
Easy solution from Recursion to memoization || 3 approaches || PYTHON3
dabbiruhaneesh
1
32
count ways to build good strings
2,466
0.419
Medium
33,846
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2813134/Easy-solution-from-Recursion-to-memoization-oror-3-approaches-oror-PYTHON3
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: ans=[0] def recursive(s): if s>high: return 0 p=recursive(s+zero)+recursive(s+one) if s>=low and s<=high: p+=1 return p return recursive(0)%(10**9+7)
count-ways-to-build-good-strings
Easy solution from Recursion to memoization || 3 approaches || PYTHON3
dabbiruhaneesh
1
32
count ways to build good strings
2,466
0.419
Medium
33,847
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2813134/Easy-solution-from-Recursion-to-memoization-oror-3-approaches-oror-PYTHON3
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: ans=[0] mod=10**9+7 def recursive(s): if s>high: return 0 if dp[s]!=-1: return dp[s] p=recursive(s+zero)+recursive(s+one) if s>=low and s<=high: p+=1 dp[s]=p%mod return dp[s] dp=[-1]*(high+1) return recursive(0)%mod
count-ways-to-build-good-strings
Easy solution from Recursion to memoization || 3 approaches || PYTHON3
dabbiruhaneesh
1
32
count ways to build good strings
2,466
0.419
Medium
33,848
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2812003/FASTEST-PYTHON-SOLUTION-USING-DYNAMIC-PROGRAMMING
class Solution: def countGoodStrings(self, low: int, high: int, a: int, b: int) -> int: ct=0 lst=[-1]*(high+1) def sol(a,b,lst,i): if i==0: return 1 if i<0: return 0 if lst[i]!=-1: return lst[i] lst[i]=sol(a,b,lst,i-a)+sol(a,b,lst,i-b) return lst[i] for i in range(low,high+1): ct+=sol(a,b,lst,i) return ct%(10**9+7)
count-ways-to-build-good-strings
FASTEST PYTHON SOLUTION USING DYNAMIC PROGRAMMING
beneath_ocean
1
12
count ways to build good strings
2,466
0.419
Medium
33,849
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2808241/Python-DP-tabulation-approach
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: MOD = 1_000_000_007 limit = high + 1 - min(zero, one) # last dp array index to be processed dp_size = limit + max(zero, one) # dp array size dp: List[int] = [0] * dp_size dp[0] = 1 for i in range(limit): if dp[i]: dp[i+zero] += dp[i] % MOD dp[i+one] += dp[i] % MOD return sum(dp[low:high+1]) % MOD
count-ways-to-build-good-strings
[Python] DP tabulation approach
olzh06
1
19
count ways to build good strings
2,466
0.419
Medium
33,850
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2829014/Python3-DP
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: dp = [0] * (high+1) for i in range(high, -1, -1): if low <= i: dp[i] = 1 if i+zero <= high: dp[i] += dp[i+zero] if i+one <= high: dp[i] += dp[i+one] dp[i] %= 1_000_000_007 return dp[0]
count-ways-to-build-good-strings
[Python3] DP
ye15
0
6
count ways to build good strings
2,466
0.419
Medium
33,851
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2825194/Python-(Simple-DP)
class Solution: def countGoodStrings(self, low, high, zero, one): dp = [0]*(high+1) dp[0] = 1 for i in range(1,max(one,zero)+1): if i-zero >= 0 and i-one >= 0: dp[i] = dp[i-zero] + dp[i-one] elif i-zero >= 0: dp[i] = dp[i-zero] elif i-one >= 0: dp[i] = dp[i-one] for i in range(max(one,zero)+1,high+1): dp[i] = dp[i-zero] + dp[i-one] return sum([dp[i] for i in range(low,high+1)])%(10**9+7)
count-ways-to-build-good-strings
Python (Simple DP)
rnotappl
0
3
count ways to build good strings
2,466
0.419
Medium
33,852
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2810983/Python-or-EnumerationRecurrence-Problem
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: p = 10**9 + 7 dp = Counter({0:1}) for i in range(1,high+1): dp[i] = (dp[i - zero] + dp[i - one]) % p return reduce(lambda x, y : (x + y) % p, (dp[i] for i in range(low,high+1)), 0)
count-ways-to-build-good-strings
Python | Enumeration/Recurrence Problem
on_danse_encore_on_rit_encore
0
5
count ways to build good strings
2,466
0.419
Medium
33,853
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2808895/python3-dp-solution-for-reference.
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: dp = [0]*(high) dp[zero-1] = 1 dp[one-1] += 1 for i in range(high): if i-zero >= 0: dp[i] += 1+dp[i-zero] if i-one >= 0: dp[i] += 1+dp[i-one] return (dp[high-1] - (dp[low-2] if low-2>=0 else 0))%(10**9+7)
count-ways-to-build-good-strings
[python3] dp solution for reference.
vadhri_venkat
0
9
count ways to build good strings
2,466
0.419
Medium
33,854
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2807924/Python-Answer-DP-Solution
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: mod = 10**9 + 7 @cache def calc(i): res = 0 ro = 0 rz = 0 if i == zero: res += 1 if i == one: res += 1 if i > zero: rz = calc(i-zero)%mod if i > one: ro = calc(i-one)%mod return (res + rz + ro)%mod mod = 10**9 + 7 res = 0 for i in range(low, high+1): val = calc(i) res = (res+ val )%mod return res
count-ways-to-build-good-strings
[Python Answer🤫🐍🐍🐍] DP Solution
xmky
0
8
count ways to build good strings
2,466
0.419
Medium
33,855
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2807475/python-Good-old-DP
class Solution: def __init__(self): self.dp = {} def OPT(self, i): if i <= 0: return 0 return self.dp[i] def countGoodStrings(self, low, high, zero, one): mod = 1e9 + 7 self.dp[zero] = 1 if one in self.dp: self.dp[one] += 1 else: self.dp[one] = 1 for i in range(1, high + 1): if i not in self.dp: self.dp[i] = (self.OPT(i - one) + self.OPT(i - zero)) % mod else: self.dp[i] += (self.OPT(i - one) + self.OPT(i - zero)) % mod count = 0 for i in range(low, high + 1): count += self.dp[i] return int(count % mod)
count-ways-to-build-good-strings
[python] Good old DP
uzairfassi
0
11
count ways to build good strings
2,466
0.419
Medium
33,856
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2807305/DP-Python-solution
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: dp = [0] * (high+1) dp[0] = 1 mod = 10**9 + 7 for i in range(1, high+1): dp[i] = (dp[i-zero] + dp[i-one]) return sum(dp[i] for i in range(low, high+1)) % mod
count-ways-to-build-good-strings
DP Python solution
qcx60990
0
19
count ways to build good strings
2,466
0.419
Medium
33,857
https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2807274/Simple-Python3-solution.
class Solution: def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int: dp = [0]*(high+1) dp[zero] += 1 dp[one] += 1 mod = (10**9)+7 for i in range(min(zero,one)+1,high+1): if i-zero>=0: dp[i]+=dp[i-zero] if i-one>=0: dp[i]+=dp[i-one] s = 0 for i in range(low,high+1): s+=dp[i] return s%mod
count-ways-to-build-good-strings
Simple Python3 solution.
kamal0308
0
23
count ways to build good strings
2,466
0.419
Medium
33,858
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2838006/BFS-%2B-Graph-%2B-level-O(n)
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: path_b = set([bob]) lvl_b = {bob:0} g = defaultdict(list) for u, v in edges: g[u].append(v) g[v].append(u) n = len(amount) node_lvl = [0] * n q = deque([0]) lvl = 0 seen = set([0]) while q: size = len(q) for _ in range(size): u = q.popleft() node_lvl[u] = lvl for v in g[u]: if v in seen: continue q.append(v) seen.add(v) lvl += 1 b = bob lvl = 1 while b != 0: for v in g[b]: if node_lvl[v] > node_lvl[b]: continue b = v cost = amount[b] path_b.add(b) lvl_b[b] = lvl break lvl += 1 # print(f"lvl_b {lvl_b} path_b {path_b} ") cost_a = [] q = deque([(0, amount[0])]) seen = set([0]) lvl = 1 while q: size = len(q) for _ in range(size): u, pre_cost = q.popleft() child_cnt = 0 for v in g[u]: if v in seen: continue seen.add(v) child_cnt += 1 cost = pre_cost inc = amount[v] if v in path_b: if lvl_b[v] == lvl: cost += inc//2 elif lvl_b[v] > lvl: cost += inc else: cost += 0 else: cost += amount[v] q.append((v, cost)) if child_cnt == 0: cost_a.append(pre_cost) lvl += 1 ans = max(cost_a) return ans
most-profitable-path-in-a-tree
BFS + Graph + level, O(n)
goodgoodwish
0
2
most profitable path in a tree
2,467
0.464
Medium
33,859
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2831080/Python3-dfs
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: n = 1 + len(edges) tree = [[] for _ in range(n)] for u, v in edges: tree[u].append(v) tree[v].append(u) seen = [False] * n def dfs(u, d): """Return """ seen[u] = True ans = -inf dd = 0 if u == bob else n for v in tree[u]: if not seen[v]: x, y = dfs(v, d+1) ans = max(ans, x) dd = min(dd, y) if ans == -inf: ans = 0 if d == dd: ans += amount[u]//2 if d < dd: ans += amount[u] return ans, dd+1 return dfs(0, 0)[0]
most-profitable-path-in-a-tree
[Python3] dfs
ye15
0
3
most profitable path in a tree
2,467
0.464
Medium
33,860
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2814835/Python3-or-Two-DFS-Traversal-or-Explanation
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: n = len(amount) parent = [-1 for i in range(n)] dist = [0 for i in range(n)] graph = [[] for i in range(n)] for u,v in edges: graph[u].append(v) graph[v].append(u) def findDistance(curr,currParent): for it in graph[curr]: if it!=currParent: dist[it] = dist[curr] + 1 findDistance(it,curr) parent[it] = curr return def modifyCost(currBob,currDist): while currBob!=0: if currDist < dist[currBob]: amount[currBob] = 0 elif currDist == dist[currBob]: amount[currBob] = amount[currBob]//2 currBob = parent[currBob] currDist+=1 return def findMaxProfitPath(curr,currParent): if len(graph[curr]) == 1 and curr > 0: return amount[curr] val = -math.inf for it in graph[curr]: if it!=currParent: val = max(val,findMaxProfitPath(it,curr)) return val + amount[curr] findDistance(0,-1) modifyCost(bob,0) return findMaxProfitPath(0,-1)
most-profitable-path-in-a-tree
[Python3] | Two DFS Traversal | Explanation
swapnilsingh421
0
14
most profitable path in a tree
2,467
0.464
Medium
33,861
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2812390/python
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: adj = defaultdict(set) for u, v in edges: adj[u].add(v) adj[v].add(u) path = [[bob, 0]] bobSteps = dict() aliceMaxScore = float('-inf') def dfsBob(parent, root, steps): if root == 0: for node, step in path: bobSteps[node] = step return for child in adj[root]: if child == parent: continue path.append([child, steps + 1]) dfsBob(root, child, steps + 1) path.pop() def dfsAlice(parent, root, steps, score): nonlocal aliceMaxScore if (root not in bobSteps) or (steps < bobSteps[root]): score += amount[root] elif steps > bobSteps[root]: score += 0 elif steps == bobSteps[root]: score += amount[root] // 2 if (len(adj[root]) == 1) and (root != 0): aliceMaxScore = max(aliceMaxScore, score) return for neighbor in adj[root]: if neighbor == parent: continue dfsAlice(root, neighbor, steps + 1, score) dfsBob(-1, bob, 0) dfsAlice(-1, 0, 0, 0) return aliceMaxScore
most-profitable-path-in-a-tree
python
yzhao156
0
10
most profitable path in a tree
2,467
0.464
Medium
33,862
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2811225/Python-3-DFS-Backtracking-with-Explanation
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: n = len(amount) # number of nodes graph = [set() for _ in range(n)] # adjacency list presentation of the tree for i,j in edges: graph[i].add(j) graph[j].add(i) bobpath = dict() # use hashmap to record nodes on the path from bob to root 0 # as well as time: node = key, time = value self.stop = False # True when Bob reaches root 0, this helps stop the DFS visited = [False]*n # True if node is visited, initialized as False for all nodes def backtrackbob(node,time): # the first backtracking, with time at each node bobpath[node] = time # add node:time to the hashmap visited[node] = True # mark node as visited if node==0: # root 0 is reached self.stop = True # this helps stop the DFS return None count = 0 # this helps determine if a node is leaf node for nei in graph[node]: if not visited[nei]: count += 1 break if count==0: # node is leaf node if all neighbors are already visited del bobpath[node] # delete leaf node from hashmap before retreating from leaf node return None for nei in graph[node]: # explore unvisited neighbors of node if self.stop: return None # if root 0 is already reached, stop the DFS if not visited[nei]: backtrackbob(nei,time+1) if not self.stop: # if root 0 is reached, keep node in the hashmap when backtracking del bobpath[node] # otherwise, delete node before retreating return None backtrackbob(bob,0) # execute the first backtracking, time at bob is initialized = 0 self.ans = float(-inf) # answer of the problem self.income = 0 # income of Alice when travelling to leaf nodes, initialized = 0 visited = [False]*n # True if node is visited, initialized as False for all nodes def backtrackalice(node,time): # second backtracking, with time at each node visited[node] = True if node in bobpath: # if the node Alice visits is on Bob's path, there are 3 cases if time == bobpath[node]: # Alice and Bob reach the node at the same time reward = amount[node]//2 elif time<bobpath[node]: # Alice reachs node before Bob reward = amount[node] else: # Alice reachs node after Bob reward = 0 else: # if the node Alice visits is not on Bob's path reward = amount[node] self.income += reward # add the reward (price) at this node to the income count = 0 # this helps determine if a node is leaf node for nei in graph[node]: if not visited[nei]: count += 1 break if count==0: # node is leaf node if all neighbors are already visited self.ans = max(self.ans,self.income) # update the answer self.income -= reward # remove the reward (price) at leaf node before backtracking return None for nei in graph[node]: # explore unvisited neighbors of node if not visited[nei]: backtrackalice(nei,time+1) self.income -= reward # remove the reward (price) at this node before retreating return None backtrackalice(0,0) # execute the second backtracking, time at root 0 is initialized = 0 return self.ans
most-profitable-path-in-a-tree
Python 3, DFS Backtracking with Explanation
cuongmng
0
14
most profitable path in a tree
2,467
0.464
Medium
33,863
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2809797/Python3-BFS%2BDFS-step-by-step
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: class Node: def __init__(self, val, gate, parent, steps_from_zero): self.val = val self.gate = gate self.parent = parent self.steps_from_zero = steps_from_zero self.steps_from_bob = len(amount) self.children = set() # build a graph from input graph = defaultdict(list) for e in edges: graph[e[0]].append(e[1]) graph[e[1]].append(e[0]) seen = set([0]) root = Node(val = 0, gate = amount[0], parent = None, steps_from_zero = 0) # BFS to construct the tree queue = deque([root]) level = 1 while queue: curr_level_length = len(queue) for _ in range(curr_level_length): curr_node = queue.popleft() for i in graph[curr_node.val]: if i not in seen: seen.add(i) new_node = Node(val = i, gate = amount[i], parent = curr_node, steps_from_zero = level) if i == bob: bob_node = new_node curr_node.children.add(new_node) queue.append(new_node) level += 1 # iterate bob path and fill in steps_from_bob tmp_node = bob_node i = 0 while tmp_node: tmp_node.steps_from_bob = i i += 1 tmp_node = tmp_node.parent # DFS to find max net_income def dfs(curr_alice, net_income): nonlocal ans # Bob and Alice are in the same node if curr_alice.steps_from_zero == curr_alice.steps_from_bob: net_income += curr_alice.gate / 2 # Alice reaches the node before Bob therefore gain/pay the gate fee elif curr_alice.steps_from_zero < curr_alice.steps_from_bob: net_income += curr_alice.gate # Alice reaches leaf node if len(curr_alice.children) == 0: ans = max(ans, net_income) return for child_node in curr_alice.children: dfs(child_node, net_income) ans = float('-inf') dfs(root, 0) return int(ans)
most-profitable-path-in-a-tree
[Python3] BFS+DFS step-by-step
user1793l
0
9
most profitable path in a tree
2,467
0.464
Medium
33,864
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2807551/Python-Easiest-DFS-Solution-100-Faster
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: graph = defaultdict(list) for i,j in edges: graph[i].append(j) graph[j].append(i) parent=[-1 for _ in range(len(amount)+1)] time = [-1 for _ in range(len(amount)+1)] def dfs(node,par,cnt): parent[node]=par time[node]=cnt for nei in graph[node]: if nei!=par: dfs(nei,node,cnt+1) dfs(0,-1,0) curr = bob t=0 while curr!=0: if t<time[curr]: amount[curr]=0 elif t==time[curr]: amount[curr]//=2 curr = parent[curr] t+=1 best = -sys.maxsize def dfs2(node,par,curr): down =0 for v in graph[node]: if v!=par: dfs2(v,node,curr+amount[v]) down+=1 if down==0: nonlocal best best = max(best,curr) dfs2(0,-1,amount[0]) return best
most-profitable-path-in-a-tree
Python Easiest DFS Solution 100% Faster
prateekgoel7248
0
35
most profitable path in a tree
2,467
0.464
Medium
33,865
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2807500/Easy-solution-with-python100-speed
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: graph = defaultdict(list) for a, b in edges: graph[a].append(b) graph[b].append(a) arr = [] def dfs(node, path, parent = -1): if node == 0: arr.extend(list(path)) return for nbr in graph[node]: if nbr == parent: continue path.append(nbr) dfs(nbr, path, node) path.pop() dfs(bob, [bob]) for i in range(len(arr)//2): amount[arr[i]] = 0 if len(arr)%2: amount[arr[i+1]] //= 2 visited = set() def dfs2(node, parent = -1): if len(graph[node]) == 1 and graph[node][0] == parent: return amount[node] cur = -inf for nbr in graph[node]: if parent == nbr: continue cur = max(cur, dfs2(nbr, node)) return amount[node] + cur return dfs2(0)
most-profitable-path-in-a-tree
Easy solution with python100% speed
Samuelabatneh
0
11
most profitable path in a tree
2,467
0.464
Medium
33,866
https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2807464/Python-Solution-Explained
class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: graph = defaultdict(list) for edge in edges: graph[edge[0]].append(edge[1]) graph[edge[1]].append(edge[0]) def bob_dfs(curr_node, prev_node, count): if curr_node == 0: return count if prev_node != None and len(graph[curr_node]) == 1 and curr_node != 0: return -1 for node in graph[curr_node]: if node == prev_node: continue res = bob_dfs(node, curr_node, count + 1) if res != -1: if count < (res + 1) // 2: amount[curr_node] = 0 if res % 2 == 0 and res // 2 == count: amount[curr_node] /= 2 return res return -1 bob_dfs(bob, None, 0) leafs_res = [] def sum_dfs(curr_node, curr_sum, prev_node): if len(graph[curr_node]) == 1 and curr_node != 0: leafs_res.append(curr_sum + amount[curr_node]) for node in graph[curr_node]: if node == prev_node: continue sum_dfs(node, curr_sum + amount[curr_node], curr_node) sum_dfs(0, 0, None) res = max(leafs_res) if res % 1 == 0: return int(res) else: return res
most-profitable-path-in-a-tree
Python Solution - Explained
eden33335
0
13
most profitable path in a tree
2,467
0.464
Medium
33,867
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807491/Python-Simple-dumb-O(N)-solution
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: def splitable_within(parts_limit): # check the message length achievable with <parts_limit> parts length = sum(limit - len(str(i)) - len(str(parts_limit)) - 3 for i in range(1, parts_limit + 1)) return length >= len(message) parts_limit = 9 if not splitable_within(parts_limit): parts_limit = 99 if not splitable_within(parts_limit): parts_limit = 999 if not splitable_within(parts_limit): parts_limit = 9999 if not splitable_within(parts_limit): return [] # generate the actual message parts parts = [] m_index = 0 # message index for part_index in range(1, parts_limit + 1): if m_index >= len(message): break length = limit - len(str(part_index)) - len(str(parts_limit)) - 3 parts.append(message[m_index:m_index + length]) m_index += length return [f'{part}<{i + 1}/{len(parts)}>' for i, part in enumerate(parts)]
split-message-based-on-limit
[Python] Simple dumb O(N) solution
vudinhhung942k
2
62
split message based on limit
2,468
0.483
Hard
33,868
https://leetcode.com/problems/split-message-based-on-limit/discuss/2843586/Binary-Search-solution-with-digit-count-check(It-passes-%22abbababbbaaa-aabaa-a%22-test-case-)
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: if limit <= 5: return [] # Important: Determine number of digit of b. BS monotone holds for same digit-count # This will fix the testcase like: message = "abbababbbaaa aabaa a", limit = 8 nd = -1 for dc in range(1, 7): remain = len(message) for d in range(1, dc+1): if limit - 3 - d - dc < 0: break remain -= (limit - 3 - d - dc)*9*10**(d-1) if remain <= 0: nd = dc break if nd == -1: return [] # binary search of b start, end = 10**(nd - 1), 10 ** nd while start != end: mid = (start + end) // 2 dc = len(str(mid)) remain = len(message) for d in range(1, dc): remain -= (limit - 3 - d - dc)*9*10**(d-1) for i in range(10**(dc-1), mid + 1): remain -= limit - 3 - 2*dc if remain < 0: break # print(start, end, mid, remain) if remain > 0: start = mid + 1 else: end = mid # construct answer ans = [] dc = len(str(start)) cur = 0 for d in range(1, dc + 1): for i in range(10**(d-1), 10**d): nxt = min(cur + limit - 3 - d - dc, len(message)) ans.append(message[cur:nxt] + '<' + str(i) + '/' + str(start) + '>') cur = nxt if nxt >= len(message): break if cur < len(message): return [] return ans
split-message-based-on-limit
Binary Search solution with digit-count check(It passes "abbababbbaaa aabaa a" test case )
qian48
0
4
split message based on limit
2,468
0.483
Hard
33,869
https://leetcode.com/problems/split-message-based-on-limit/discuss/2831094/Python3-linear-search
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: prefix = b = 0 while 3 + len(str(b))*2 < limit and len(message) + prefix + (3+len(str(b)))*b > limit * b: b += 1 prefix += len(str(b)) ans = [] if 3 + len(str(b))*2 < limit: i = 0 for a in range(1, b+1): step = limit - (len(str(a)) + len(str(b)) + 3) ans.append(f"{message[i:i+step]}<{a}/{b}>") i += step return ans
split-message-based-on-limit
[Python3] linear search
ye15
0
9
split message based on limit
2,468
0.483
Hard
33,870
https://leetcode.com/problems/split-message-based-on-limit/discuss/2823276/Python-Binary-Search-On-range(1-9)-(10-99)...
class Solution: def splitMessage(self, s: str, limit: int) -> List[str]: if limit <= 4: return [] n = len(s) ans, step = float('inf'), 1 while True: if 2 * len(str(step)) + 3 > limit: break lo, hi, suffix = step, min(n, step * 10 - 1), len(str(step)) + 3 while lo <= hi: mid = (lo + hi) // 2 idx, i = 1, 0 while i < n: i += limit - (suffix + len(str(idx))) idx += 1 if idx - 1 > mid: break idx -= 1 if idx <= mid: ans = min(ans, mid) hi = mid - 1 else: lo = mid + 1 if ans != float('inf'): break step *= 10 if ans == float('inf'): return [] ans_split = [] idx, i, suffix = 1, 0, len(str(ans)) + 3 while i < n: ans_split.append(s[i:i + limit - (suffix + len(str(idx)))] + '<' + str(idx) + '/' + str(ans) + '>') i += limit - (suffix + len(str(idx))) idx += 1 return ans_split
split-message-based-on-limit
[Python] Binary Search On range(1, 9), (10, 99)...
cava
0
8
split message based on limit
2,468
0.483
Hard
33,871
https://leetcode.com/problems/split-message-based-on-limit/discuss/2818925/Faster-than-95
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: l=len(message) if limit<=5: return [] min_size=None min_ct=0 for ct in range(1, min(((limit-4)>>1)+1, 6)): total=0 for i in range(1, ct): total+=(9*10**(i-1))*(limit-i-ct-3) left=l-total if left<0: continue left_size=(left-1)//(limit-2*ct-3)+1 if left_size>9*10**(ct-1): continue total_size=left_size+10**(ct-1)-1 if (min_size==None or total_size<min_size): min_size=total_size min_ct=ct if min_size==None: return [] else: str_total_size=str(min_size) ans=[] curs=0 for i in range(min_size-1): new_curs=curs+limit-(int(log10(i+1))+1)-min_ct-3 # print(limit, (int(log10(i+1))+1), min_ct) ans.append(message[curs:new_curs]+'<'+str(i+1)+'/'+str_total_size+'>') curs=new_curs ans.append(message[curs:]+'<'+str_total_size+'/'+str_total_size+'>') return ans
split-message-based-on-limit
Faster than 95%
mbeceanu
0
4
split message based on limit
2,468
0.483
Hard
33,872
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807907/Python-Answer-Greedy-Buffer-and-Special-Character
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: def buildnum(start,total): return f'<{start}/{total}>' output = [] if limit-5 <= 0: return [] else: total = ceil(len(message) / (limit-3-2)) total = '&amp;'* len(str(total)) buff = [] count = 1 for i,c in enumerate(message): buff.append(c) if len(buff) + len(buildnum(count,total)) == limit: output.append( ''.join(buff) + buildnum(count,total) ) buff = [] count += 1 elif len(buff) + len(buildnum(count,total)) > limit : return [] if len(buff) > 0: output.append( ''.join(buff) + buildnum(count,total) ) count += 1 count -= 1 output = [s.replace(total,str(count)) for s in output] return output
split-message-based-on-limit
[Python Answer🤫🐍🐍🐍] Greedy Buffer and Special Character
xmky
0
11
split message based on limit
2,468
0.483
Hard
33,873
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807809/Python-3Binary-Search
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: n = len(message) l, h = 1, n def bs(x): dl = 3 + len(str(x)) n = len(message) for i in range(1, x+1): k = limit - dl - len(str(i)) if k <= 0: return False n -= k if n <= 0: return True return False while l < h: mid = l + (h - l) // 2 if bs(mid): h = mid else: l = mid + 1 dl = 3 + len(str(l)) n = len(message) j = 0 ans = [] for i in range(1, l+1): k = limit - dl - len(str(i)) if k <= 0: return [] tmp = message[j:j+k] + f"<{i}/{l}>" ans.append(tmp) j += k return ans
split-message-based-on-limit
[Python 3]Binary Search
chestnut890123
0
24
split message based on limit
2,468
0.483
Hard
33,874
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807488/Python-Solution-Explained
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: res = [] curr_start = 0 if (limit - 5) * 9 > len(message): calc = ceil(len(message) / (limit - 5)) for i in range(1, calc+1): res.append(f"{message[curr_start:curr_start+(limit-5)]}<{i}/{calc}>") curr_start += (limit - 5) return res elif (limit - 6) * 9 + (limit - 7) * 90 > len(message): calc = ceil((len(message) - (limit - 6) * 9) / (limit - 7)) + 9 for i in range(1, 10): res.append(f"{message[curr_start:curr_start+(limit-6)]}<{i}/{calc}>") curr_start += (limit - 6) for i in range(10, calc+1): res.append(f"{message[curr_start:curr_start+(limit-7)]}<{i}/{calc}>") curr_start += (limit - 7) return res elif (limit - 7) * 9 + (limit - 8) * 90 + (limit - 9) * 900 > len(message): calc = ceil((len(message) - (limit - 7) * 9 - (limit - 8) * 90) / (limit - 9)) + 99 for i in range(1, 10): res.append(f"{message[curr_start:curr_start+(limit-7)]}<{i}/{calc}>") curr_start += (limit - 7) for i in range(10, 100): res.append(f"{message[curr_start:curr_start+(limit-8)]}<{i}/{calc}>") curr_start += (limit - 8) for i in range(100, calc+1): res.append(f"{message[curr_start:curr_start+(limit-9)]}<{i}/{calc}>") curr_start += (limit - 9) return res elif (limit - 8) * 9 + (limit - 9) * 90 + (limit - 10) * 900 + (limit - 11) * 9000 > len(message): calc = ceil((len(message) - (limit - 8) * 9 - (limit - 9) * 90 - (limit - 10) * 900) / (limit - 11)) + 999 for i in range(1, 10): res.append(f"{message[curr_start:curr_start+(limit-8)]}<{i}/{calc}>") curr_start += (limit - 8) for i in range(10, 100): res.append(f"{message[curr_start:curr_start+(limit-9)]}<{i}/{calc}>") curr_start += (limit - 9) for i in range(100, 1000): res.append(f"{message[curr_start:curr_start+(limit-10)]}<{i}/{calc}>") curr_start += (limit - 10) for i in range(1000, calc+1): res.append(f"{message[curr_start:curr_start+(limit-11)]}<{i}/{calc}>") curr_start += (limit - 11) return res else: return []
split-message-based-on-limit
Python Solution - Explained
eden33335
0
7
split message based on limit
2,468
0.483
Hard
33,875
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807409/Fast-Tricky-Python3-Explained
class Solution: def split(self, message, limit, parts): i, res = 0, [] for part in range(1, parts+1): suffix = '<' + str(part) + '/' + str(parts) + '>' prefix_len = limit - len(suffix) res.append(message[i:i+prefix_len] + suffix) i += prefix_len return res def splitMessage(self, message: str, limit: int) -> List[str]: if limit < 6: return [] n = len(message) for parts in range(1, n+1): tot_parts = parts cur_parts = 9 suffix = len(str(parts)) + 4 prefix = limit - suffix mess = n while tot_parts > 0 and mess > 0 and prefix > 0: max_take = cur_parts * prefix if mess > max_take: tot_parts -= cur_parts mess -= max_take else: full_parts = mess // prefix tot_parts -= full_parts mess -= full_parts * prefix if mess > 0: tot_parts -= 1 mess = 0 cur_parts *= 10 prefix -= 1 suffix += 1 if tot_parts == mess == 0: return self.split(message, limit, parts) return []
split-message-based-on-limit
Fast, Tricky Python3 Explained
ryangrayson
0
21
split message based on limit
2,468
0.483
Hard
33,876
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807297/O(N)-Simple-Straightforward-Approach-Python
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: symbol_count = 3 page_count = 0 N = len(message) ans_page = -1 for i in range(1,len(message)+1): page_count += len(str(i)) tot_count = (len(str(i))+3)*i suffix_count = page_count + tot_count x , y = divmod(suffix_count+N,i) if (x == limit and y == 0) or (x < limit): ans_page = i break if ans_page == -1: return [] curr_page = 1 suff_start = '<' suff_end = '/'+str(ans_page)+'>' i = 0 res = [] while curr_page <= ans_page: if i >= N: return [] suffix = suff_start + str(curr_page) + suff_end j = i + limit - len(suffix) res.append(message[i:j]+suffix) i = j curr_page += 1 return res
split-message-based-on-limit
O(N) - Simple Straightforward Approach - Python
ananth_19
0
28
split message based on limit
2,468
0.483
Hard
33,877
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807296/Binary-Search-%2B-Construction-Python-Solution
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: l, r = 0, len(message) def is_possible(n): rem = len(message) for i in range(1,n+1): used = 3 + len(str(i)) + len(str(n)) taken = limit - used rem -= taken return rem <= 0 while l < r: mid = (l+r) // 2 if is_possible(mid): r = mid else: l = mid + 1 if not is_possible(l): return [] ret = [] mptr = 0 for i in range(1,l+1): used = 3 + len(str(i)) + len(str(l)) curr = message[mptr:mptr+(limit-used)] mptr += (limit-used) ret.append(curr + "<{0}/{1}>".format(str(i), str(l))) return ret
split-message-based-on-limit
Binary Search + Construction Python Solution
seanjaeger
0
17
split message based on limit
2,468
0.483
Hard
33,878
https://leetcode.com/problems/split-message-based-on-limit/discuss/2807269/Nothing-fancy%3A-check-potential-of-parts-one-by-one-O(nlogn)
class Solution: def splitMessage(self, message: str, limit: int) -> List[str]: n = len(message) best = math.inf def check(x): avail = 0 start = 1 while start <= x: next_start = start * 10 suffix = f"<{start}/{x}>" if len(suffix) > limit: return False avail += (min(next_start - 1, x) - start + 1) * (limit - len(suffix)) start = next_start last_suffix = f"<{x}/{x}>" return avail >= n >= avail - (limit - len(last_suffix)) for n_part in range(1, n + 1): if check(n_part): break else: return [] ans = [] start = 0 for i in range(1, n_part + 1): suffix = f"<{i}/{n_part}>" next_start = start + limit - len(suffix) ans.append(message[start:next_start] + suffix) start = next_start return ans
split-message-based-on-limit
Nothing fancy: check potential # of parts one by one, O(nlogn)
chuan-chih
0
26
split message based on limit
2,468
0.483
Hard
33,879
https://leetcode.com/problems/convert-the-temperature/discuss/2839560/Python-or-Easy-Solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [(celsius + 273.15),(celsius * 1.80 + 32.00)]
convert-the-temperature
Python | Easy Solution✔
manayathgeorgejames
4
127
convert the temperature
2,469
0.909
Easy
33,880
https://leetcode.com/problems/convert-the-temperature/discuss/2810126/Very-difficult-%3A(
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32]
convert-the-temperature
Very difficult :(
mediocre-coder
4
610
convert the temperature
2,469
0.909
Easy
33,881
https://leetcode.com/problems/convert-the-temperature/discuss/2817777/Python-1-liner
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
Python 1-liner
Vistrit
3
137
convert the temperature
2,469
0.909
Easy
33,882
https://leetcode.com/problems/convert-the-temperature/discuss/2818442/PYTHON-Simple-or-One-liner
class Solution: def convertTemperature(self, c: float) -> List[float]: return [c+273.15, c*1.80+32]
convert-the-temperature
[PYTHON] Simple | One-liner
omkarxpatel
2
8
convert the temperature
2,469
0.909
Easy
33,883
https://leetcode.com/problems/convert-the-temperature/discuss/2818760/Python-Easy-Solution-in-One-Line
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+273.15,celsius*1.8+32]
convert-the-temperature
Python Easy Solution in One Line
DareDevil_007
1
41
convert the temperature
2,469
0.909
Easy
33,884
https://leetcode.com/problems/convert-the-temperature/discuss/2808822/Python-solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: ans=[] Kelvin = celsius + 273.15 Fahrenheit = celsius * (9/5) + 32 ans.append(Kelvin) ans.append(Fahrenheit) return ans
convert-the-temperature
Python solution
shashank_2000
1
50
convert the temperature
2,469
0.909
Easy
33,885
https://leetcode.com/problems/convert-the-temperature/discuss/2849858/Python-oneliner
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+273.15, celsius*1.80+32]
convert-the-temperature
Python oneliner
StikS32
0
2
convert the temperature
2,469
0.909
Easy
33,886
https://leetcode.com/problems/convert-the-temperature/discuss/2849468/Python3-solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [round(celsius + 273.15, 5), round((celsius *1.80) + 32.00, 5)]
convert-the-temperature
Python3 solution
SupriyaArali
0
1
convert the temperature
2,469
0.909
Easy
33,887
https://leetcode.com/problems/convert-the-temperature/discuss/2845500/1-line-Python
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
1 line, Python
Tushar_051
0
2
convert the temperature
2,469
0.909
Easy
33,888
https://leetcode.com/problems/convert-the-temperature/discuss/2844004/Simple-Python-Solution-%3A)
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [ celsius + 273.15, # kelvin celsius * 1.80 + 32.00 # farenheit ]
convert-the-temperature
Simple Python Solution :)
EddSH1994
0
1
convert the temperature
2,469
0.909
Easy
33,889
https://leetcode.com/problems/convert-the-temperature/discuss/2841244/one-line-solution-python
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15,celsius * (9/5) + 32.00]
convert-the-temperature
one line solution python
ft3793
0
1
convert the temperature
2,469
0.909
Easy
33,890
https://leetcode.com/problems/convert-the-temperature/discuss/2838076/Kid-Problem-Eaiest-One-Line-Code
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+273.15,celsius*1.80 + 32.00]
convert-the-temperature
Kid Problem Eaiest One Line Code
khanismail_1
0
3
convert the temperature
2,469
0.909
Easy
33,891
https://leetcode.com/problems/convert-the-temperature/discuss/2831897/Python-Solution-Math-oror-Contest-Question
class Solution: def convertTemperature(self, celsius: float) -> List[float]: k=celsius + 273.15 f=celsius * 1.80 + 32.00 ans=[round(k, 5),round(f, 5)] return ans
convert-the-temperature
Python Solution - Math || Contest Question
T1n1_B0x1
0
3
convert the temperature
2,469
0.909
Easy
33,892
https://leetcode.com/problems/convert-the-temperature/discuss/2822760/hello-world
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [(celsius+273.15),((celsius*1.8)+32.0)]
convert-the-temperature
hello world
ATHBuys
0
5
convert the temperature
2,469
0.909
Easy
33,893
https://leetcode.com/problems/convert-the-temperature/discuss/2822121/Python3-one-line-solution
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [round(celsius + 273.15, 5), round(celsius * 1.8 + 32,5)]
convert-the-temperature
Python3 one-line solution
sipi09
0
4
convert the temperature
2,469
0.909
Easy
33,894
https://leetcode.com/problems/convert-the-temperature/discuss/2821695/Python3-Solution-with-using-simple-conversion
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.8 + 32.0]
convert-the-temperature
[Python3] Solution with using simple conversion
maosipov11
0
4
convert the temperature
2,469
0.909
Easy
33,895
https://leetcode.com/problems/convert-the-temperature/discuss/2820055/Python-1-Line-Code
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius + 273.15, celsius * 1.80 + 32.00]
convert-the-temperature
Python 1 - Line Code
Asmogaur
0
5
convert the temperature
2,469
0.909
Easy
33,896
https://leetcode.com/problems/convert-the-temperature/discuss/2818001/Easy-1-line-python-code
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return(celsius + 273.15, celsius * 1.80 + 32.00)
convert-the-temperature
Easy 1-line python code
Xand0r
0
1
convert the temperature
2,469
0.909
Easy
33,897
https://leetcode.com/problems/convert-the-temperature/discuss/2816282/Convert-the-temperature(Solution)
class Solution: def convertTemperature(self, celsius: float) -> List[float]: return [celsius+273.15,celsius*1.80+32.00]
convert-the-temperature
Convert the temperature(Solution)
NIKHILTEJA
0
1
convert the temperature
2,469
0.909
Easy
33,898
https://leetcode.com/problems/convert-the-temperature/discuss/2815507/python-solution-no-need-for-10**-5
class Solution: def convertTemperature(self, celsius: float) -> List[float]: kelvin = celsius + 273.15 fahrenheit = (celsius * 1.80) + 32.00 return [kelvin, fahrenheit]
convert-the-temperature
python solution no need for 10**-5
samanehghafouri
0
2
convert the temperature
2,469
0.909
Easy
33,899