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/construct-k-palindrome-strings/discuss/1527654/Python3-Solution-with-using-hashmap | class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k:
return False
counter = collections.Counter(s)
odd_count = 0
for key in counter:
if counter[key] % 2 != 0:
odd_count += 1
return odd_count <= k | construct-k-palindrome-strings | [Python3] Solution with using hashmap | maosipov11 | 0 | 78 | construct k palindrome strings | 1,400 | 0.632 | Medium | 21,000 |
https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/639682/Python3-two-solutions-Circle-and-Rectangle-Overlapping | class Solution:
def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:
x = 0 if x1 <= x_center <= x2 else min(abs(x1-x_center), abs(x2-x_center))
y = 0 if y1 <= y_center <= y2 else min(abs(y1-y_center), abs(y2-y_center))
return x**2 + y**2 <= radius**2 | circle-and-rectangle-overlapping | Python3 two solutions - Circle and Rectangle Overlapping | r0bertz | 2 | 386 | circle and rectangle overlapping | 1,401 | 0.442 | Medium | 21,001 |
https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/639682/Python3-two-solutions-Circle-and-Rectangle-Overlapping | class Solution:
def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:
def pointInCircle(p, center):
nonlocal radius
xr, yr = center
x, y = p
return abs(x-xr)**2 + abs(y-yr)**2 <= radius**2
def segmentOverlaps(s1, s2):
return max(s1[0], s2[0]) <= min(s1[1], s2[1])
if any(pointInCircle(p, (x_center, y_center))
for p in [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]):
return True
if (not segmentOverlaps([x_center - radius, x_center + radius], sorted([x1, x2])) or
not segmentOverlaps([y_center - radius, y_center + radius], sorted([y1, y2]))):
return False
return x1 <= x_center <= x2 or y1 <= y_center <= y2 | circle-and-rectangle-overlapping | Python3 two solutions - Circle and Rectangle Overlapping | r0bertz | 2 | 386 | circle and rectangle overlapping | 1,401 | 0.442 | Medium | 21,002 |
https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/1133076/Python3-geometry | class Solution:
def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:
if x1 <= x_center <= x2 and y1 <= y_center <= y2: return True # circle inside rectangle
for x, y in (x1, y1), (x1, y2), (x2, y1), (x2, y2):
if (x - x_center)**2 + (y - y_center)**2 <= radius**2: return True
# check edge
for x in [x1, x2]:
if x_center - radius <= x <= x_center + radius and y1 <= y_center <= y2: return True
for y in [y1, y2]:
if y_center - radius <= y <= y_center + radius and x1 <= x_center <= x2: return True
return False | circle-and-rectangle-overlapping | [Python3] geometry | ye15 | 1 | 150 | circle and rectangle overlapping | 1,401 | 0.442 | Medium | 21,003 |
https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/1489055/Partitioning-all-areas-in-9-cases | class Solution:
def checkOverlap(self, r: int, xc: int, yc: int, x1: int, y1: int, x2: int, y2: int) -> bool:
if xc >= x1 and xc <= x2 and yc >= y1 and yc <= y2:
return True
elif xc > x2:
if yc > y2:
return r**2 >= (xc-x2)**2 + (yc-y2)**2
elif yc >= y1 and yc < y2:
return r >= xc-x2
else: # yc < y1
return r**2 >= (xc-x2)**2 + (yc-y1)**2
elif xc <= x1:
if yc > y2:
return r**2 >= (xc-x1)**2 + (yc-y2)**2
elif yc >= y1 and yc < y2:
return r >= x1-xc
else: # yc < y1
return r**2 >= (xc-x1)**2 + (yc-y1)**2
elif xc > x1 and xc < x2 and yc > y2:
return r >= yc -y2
else:
return r >= y1-yc | circle-and-rectangle-overlapping | Partitioning all areas in 9 cases | byuns9334 | 0 | 102 | circle and rectangle overlapping | 1,401 | 0.442 | Medium | 21,004 |
https://leetcode.com/problems/reducing-dishes/discuss/2152786/python-3-oror-simple-sorting-solution | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort(reverse=True)
maxSatisfaction = dishSum = 0
for dish in satisfaction:
dishSum += dish
if dishSum <= 0:
break
maxSatisfaction += dishSum
return maxSatisfaction | reducing-dishes | python 3 || simple sorting solution | dereky4 | 1 | 102 | reducing dishes | 1,402 | 0.72 | Hard | 21,005 |
https://leetcode.com/problems/reducing-dishes/discuss/1133079/Python3-dp | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort() # ascending order
@cache
def fn(i, k):
"""Return max sum of like-time coefficient of satisfation[i:]."""
if i == len(satisfaction): return 0
return max(satisfaction[i]*k + fn(i+1, k+1), fn(i+1, k))
return fn(0, 1) | reducing-dishes | [Python3] dp | ye15 | 1 | 76 | reducing dishes | 1,402 | 0.72 | Hard | 21,006 |
https://leetcode.com/problems/reducing-dishes/discuss/2835613/Python-3oror-Easy-to-understandoror-Beginner-Friendly | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort()
l=len(satisfaction)
lst=[i+1 for i in range(l)]
res=0
i=0
while(i<l):
temp=0
k=i
for j in range(1,l-i+1):
temp = temp + satisfaction[k]*j
k+=1
res=max(res,temp)
i+=1
return res | reducing-dishes | Python 3✅|| Easy to understand✌🏼|| Beginner Friendly | jhadevansh0809 | 0 | 1 | reducing dishes | 1,402 | 0.72 | Hard | 21,007 |
https://leetcode.com/problems/reducing-dishes/discuss/2790801/Solving-from-the-scratch | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
if max(satisfaction) <= 0 : return(0)
# elif min(satisfaction) >= 0 : return(satisfaction.sort())
s_sorted = satisfaction.copy()
s_sorted.sort()
i_positive = 0
print(s_sorted)
for i in s_sorted:
if i >= 0: break
else:
i_positive = i_positive + 1
print(i_positive)
max_sum = 0
len_negative = len(s_sorted[:i_positive])
for i in range(len_negative+1):
temp = 0
k = 1
for j in s_sorted[i_positive-i:]:
temp = temp + j*k
k = k + 1
if max_sum<temp: max_sum = temp
return(max_sum) | reducing-dishes | Solving from the scratch | JulyMarc | 0 | 3 | reducing dishes | 1,402 | 0.72 | Hard | 21,008 |
https://leetcode.com/problems/reducing-dishes/discuss/2690997/Clean-Concise-Python3-or-Top-Down-and-Bottom-Up-or-Fully-Explained | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
n = len(satisfaction)
satisfaction.sort()
@cache
def dp(dish, time):
if dish == n:
return 0
cook = satisfaction[dish] * (time + 1) + dp(dish + 1, time + 1)
skip = dp(dish + 1, time)
return max(cook, skip)
return dp(0, 0) | reducing-dishes | Clean, Concise Python3 | Top Down & Bottom Up | Fully Explained | ryangrayson | 0 | 5 | reducing dishes | 1,402 | 0.72 | Hard | 21,009 |
https://leetcode.com/problems/reducing-dishes/discuss/2690997/Clean-Concise-Python3-or-Top-Down-and-Bottom-Up-or-Fully-Explained | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
n = len(satisfaction)
satisfaction.sort()
dp = [0] * (n + 1)
for dish in range(n - 1, -1, -1):
nxt_dp = [0] * (dish + 1)
for time in range(dish, -1, -1):
cook = satisfaction[dish] * (time + 1) + dp[time + 1]
skip = dp[time]
nxt_dp[time] = max(cook, skip)
dp = nxt_dp
return dp[0] | reducing-dishes | Clean, Concise Python3 | Top Down & Bottom Up | Fully Explained | ryangrayson | 0 | 5 | reducing dishes | 1,402 | 0.72 | Hard | 21,010 |
https://leetcode.com/problems/reducing-dishes/discuss/2645271/Simple-python-code-with-explanation | class Solution:
def maxSatisfaction(self, sat):
#sort the satisfaction list
sat= sorted(sat)
#create an array(arr) store 0 in it
arr = [0]
#iterate over the elements in satisfaction list
for i in range(len(sat)):
#create a variable time and assign 1 to it
time = 1
#creste a variable to store the sum of each iteration
arr2 = 0
#iterate over the elements from current to last index
for j in range(i,len(sat)):
#add the curr *time value
arr2 += (time*sat[j])
#increse the time value by 1
time +=1
#add the value(arr2) in arr
arr.append(arr2)
#reset the arr2 value to 0
arr2 = 0
#reset the time value to 1
time = 1
#return the maximum value in arr
return max(arr) | reducing-dishes | Simple python code with explanation | thomanani | 0 | 13 | reducing dishes | 1,402 | 0.72 | Hard | 21,011 |
https://leetcode.com/problems/reducing-dishes/discuss/2592263/Very-short-Python-solution-with-memoization-explanation-provided. | class Solution:
@cache
def dp(self, time, dish):
if time > len(self.satisfaction) or dish >= len(self.satisfaction):
return 0
return max(self.dp(time + 1, dish + 1) + time * self.satisfaction[dish], # To prepare the dish
self.dp(time, dish + 1)) # To skip the dish
def maxSatisfaction(self, satisfaction: List[int]) -> int:
self.satisfaction = sorted(satisfaction)
return self.dp(1, 0) | reducing-dishes | Very short Python solution with memoization, explanation provided. | metaphysicalist | 0 | 40 | reducing dishes | 1,402 | 0.72 | Hard | 21,012 |
https://leetcode.com/problems/reducing-dishes/discuss/2557110/Python-or-Easy-to-understand | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
sort = sorted(satisfaction, reverse = True)
positive = 0
counter = 0
for i in sort:
if positive+i>0:
positive+=i
counter+=1
sum = 0
for i in range(counter):
sum+=sort[i]*(counter-i)
return sum | reducing-dishes | ✅ Python | Easy to understand | KateIV | 0 | 198 | reducing dishes | 1,402 | 0.72 | Hard | 21,013 |
https://leetcode.com/problems/reducing-dishes/discuss/2481898/easy-python-solution | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort()
value_list = []
for i in range(len(satisfaction)) :
subArray = satisfaction[i:]
new_val = sum([((j+1)*subArray[j]) for j in range(len(subArray))])
# print(new_val, subArray)
value_list.append(new_val)
if max(value_list) > 0 :
return max(value_list)
return 0 | reducing-dishes | easy python solution | sghorai | 0 | 75 | reducing dishes | 1,402 | 0.72 | Hard | 21,014 |
https://leetcode.com/problems/reducing-dishes/discuss/1819750/python-n(logn)-different-approach | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort()
# satisfaction = [-9, -8, -1, 0, 5]
cumulative = []
temp = 0
for i in satisfaction[::-1]:
temp += i
cumulative.append(temp)
# This step is not required. For understanding, I have added this.
cumulative = cumulative[::-1]
# cumulative = [-11, -3, 4, 5, 5]
return sum([i for i in cumulative if i>0]) | reducing-dishes | python n(logn) different approach | sriharsha_revadi | 0 | 65 | reducing dishes | 1,402 | 0.72 | Hard | 21,015 |
https://leetcode.com/problems/reducing-dishes/discuss/1666000/Simple-python-soln | class Solution:
def maxSatisfaction(self, st: List[int]) -> int:
st.sort()
if st[-1]<=0:
return 0
maxs=c=0
while c < len(st):
curr = 0
for i, k in list(enumerate(st)):
curr += k *(i+1)
st = st[c+1:]
maxs = max(maxs, curr)
return maxs | reducing-dishes | Simple python soln | gamitejpratapsingh998 | 0 | 55 | reducing dishes | 1,402 | 0.72 | Hard | 21,016 |
https://leetcode.com/problems/reducing-dishes/discuss/1556778/Python3-Simple-Solution | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort()
result = 0
for time in range(len(satisfaction)):
result += (time + 1) * satisfaction[time]
for shift in range(len(satisfaction)):
sum_num = sum(satisfaction[shift:])
if sum_num < 0:
result -= sum_num
else:
break
return result | reducing-dishes | [Python3] Simple Solution | JingMing_Chen | 0 | 129 | reducing dishes | 1,402 | 0.72 | Hard | 21,017 |
https://leetcode.com/problems/reducing-dishes/discuss/859059/Intuitive-approach-by-sorting-satisfaction-and-using-two-loop-(O(n2)) | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction = sorted(satisfaction)
if satisfaction[-1] <= 0:
return 0
def svalue(s, sat_list=satisfaction):
sv = 0
for i, v in enumerate(sat_list[s:]):
sv += v * (i+1)
return sv
max_sv = 0
for i in range(len(satisfaction)):
sv = svalue(i)
if sv > max_sv:
max_sv = sv
return max_sv | reducing-dishes | Intuitive approach by sorting satisfaction and using two loop (O(n^2)) | puremonkey2001 | 0 | 86 | reducing dishes | 1,402 | 0.72 | Hard | 21,018 |
https://leetcode.com/problems/reducing-dishes/discuss/600287/PYTHON-3-75-Time-or-100-Space | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort()
result , current_sum = 0 , 0
while satisfaction and satisfaction[-1] + current_sum > 0:
current_sum += satisfaction.pop()
result += current_sum
return result | reducing-dishes | [PYTHON 3] 75% Time | 100% Space | mohamedimranps | 0 | 85 | reducing dishes | 1,402 | 0.72 | Hard | 21,019 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1041468/Python3-simple-solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
l = []
while sum(l) <= sum(nums):
l.append(nums.pop())
return l | minimum-subsequence-in-non-increasing-order | Python3 simple solution | EklavyaJoshi | 9 | 297 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,020 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2330458/Solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
if (len(nums) == 1):
return nums
nums.sort()
count = 0
num = []
l = len(nums)
for i in range(1,l+1):
count += nums[-i]
num.append(nums[-i])
if count > sum(nums[:l-i]):
return (num) | minimum-subsequence-in-non-increasing-order | Solution | fiqbal997 | 2 | 68 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,021 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2641422/Python-Solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
ans=[]
nums.sort()
while sum(nums)>sum(ans):
ans.append(nums.pop())
if sum(nums)==sum(ans):
ans.append(nums.pop())
return ans | minimum-subsequence-in-non-increasing-order | Python Solution | Sneh713 | 1 | 72 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,022 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2359612/Python-oror-O(n)-Solution-oror-Easily-understandable | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
totalSum=sum(nums)
currSum=0
seq=[]
for i in range(len(nums)-1,-1,-1):
currSum+=nums[i]
seq.append(nums[i])
if(currSum>totalSum-currSum):
return seq
return seq | minimum-subsequence-in-non-increasing-order | Python || O(n) Solution || Easily understandable | ausdauerer | 1 | 35 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,023 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1526095/Sort-and-compute-sub-sum-94-speed | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
total, sub_sum = sum(nums), 0
nums.sort(reverse=True)
for i, n in enumerate(nums):
sub_sum += n
if 2 * sub_sum > total:
return nums[:i + 1]
return nums | minimum-subsequence-in-non-increasing-order | Sort and compute sub sum, 94% speed | EvgenySH | 1 | 125 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,024 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1148138/Python3-Brute-Force-Solution-(4-lines) | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
sumi = []
while sum(sumi) <= sum(nums):
sumi.append(nums.pop(nums.index(max(nums))))
return sumi | minimum-subsequence-in-non-increasing-order | [Python3] Brute Force Solution (4 lines) | PleaseDontHelp | 1 | 63 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,025 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1067815/Python3-O(n)-solution-faster-than-99.63-solutions | class Solution:
def minSubsequence(self, nums):
hashTable = [0] * 101
sumVal, hashIndex = 0, 100
ans = []
for val in nums:
sumVal += val
hashTable[val] += 1
currVal = sumVal // 2
while(hashIndex > 0):
if hashTable[hashIndex] == 0:
hashIndex -= 1
continue
if currVal >= 0:
ans.append(hashIndex)
currVal -= hashIndex
hashTable[hashIndex] -= 1
if currVal < 0:
return ans | minimum-subsequence-in-non-increasing-order | Python3 O(n) solution faster than 99.63% solutions | danieltseng | 1 | 92 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,026 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2797967/Python-O(N)-time-and-O(1)-space | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort(reverse=True)
total_sum = sum(nums)
curr_total = 0
for i in range(len(nums)):
curr_total+=nums[i]
if curr_total > total_sum-curr_total:
return nums[:i+1] | minimum-subsequence-in-non-increasing-order | Python O(N) time and O(1) space | Rajeev_varma008 | 0 | 1 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,027 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2767136/Python-basic-solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
ans=[]
while len(nums) != 0:
cur=nums.pop()
ans.append(cur)
if sum(ans) > sum(nums):
break
return ans | minimum-subsequence-in-non-increasing-order | Python basic solution | beingab329 | 0 | 7 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,028 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2614409/iterative-using-sort | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
# get the total sum of nums
# sort nums in descending order using sort()
# iterate nums using a sliding window and run trials
# try to see if the first number is greater than the remaining sum
# if not, increase the window size
# since nums is already sorted descending, return the slice
# time O(n) space O(1)
nums.sort(reverse=True)
n = len(nums)
total, remaining = 0, sum(nums)
for i in range(n):
total += nums[i]
remaining -= nums[i]
if total > remaining:
return nums[:i + 1] | minimum-subsequence-in-non-increasing-order | iterative using sort | andrewnerdimo | 0 | 9 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,029 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2547583/python-solution-94.19-faster | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
sum_all_nums = sum(nums[::])
greatest = []
count = 0
if len(nums) == 1:
return nums
if len(nums) == 2 and nums[0] == nums[1]:
return nums
for _ in range(1, len(nums)):
diff = sum_all_nums - nums[-1]
greatest.append(nums[-1])
count += nums[-1]
sum_all_nums -= nums[-1]
nums.pop()
if diff == count and len(nums) == 2:
return nums
if diff >= count:
continue
return greatest | minimum-subsequence-in-non-increasing-order | python solution 94.19% faster | samanehghafouri | 0 | 35 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,030 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2522260/Simple-Python-solution-using-sorting | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort(reverse=True)
if len(nums) == 1:
return nums
for i in range(1,len(nums)):
if sum(nums[:i]) > sum(nums[i:]):
return nums[:i]
return nums | minimum-subsequence-in-non-increasing-order | Simple Python solution using sorting | aruj900 | 0 | 16 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,031 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2345922/Minimum-Subsequence-in-Non-Increasing-Order | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
n = len(nums)
x = sum(nums)
tempSum = 0
y = []
for i in range(n):
for j in range(n-i - 1):
if nums[j]>nums[j+1]:
m = nums[j]
nums[j]= nums[j+1]
nums[j+1]=m
x-= nums[n-i-1]
tempSum+=nums[n-i-1]
y.append( nums[n-i-1])
if tempSum > x :
break
return y | minimum-subsequence-in-non-increasing-order | Minimum Subsequence in Non-Increasing Order | dhananjayaduttmishra | 0 | 8 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,032 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2152683/python-3-oror-simple-greedy-solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
target = sum(nums) // 2 + 1
nums.sort(reverse=True)
res = []
for num in nums:
res.append(num)
target -= num
if target <= 0:
break
return res | minimum-subsequence-in-non-increasing-order | python 3 || simple greedy solution | dereky4 | 0 | 57 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,033 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/2113228/Easiest-Python-Code | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
a = sum(nums)
l = []
for i in range(len(nums)-1,-1,-1):
a = a - nums[i]
l.append(nums[i])
if sum(l)>a:
break
return l | minimum-subsequence-in-non-increasing-order | Easiest Python Code | prernaarora221 | 0 | 46 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,034 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1941246/easy-python-code | class Solution:
def sum(l):
add = 0
for i in l:
add+=i
return add
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort(reverse=True)
for i in range(len(nums)):
if sum(nums[:i+1]) > sum(nums[i+1:]):
return nums[:i+1] | minimum-subsequence-in-non-increasing-order | easy python code | dakash682 | 0 | 48 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,035 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1865518/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
k = 1
nums.sort(reverse = True)
while sum(nums[:k]) <= sum(nums[k:]):
k+=1
return nums[:k] | minimum-subsequence-in-non-increasing-order | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 52 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,036 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1831820/4-Lines-Python-Solution-oror-30-Faster-oror-Memory-less-than-99 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
if len(set(nums))==1: return nums
nums.sort(reverse=True)
for i in range(1,len(nums)):
if sum(nums[:i])>sum(nums[i:]): return nums[:i] | minimum-subsequence-in-non-increasing-order | 4-Lines Python Solution || 30% Faster || Memory less than 99% | Taha-C | 0 | 33 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,037 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1831820/4-Lines-Python-Solution-oror-30-Faster-oror-Memory-less-than-99 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
if len(set(nums))==1: return nums
nums.sort(reverse=True) ; res=0 ; sm=sum(nums)//2
for i in range(len(nums)):
res+=nums[i]
if res>sm: return nums[:i+1] | minimum-subsequence-in-non-increasing-order | 4-Lines Python Solution || 30% Faster || Memory less than 99% | Taha-C | 0 | 33 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,038 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1743052/Python-dollarolution-(faster-than-98-less-mem-use-than-99) | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums = sorted(nums,reverse = True)
s, su = sum(nums)//2, 0
for i in range(len(nums)):
su += nums[i]
if su > s:
return nums[0:i+1] | minimum-subsequence-in-non-increasing-order | Python $olution (faster than 98%, less mem use than 99%) | AakRay | 0 | 100 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,039 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1570421/Python3-Java-%3A-Easy-Solution-oror-Sort-oror-PriorityQueue | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
total = sum(nums)
nums.sort()
count = 0
res = []
for i in reversed(nums):
count += i
total -= i
res.append(i)
if count > total:
return res
return res | minimum-subsequence-in-non-increasing-order | [Python3] / [Java] : Easy Solution || Sort || PriorityQueue | abhijeetmallick29 | 0 | 51 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,040 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1337128/Simple-Python-Solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
temp=[]
nums.sort(reverse=True)
for i in range(len(nums)):
if sum(nums[:i+1]) > sum(nums[i+1:]):
temp.append(nums[:i+1])
return temp[0] | minimum-subsequence-in-non-increasing-order | Simple Python Solution | sangam92 | 0 | 46 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,041 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1284663/Python-Solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
n = len(nums)
if n == 1:
return nums
else:
i, j, total = 0, 0, sum(nums)
half = total/2
nums.sort(reverse=True)
curr_sum = sum(nums[i:j+1])
while j < n:
if curr_sum <= half:
j += 1
curr_sum += nums[j]
elif curr_sum > half:
while curr_sum > half:
if curr_sum - nums[i] <= half:
break
curr_sum -= nums[i]
i += 1
break
return nums[i:j+1] | minimum-subsequence-in-non-increasing-order | Python Solution | paramvs8 | 0 | 88 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,042 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1271643/greedy-cumulative-sum-radix-sort-O(1)-space-beats-98 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
subseqs, cp = [], sorted(nums)
output_sum, total = 0, sum(nums)
while output_sum <= total:
total -= cp[-1]
output_sum += cp[-1]
subseqs.append(cp.pop())
return subseqs | minimum-subsequence-in-non-increasing-order | greedy cumulative sum, radix sort, O(1) space beats 98% | rsha256 | 0 | 39 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,043 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1271643/greedy-cumulative-sum-radix-sort-O(1)-space-beats-98 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
subseqs = []
output_sum, total = 0, sum(nums)
while output_sum <= total:
total -= nums[-1]
output_sum += nums[-1]
subseqs.append(nums.pop())
return subseqs | minimum-subsequence-in-non-increasing-order | greedy cumulative sum, radix sort, O(1) space beats 98% | rsha256 | 0 | 39 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,044 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1271643/greedy-cumulative-sum-radix-sort-O(1)-space-beats-98 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
nums = deque(nums)
i, output_sum, total = len(nums)-1, 0, sum(nums)
while output_sum <= total:
total -= nums[i]
output_sum += nums[i]
i -= 1
for _ in range(i+1):
nums.popleft()
return list(reversed(nums)) | minimum-subsequence-in-non-increasing-order | greedy cumulative sum, radix sort, O(1) space beats 98% | rsha256 | 0 | 39 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,045 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1271643/greedy-cumulative-sum-radix-sort-O(1)-space-beats-98 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
i, output_sum, total = len(nums)-1, 0, sum(nums)
while output_sum <= total:
total -= nums[i]
output_sum += nums[i]
i -= 1
del nums[:i+1]
return reversed(nums) | minimum-subsequence-in-non-increasing-order | greedy cumulative sum, radix sort, O(1) space beats 98% | rsha256 | 0 | 39 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,046 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1271643/greedy-cumulative-sum-radix-sort-O(1)-space-beats-98 | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
subseqs = []
output_sum, total = 0, sum(nums)
ctr = Counter(nums)
for x in range(100, 0, -1): # go from 100 to 0, the range of nums[i], with step of -1
while ctr[x]:
total -= x
output_sum += x
subseqs.append(x)
if output_sum > total:
return subseqs
ctr[x] -= 1
return subseqs | minimum-subsequence-in-non-increasing-order | greedy cumulative sum, radix sort, O(1) space beats 98% | rsha256 | 0 | 39 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,047 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1265352/easy-or-beats-93.6-or | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
y=sum(nums)
p=[]
u=0
while True:
a=nums.pop()
p.append(a)
u+=a
if u > y-u:
return sorted(p,reverse=True) | minimum-subsequence-in-non-increasing-order | easy | beats 93.6% | | chikushen99 | 0 | 64 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,048 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/969258/Python3-Easy-solution-with-(and-without)-dictionary | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
total = sum(nums)
nums = sorted(nums, reverse=True)
for i in range(1,len(nums)+1):
new_sum = sum(nums[:i]) #calculate sum at every index.. this can be optimized by saving current sum and adding up next elements like in next solution
if total - new_sum < new_sum: #compare calculated sum with total sum
return nums[:i] | minimum-subsequence-in-non-increasing-order | [Python3] Easy solution with (and without) dictionary | sahilrajpal85 | 0 | 82 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,049 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/969258/Python3-Easy-solution-with-(and-without)-dictionary | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
d = dict()
nums = sorted(nums, reverse=True)
val, total_sum = 0, sum(nums)
for i in range(1,len(nums)+1):
val += nums[i-1]
d[i] = val
for key, value in d.items():
if total_sum - value < value:
return nums[:key] | minimum-subsequence-in-non-increasing-order | [Python3] Easy solution with (and without) dictionary | sahilrajpal85 | 0 | 82 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,050 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/859683/Python3-sort | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
ans = []
total, sm = sum(nums), 0
for x in sorted(nums, reverse=True):
ans.append(x)
sm += x
if sm > total - sm: return ans | minimum-subsequence-in-non-increasing-order | [Python3] sort | ye15 | 0 | 58 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,051 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/849580/python3-code-for-begginers | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
nums.reverse()
l=[]
for i in range(len(nums)):
l.append(nums[i])
if sum(l)>sum(nums[(i+1):]):
return l | minimum-subsequence-in-non-increasing-order | python3 code for begginers | aayushchaudhary | 0 | 35 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,052 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/683790/Python-solution%3A-using-sum-only-once-and-using-the-same-input-array-to-return | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort(reverse=True)
total_sum = sum(nums)
curr_sum = 0
for i in range(len(nums)):
curr_sum += nums[i]
if total_sum - curr_sum < curr_sum:
break
return nums[:i+1] | minimum-subsequence-in-non-increasing-order | Python solution: using sum only once and using the same input array to return | Amit_Bhatt | 0 | 73 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,053 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/579995/Simple-Python-Solution | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
answer=[]
if len(nums)==1:
answer.append(nums[0])
return answer
total=sum(nums)
n=len(nums)
nums.sort()
if total-nums[n-1]<nums[n-1]:
answer.append(nums[n-1])
return answer
sum1=0
count=0
for i in range(len(nums)-1, -1,-1):
count+=1
# print(count)
sum1+=nums[i]
if sum1>(total-sum1):
break
l=nums[n-count:]
print(l)
l=l[::-1]
return l | minimum-subsequence-in-non-increasing-order | Simple Python Solution | Ayu-99 | 0 | 42 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,054 |
https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/565103/Python-O(-n-lg-n-)-by-sorting.-w-Hint | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
# make nums sorted in descending order
nums.sort( reverse = True )
summation = sum( nums )
sequence, partial_sum = [], 0
# keep picking number from largest one, until partial sum is larger than (summation / 2)
for number in nums:
partial_sum += number
sequence.append( number )
if partial_sum > summation / 2:
break
return sequence | minimum-subsequence-in-non-increasing-order | Python O( n lg n ) by sorting. [w/ Hint] | brianchiang_tw | 0 | 129 | minimum subsequence in non increasing order | 1,403 | 0.721 | Easy | 21,055 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/2809472/Python3-Solution-or-One-Line | class Solution:
def numSteps(self, s):
return len(s) + s.rstrip('0').count('0') + 2 * (s.count('1') != 1) - 1 | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | ✔ Python3 Solution | One Line | satyam2001 | 1 | 98 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,056 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/1504369/Python3-Intuitive-O(N)-solution-faster-than-99-explained | class Solution:
def numSteps(self, s: str) -> int:
found_one = False
increments = 0
for num in s[1:][::-1]:
if num == '1':
found_one |= True
elif found_one:
increments += 1
if found_one:
increments += 1
return len(s) + increments
else:
return len(s) - 1 | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | [Python3] Intuitive O(N) solution faster than 99% explained | Skaiir | 1 | 328 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,057 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/2817501/the-fastest-run-time-97 | class Solution:
def numSteps(self, s: str) -> int:
s=int(s,2);k=0
while s!=1:
k+=1
if s%2==1:
s+=1
else:
s//=2
return k | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | the fastest run time 97% | Samandar_Abduvaliyev | 0 | 4 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,058 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/2220060/Python-solution-oror-handle-carry-with-string-oror-does-not-convert-to-int | class Solution:
def numSteps(self, s: str) -> int:
if s == '1': return 0
s = [a for a in str(s)]
count = 0
# print(s)
while 1 < len(s):
if s[-1] == '1':
# add 1
s[-1] = '0'
carry = True
# check from the end if need to carry forward
# or the carry can be 'absorb' by a zero
for i in range(len(s) - 2, -1, -1):
if carry == True:
if s[i] == '1':
s[i] = '0'
carry = True
else:
s[i] = '1'
carry = False
break
# if there is still carry at the end
# prepend a '1' at the beginning
if carry:
s.insert(0, '1')
else:
# divide it by 2
s = s[:-1]
count += 1
# print(s)
if s == ['0']: return null
return count | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | Python solution || handle carry with string || does not convert to int | lamricky11 | 0 | 125 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,059 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/1757784/Python3-Bit-manipulation | class Solution:
def numSteps(self, s: str) -> int:
ans = 0
s = int(s,2)
while s > 1:
ans += 1
s = s + 1 if s & 1 else s >> 1
return ans | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | [Python3] Bit manipulation | keehuachin | 0 | 173 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,060 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/1178609/Python3 | class Solution:
def numSteps(self, s: str) -> int:
count=0
n=int(s,2)
while(n!=1):
if n%2==0:
n=n//2
else:
n+=1
count+=1
return count | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | Python3 | samarthnehe | 0 | 224 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,061 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/1156705/simple-and-easy-to-understand-python | class Solution:
def numSteps(self, s: str) -> int:
steps = 0
n = int(s,2)
while n!=1:
if n%2==0:
n = n//2
else:
n+=1
steps+=1
return steps | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | simple and easy to understand python | pheobhe | 0 | 105 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,062 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/1123878/Python3-simulation | class Solution:
def numSteps(self, s: str) -> int:
n = int(s, 2)
ans = 0
while n > 1:
ans += 1
if n&1: n += 1
else: n //= 2
return ans | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | [Python3] simulation | ye15 | 0 | 84 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,063 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/983732/python3-count-ones-from-LSB | class Solution:
def numSteps(self, s: str) -> int:
# bit length of string indicates do ops on string
# carry addition if number is odd
# shift right if number is even
# rather than do ops directly, look for pattern
# going through string from LSB to MSB
# if seeing "1", increment ones count
# if seeing "0" without "1" count, inc result directly
# if seeing "0" with "1" count: add (ones + 1) to res, set ones to 1
# e.g., add 1, shift "ones" number of times
# if ones > 1 after traversal, add (ones + 1) to res
# O(S) time and O(1) space
res, ones = 0, 0
for c in reversed(s):
if c == "1": ones += 1
if c == "0":
if not ones: res += 1
else:
res += ones + 1
ones = 1
if ones > 1: res += ones + 1
return res | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | python3 - count ones from LSB | dachwadachwa | 0 | 102 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,064 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/718152/Python3-O(N)-Solution-Bit-Manipulation | class Solution:
def numSteps(self, s: str) -> int:
n, steps = [int(i) for i in s], 0
while (n != [1]):
if n[-1] == 0:
# for even
n = n[:-1]
else:
# for odd
found = False
for i in range(len(n)-1, -1, -1):
if (n[i] == 1):
n[i] = 0
else:
n[i] = 1
found = True
break
if not found:
n = [1] + n
steps += 1
return steps
``` | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | [Python3] O(N) Solution, Bit Manipulation | uds5501 | 0 | 163 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,065 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/564736/Python-O(n)-sol-by-simulation.-w-Comment | class Solution:
def numSteps(self, s: str) -> int:
# convert binary string to integer
num, step = int(s,2), 0
while num != 1:
if num & 1 :
# odd number
num += 1
else:
# even number
num >>= 1
step += 1
return step | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | Python O(n) sol by simulation. [w/ Comment] | brianchiang_tw | 0 | 220 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,066 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/564736/Python-O(n)-sol-by-simulation.-w-Comment | class Solution:
def numSteps(self, s: str) -> int:
# convert binary string to integer
num, step = int(s, 2), 0
while(num!=1):
# update num with conditional expression
num = num + 1 if num & 1 else num >> 1
step += 1
return step | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | Python O(n) sol by simulation. [w/ Comment] | brianchiang_tw | 0 | 220 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,067 |
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/579845/python-100time-100-mem | class Solution:
def numSteps(self, s: str) -> int:
ans=0
while s!='1':
if s[-1]=='1':
s=bin(int(s,2)+1)[2:]
else:
s=s[:-1]
ans+=1
return ans | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | python 100%time 100% mem | saumitrawork | -2 | 254 | number of steps to reduce a number in binary representation to one | 1,404 | 0.522 | Medium | 21,068 |
https://leetcode.com/problems/longest-happy-string/discuss/1226968/Python-9-line-greedy-solution-by-using-Counter | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
count = collections.Counter({'a':a, 'b':b, 'c':c})
res = ['#']
while True:
(a1, _), (a2, _) = count.most_common(2)
if a1 == res[-1] == res[-2]:
a1 = a2
if not count[a1]:
break
res.append(a1)
count[a1] -= 1
return ''.join(res[1:]) | longest-happy-string | [Python] 9-line greedy solution by using Counter | licpotis | 5 | 524 | longest happy string | 1,405 | 0.574 | Medium | 21,069 |
https://leetcode.com/problems/longest-happy-string/discuss/569902/Simple-and-short-python-code(16-ms-faster-than-92.72) | class Solution(object):
def longestDiverseString(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: str
"""
r = ''
d = {'a':a, 'b':b, 'c':c}
sign = [-1, 1]
for i in range(a+b+c):
# exclude the last character
cmp_key = lambda x: d[x]* sign[x!=r[i-1]]
# if r is good
if i<2 or r[i-1]!=r[i-2]:
cmp_key = d.get
c = max(d, key=cmp_key)
if d[c] == 0:
break
r += c
d[c] -=1
return r | longest-happy-string | Simple and short python code(16 ms, faster than 92.72%) | nkjancy | 2 | 704 | longest happy string | 1,405 | 0.574 | Medium | 21,070 |
https://leetcode.com/problems/longest-happy-string/discuss/2303833/Python-90-Faster-Heap | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
map = {'a':a,'b':b,'c':c}
heap = []
for key,val in map.items():
if val!=0:
heap.append((-val,key))
heapify(heap)
ans = ''
while heap:
count,char = heappop(heap)
if len(ans)>1 and ans[-1]==ans[-2]==char:
if heap:
count2,char2 = heappop(heap)
heappush(heap,(count,char))
ans+=char2
if count2!=-1:
heappush(heap,(count2+1,char2))
else:
ans+=char
if count!=-1:
heappush(heap,(count+1,char))
return(ans) | longest-happy-string | Python 90% Faster Heap | Abhi_009 | 1 | 292 | longest happy string | 1,405 | 0.574 | Medium | 21,071 |
https://leetcode.com/problems/longest-happy-string/discuss/1644806/Simple-and-intuitive-python-solution | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
substr = ""
options = {
"a": a,
"b": b,
"c": c
}
def is_valid_substr(x):
if substr[-2:] + x not in {'aaa', 'bbb', 'ccc'}:
return True
return False
while options["a"] > 0 or options["b"] > 0 or options["c"] > 0:
max_order = {
k: v
for k, v in sorted(
options.items(), key=lambda item: -item[1])
}
for k, v in max_order.items():
if is_valid_substr(k) and v > 0:
options[k] -= 1
substr += k
break
else:
break
return substr | longest-happy-string | Simple and intuitive python solution | Arvindn | 1 | 407 | longest happy string | 1,405 | 0.574 | Medium | 21,072 |
https://leetcode.com/problems/longest-happy-string/discuss/1123890/Python3-greedy | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
pq = [] # max-heap
for x, c in zip((a, b, c), "abc"):
if x: heappush(pq, (-x, c))
ans = []
while pq:
n, x = heappop(pq)
if ans[-2:] != [x, x]:
ans.append(x)
if n+1: heappush(pq, (n+1, x))
else:
if not pq: break
nn, xx = heappop(pq)
ans.append(xx)
if nn+1: heappush(pq, (nn+1, xx))
heappush(pq, (n, x))
return "".join(ans) | longest-happy-string | [Python3] greedy | ye15 | 1 | 236 | longest happy string | 1,405 | 0.574 | Medium | 21,073 |
https://leetcode.com/problems/longest-happy-string/discuss/2712804/Python-heap | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
queue = []
if a != 0:
queue.append([-a,"a"])
if b != 0:
queue.append([-b,"b"])
if c != 0:
queue.append([-c,"c"])
heapq.heapify(queue)
result = ""
cnt = 0
n,pre = queue[0]
while queue:
num,cur = heapq.heappop(queue)
if pre != cur:
cnt = 1
result += cur
pre = cur
else:
if cnt == 2:
n,pre = num,cur
if len(queue) >= 1:
num,cur = heapq.heappop(queue)
result += cur
heapq.heappush(queue,[n,pre])
pre = cur
else:
break
else:
cnt += 1
result += cur
if num+1 != 0:
heapq.heappush(queue,[num+1,cur])
return result | longest-happy-string | Python heap | Bettita | 0 | 12 | longest happy string | 1,405 | 0.574 | Medium | 21,074 |
https://leetcode.com/problems/longest-happy-string/discuss/2675215/Python-Solution-! | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
res = ''
max_heap = []
for char, count in [('a', -a), ('b', -b), ('c', -c)]:
if count:
heapq.heappush(max_heap, (count, char))
while max_heap:
count, char = heapq.heappop(max_heap)
if len(res) > 1 and res[-1] == res[-2] == char:
if not max_heap:
break
count2, char2 = heapq.heappop(max_heap)
res += char2
count2 += 1
if count2:
heapq.heappush(max_heap, (count2, char2))
else:
res += char
count += 1
if count:
heapq.heappush(max_heap, (count, char))
return res | longest-happy-string | Python Solution ! | asambatu | 0 | 18 | longest happy string | 1,405 | 0.574 | Medium | 21,075 |
https://leetcode.com/problems/longest-happy-string/discuss/2546081/Python3-or-Priority-Queue-approach | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
pq=[]
if a>0:
heappush(pq,(-a,'a'))
if b>0:
heappush(pq,(-b,'b'))
if c>0:
heappush(pq,(-c,'c'))
ans=[]
while pq:
first,letter_1=heappop(pq)
if len(ans)>=2 and ans[-1]==letter_1 and ans[-2]==letter_1:
if not pq:
return ''.join(ans)
else:
second,letter_2=heappop(pq)
ans.append(letter_2)
second+=1
heappush(pq,(second,letter_2)) if second!=0 else 0
heappush(pq,(first,letter_1))
continue
ans.append(letter_1)
first+=1
heappush(pq,(first,letter_1)) if first!=0 else 0
return ''.join(ans) | longest-happy-string | [Python3] | Priority Queue approach | swapnilsingh421 | 0 | 62 | longest happy string | 1,405 | 0.574 | Medium | 21,076 |
https://leetcode.com/problems/longest-happy-string/discuss/2173448/Python3-Simple-heap-solution-with-comments | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
## RC ##
## APPROACH : Priority Queue ##
import heapq
pq = []
for idx, val in enumerate([a, b, c]):
if val == 0: continue
pq.append((-val, chr(97 + idx)))
heapq.heapify(pq)
res = ""
while(pq):
next = heapq.heappop(pq)
# If you receive the same letter again from heap pop
# 1. pop once more (next2) and push the res[-1] letter i.e next
# 2. use only one character ( coz you have so many next[1] characters, minimize others)
if res and res[-1] == next[1]:
if not pq:
return res
next2 = heapq.heappop(pq)
heapq.heappush(pq, next)
res += next2[1]
if -1 * next2[0] > 1:
heapq.heappush(pq, (next2[0] + 1, next2[1]))
continue
# you 2 characters if you have more than 2 chars
if -1 * next[0] >= 2:
res += next[1] * 2
if -1 * next[0] > 2:
heapq.heappush(pq, (next[0] + 2, next[1]))
continue
if -1 * next[0] == 1:
res += next[1]
return res | longest-happy-string | [Python3] Simple heap solution with comments | 101leetcode | 0 | 194 | longest happy string | 1,405 | 0.574 | Medium | 21,077 |
https://leetcode.com/problems/longest-happy-string/discuss/2019507/Simple-python-solution | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
char_dict = {'a': a, 'b': b, 'c': c}
happy_str = ""
while char_dict['a'] + char_dict['b'] + char_dict['c'] > 0:
max_char = max(char_dict, key=char_dict.get)
if len(happy_str) > 1 and (happy_str[-1] == happy_str[-2] == max_char):
temp_dict = char_dict.copy()
del temp_dict[max_char]
max_char = max(temp_dict, key=temp_dict.get)
if char_dict[max_char] == 0:
return happy_str
happy_str += max_char
char_dict[max_char] -= 1
return happy_str | longest-happy-string | Simple python solution | ariksa | 0 | 221 | longest happy string | 1,405 | 0.574 | Medium | 21,078 |
https://leetcode.com/problems/longest-happy-string/discuss/1835030/Python-Max-Heap-Stack | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
# Use max heap to always add the char with highest count to the result first
heap = [(-a, 'a'), (-b, 'b'), (-c, 'c')]
heapify(heap)
res = []
while heap and heap[0][0] < 0: # Handle 0 count here
item = heappop(heap)
count, char = -item[0], item[1]
# There are NOT two of the same chars before
while count > 0 and (len(res) < 2 or res[-1] != char or res[-2] != char):
res.append(char)
count -= 1
if len(res) >= 2 and res[-1] == char and res[-2] == char:
# There are two of the same chars before
if heap and heap[0][0] < 0:
item2 = heappop(heap)
count2, char2 = -item2[0], item2[1]
res.append(char2)
count2 -= 1
heappush(heap, (-count2, char2))
else:
break
# Add it back to the heap
heappush(heap, (-count, char))
return "".join(res) | longest-happy-string | Python Max Heap Stack | hitpoint6 | 0 | 67 | longest happy string | 1,405 | 0.574 | Medium | 21,079 |
https://leetcode.com/problems/longest-happy-string/discuss/639802/Python3-greedy-solution-Longest-Happy-String | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
ans = ''
remain = {letter: cnt for letter, cnt in zip('abc', [a, b, c]) if cnt}
count = 0
while remain and not (count == 2 and ans[-1] in remain and len(remain) == 1):
candidates = sorted(
filter(lambda x: x != ans[-1] if count == 2 else True, remain.keys()),
key=lambda x:-remain[x])
ans += candidates[0]
remain[ans[-1]] -= 1
if not remain[ans[-1]]:
del remain[ans[-1]]
count = 2 if len(ans) > 1 and ans[-1] == ans[-2] else 1
return ans | longest-happy-string | Python3 greedy solution - Longest Happy String | r0bertz | 0 | 437 | longest happy string | 1,405 | 0.574 | Medium | 21,080 |
https://leetcode.com/problems/longest-happy-string/discuss/566741/Fill-in-most-freq-char-into-skeleton-of-other-2-chars%3A-Explained-string-building-strategy-%2B-proof | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
nums = [a, b, c]
chars = ['a', 'b', 'c']
indices = [0, 1, 2]
def keyFunc(i):
return nums[i]
indices = sorted(indices, key=keyFunc)
if nums[indices[2]] > (nums[indices[1]] + nums[indices[0]] + 1) * 2:
nums[indices[2]] = (nums[indices[1]] + nums[indices[0]] + 1) * 2
if nums[indices[2]] > nums[indices[1]] + nums[indices[0]] + 1:
s = ""
gaps = nums[indices[1]] + nums[indices[0]] + 1
doubles = nums[indices[2]] % gaps
if doubles == 0:
doubles = gaps
singles = nums[indices[2]] - doubles
for k in [0, 1]:
for i in range(nums[indices[k]]):
if doubles > 0:
s += chars[indices[2]]
doubles -= 1
s += chars[indices[2]]
s += chars[indices[k]]
if doubles > 0:
s += chars[indices[2]]
s += chars[indices[2]]
return s
else:
s = ""
singles = nums[indices[2]]
gaps = nums[indices[1]] + nums[indices[0]] + 1
zeros = gaps - singles
skip = True
for k in [0, 1]:
for i in range(nums[indices[k]]):
if zeros > 0 and skip:
zeros -= 1
else:
s += chars[indices[2]]
s += chars[indices[k]]
skip = not skip
if not(zeros > 0 and skip):
s += chars[indices[2]]
return s | longest-happy-string | Fill in most freq char into skeleton of other 2 chars: Explained string building strategy + proof | alexeiR | 0 | 119 | longest happy string | 1,405 | 0.574 | Medium | 21,081 |
https://leetcode.com/problems/stone-game-iii/discuss/815655/Python3-beats-93-DP | class Solution(object):
def stoneGameIII(self, stoneValue):
"""
:type stoneValue: List[int]
:rtype: str
"""
dp = [0 for _ in range(len(stoneValue))]
if len(dp) >= 1:
dp[-1] = stoneValue[-1]
if len(dp) >= 2:
dp[-2] = max(stoneValue[-1] + stoneValue[-2], stoneValue[-2] - dp[-1])
if len(dp) >= 3:
dp[-3] = max(stoneValue[-3] + stoneValue[-1] + stoneValue[-2], stoneValue[-3] - dp[-2], stoneValue[-3] + stoneValue[-2] - dp[-1])
for i in range(len(stoneValue) - 4, -1, -1):
dp[i] = max([sum(stoneValue[i: i + j]) - dp[i + j] for j in range(1, 4)])
if dp[0] > 0:
return "Alice"
if dp[0] == 0:
return "Tie"
return "Bob" | stone-game-iii | Python3 beats 93% DP | ethuoaiesec | 4 | 166 | stone game iii | 1,406 | 0.596 | Hard | 21,082 |
https://leetcode.com/problems/stone-game-iii/discuss/1123897/Python3-top-down-dp | class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
@cache
def fn(i):
"""Return max value obtained from stoneValue[i:]."""
if i >= len(stoneValue): return 0
ans = -inf
for ii in range(i, i+3):
ans = max(ans, sum(stoneValue[i:ii+1]) - fn(ii+1))
return ans
ans = fn(0)
if ans > 0: return "Alice"
if ans == 0: return "Tie"
return "Bob" | stone-game-iii | [Python3] top-down dp | ye15 | 2 | 187 | stone game iii | 1,406 | 0.596 | Hard | 21,083 |
https://leetcode.com/problems/stone-game-iii/discuss/1255808/Easy-Python-Dp-Solution | class Solution:
def stoneGameIII(self, num: List[int]) -> str:
dp=[0]*(len(num)+1)
i=len(num)-1
while i>=0:
ans=-1001
ans=max(ans,num[i]-dp[i+1])
if i+1<len(num):
ans=max(ans,num[i]+num[i+1]-dp[i+2])
if i+2<len(num):
ans=max(ans,num[i]+num[i+1]+num[i+2]-dp[i+3])
dp[i]=ans
i-=1
alice=dp[0]
if alice>0:
return "Alice"
elif alice<0:
return "Bob"
else:
return "Tie" | stone-game-iii | Easy Python Dp Solution | jaipoo | 1 | 152 | stone game iii | 1,406 | 0.596 | Hard | 21,084 |
https://leetcode.com/problems/stone-game-iii/discuss/566551/Python3-O(N)-Dynamic-Programming-explained | class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
take1 = [0 for _ in range(len(stoneValue))]
take2 = [0 for _ in range(len(stoneValue))]
take3 = [0 for _ in range(len(stoneValue))]
skip1 = [0 for _ in range(len(stoneValue))]
skip2 = [0 for _ in range(len(stoneValue))]
skip3 = [0 for _ in range(len(stoneValue))]
for i in range(len(stoneValue)-1, -1, -1):
if i < len(stoneValue) - 1:
take1[i] = stoneValue[i] + min(skip1[i+1], skip2[i+1], skip3[i+1])
take2[i] = stoneValue[i] + take1[i+1]
take3[i] = stoneValue[i] + take2[i+1]
skip1[i] = max(take1[i+1], take2[i+1], take3[i+1])
skip2[i] = skip1[i+1]
skip3[i] = skip2[i+1]
else:
take1[i] = stoneValue[i]
take2[i] = stoneValue[i]
take3[i] = stoneValue[i]
skip1[i] = 0
skip2[i] = 0
skip3[i] = 0
score = max(take1[0], take2[0], take3[0])
total = sum(stoneValue)
if score > total - score:
return 'Alice'
elif score == total - score:
return 'Tie'
else:
return 'Bob' | stone-game-iii | Python3 O(N) Dynamic Programming explained | alexeiR | 1 | 94 | stone game iii | 1,406 | 0.596 | Hard | 21,085 |
https://leetcode.com/problems/stone-game-iii/discuss/2334429/Python3-or-Easy-Understanding-or-O(n)-or-Memoization | class Solution:
def stoneGameIII(self, s: List[int]) -> str:
@cache
def res(pos = 0):
if pos == len(s):
return 0
else:
a = s[pos] - res(pos + 1)
b = -math.inf if pos + 1 >= len(s) else s[pos] + s[pos + 1] - res(pos + 2)
c = -math.inf if pos + 2 >= len(s) else s[pos] + s[pos + 1] + s[pos + 2] - res(pos + 3)
return max(a, b, c)
ans = res()
return "Bob" if ans < 0 else "Alice" if ans > 0 else "Tie" | stone-game-iii | Python3 | Easy-Understanding | O(n) | Memoization | DheerajGadwala | 0 | 21 | stone game iii | 1,406 | 0.596 | Hard | 21,086 |
https://leetcode.com/problems/stone-game-iii/discuss/1502606/Python3-or-Memoization-%2B-Recursion | class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
n=len(stoneValue)
@lru_cache(None)
def dfs(strt):
ans=-float('inf')
op1,op2,op3=-float('inf'),-float('inf'),-float('inf')
if strt>=n:
return 0
op1=stoneValue[strt]-dfs(strt+1)
if strt+1<n:
op2=stoneValue[strt]+stoneValue[strt+1]-dfs(strt+2)
if strt+2<n:
op3=stoneValue[strt]+stoneValue[strt+1]+stoneValue[strt+2]-dfs(strt+3)
ans=max(ans,op1,op2,op3)
return ans
k=dfs(0)
if k>0:
return "Alice"
elif k<0:
return "Bob"
else:
return "Tie" | stone-game-iii | [Python3] | Memoization + Recursion | swapnilsingh421 | 0 | 122 | stone game iii | 1,406 | 0.596 | Hard | 21,087 |
https://leetcode.com/problems/stone-game-iii/discuss/1202977/Python-Best-Solution-O(1)-space-complexity | class Solution:
def stoneGameIII(self, s: List[int]) -> str:
n = len(s)
dpi = 0
dp1 = 0
dp2 = 0
i = n-1
while i >= 0:
ans = -1<<32
ans = max(ans,s[i]-dpi)
if i+1 < n:
ans = max(ans,(s[i]+s[i+1])-dp1)
if i+2 < n:
ans = max(ans,(s[i]+s[i+1]+s[i+2])-dp2)
dp2 = dp1
dp1 = dpi
dpi = ans
i -= 1
if dpi > 0:
return "Alice"
if dpi == 0:
return "Tie"
return "Bob" | stone-game-iii | [Python] Best Solution O(1) space complexity | Piyush_0411 | 0 | 77 | stone game iii | 1,406 | 0.596 | Hard | 21,088 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/575147/Clean-Python-3-suffix-trie-O(NlogN-%2B-N-*-S2) | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
def add(word: str):
node = trie
for c in word:
node = node.setdefault(c, {})
def get(word: str) -> bool:
node = trie
for c in word:
if (node := node.get(c)) is None: return False
return True
words.sort(key=len, reverse=True)
trie, result = {}, []
for word in words:
if get(word): result.append(word)
for i in range(len(word)):
add(word[i:])
return result | string-matching-in-an-array | Clean Python 3, suffix trie O(NlogN + N * S^2) | lenchen1112 | 48 | 5,500 | string matching in an array | 1,408 | 0.639 | Easy | 21,089 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/575147/Clean-Python-3-suffix-trie-O(NlogN-%2B-N-*-S2) | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
def add(word: str):
node = trie
for c in word:
node = node.setdefault(c, {})
node['#'] = node.get('#', 0) + 1
def get(word: str) -> bool:
node = trie
for c in word:
if (node := node.get(c)) is None: return False
return node['#'] > 1
trie = {}
for word in words:
for i in range(len(word)):
add(word[i:])
return [word for word in words if get(word)] | string-matching-in-an-array | Clean Python 3, suffix trie O(NlogN + N * S^2) | lenchen1112 | 48 | 5,500 | string matching in an array | 1,408 | 0.639 | Easy | 21,090 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/741543/Python-3-String-Matching-in-an-Array.-beats-98 | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
wd = sorted(words, key=len)
res = []
for i in range(len(wd)):
for j in range(i+1,len(wd)):
if wd[i] in wd[j]:
res.append(wd[i])
break
return res | string-matching-in-an-array | [Python 3] String Matching in an Array. beats 98% | tilak_ | 5 | 810 | string matching in an array | 1,408 | 0.639 | Easy | 21,091 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/575118/Python3-a-naive-solution | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
words.sort(key=len) #by size in ascending order
ans = []
for i, word in enumerate(words):
for j in range(i+1, len(words)):
if word in words[j]:
ans.append(word)
break
return ans | string-matching-in-an-array | [Python3] a naive solution | ye15 | 3 | 433 | string matching in an array | 1,408 | 0.639 | Easy | 21,092 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/575038/python3-Brute-Force | class Solution:
def stringMatching(self, words):
words.sort(key=len)
res = []
for i in range(len(words)):
for j in range(i + 1, len(words)):
if words[i] in words[j]:
res.append(words[i])
return set(res) | string-matching-in-an-array | [python3] Brute Force | i-i | 3 | 303 | string matching in an array | 1,408 | 0.639 | Easy | 21,093 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/1363238/Using-KMP-Algorithm-or-Python3 | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
words.sort(key=len)
n = len(words)
def _KMP(s,sz):
m = len(s)
pi = [0]*m
for i in range(1,m):
j= pi[i-1]
while j >0 and s[i] != s[j]:
j = pi[j-1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi.count(sz) > 0
ans = []
for i in range(n-1):
sz = len(words[i])
string = '#'.join(words[i:])
if _KMP(string, sz):
ans.append(words[i])
return ans | string-matching-in-an-array | Using KMP Algorithm | Python3 | kk_r_17 | 2 | 192 | string matching in an array | 1,408 | 0.639 | Easy | 21,094 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/1063199/or-Python-3-or-Easy-to-understand-using-find() | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
return set([i for i in words for j in words if i != j and j.find(i) >= 0]) | string-matching-in-an-array | | Python 3 | Easy to understand, using find() | bruadarach | 2 | 248 | string matching in an array | 1,408 | 0.639 | Easy | 21,095 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/1063199/or-Python-3-or-Easy-to-understand-using-find() | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
result = []
for i in words:
for j in words:
if i != j and j.find(i) >= 0:
result.append(i)
break
return result | string-matching-in-an-array | | Python 3 | Easy to understand, using find() | bruadarach | 2 | 248 | string matching in an array | 1,408 | 0.639 | Easy | 21,096 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/1063199/or-Python-3-or-Easy-to-understand-using-find() | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
words = sorted(words, key=len)
return set([words[i] for i in range(len(words)) for j in range(i+1,len(words)) if words[j].find(words[i]) >= 0]) | string-matching-in-an-array | | Python 3 | Easy to understand, using find() | bruadarach | 2 | 248 | string matching in an array | 1,408 | 0.639 | Easy | 21,097 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/1063199/or-Python-3-or-Easy-to-understand-using-find() | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
words = sorted(words, key=len)
result = []
for i in range(len(words)):
for j in range(i+1,len(words)):
if words[j].find(words[i]) >= 0:
result.append(words[i])
break
return result | string-matching-in-an-array | | Python 3 | Easy to understand, using find() | bruadarach | 2 | 248 | string matching in an array | 1,408 | 0.639 | Easy | 21,098 |
https://leetcode.com/problems/string-matching-in-an-array/discuss/575116/Python-sol-sharing-85%2B-w-Comment | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
substr = []
for i, word_1 in enumerate(words):
for j, word_2 in enumerate(words):
# check word_1 is substring of word_2
if i != j and word_1 in word_2:
substr.append( word_1 )
# avoid repeated element appending
break
return substr | string-matching-in-an-array | Python sol sharing 85%+ [w/ Comment] | brianchiang_tw | 2 | 404 | string matching in an array | 1,408 | 0.639 | Easy | 21,099 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.