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/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/2309477/Python3-or-merge-subarray-from-left-and-right | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
n=len(arr)
s=0
while s<n-1 and arr[s]<=arr[s+1]:
s+=1
if s==n-1:return 0
r=n-1
while r>0 and arr[r]>=arr[r-1]:
r-=1
ans=min(n-1-s,r)
i,j=0,r
while i<=s and j<n:
if arr[i]<=arr[j]:
ans=min(ans,j-i-1)
i+=1
else:
j+=1
return ans | shortest-subarray-to-be-removed-to-make-array-sorted | [Python3] | merge subarray from left and right | swapnilsingh421 | 0 | 92 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,200 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/1274093/Simple-Python-solution | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
i=1
s=set()
arr.insert(0,-1)
while(i<len(arr) and (arr[i]>=arr[i-1])):
i=i+1
k=i-1
s.add(len(arr)-i)
if(i==len(arr)):
return 0
j=len(arr)-2
while(j>-1 and (arr[j]<=arr[j+1])):
j=j-1
while(k>-1):
x=j+1
while(x<len(arr)):
if(arr[k]<=arr[x]):
s.add((x-k)-1)
break
x=x+1
k=k-1
return min(s) | shortest-subarray-to-be-removed-to-make-array-sorted | Simple Python solution | Rajashekar_Booreddy | 0 | 370 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,201 |
https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/831299/Python3-6-line | class Solution:
def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
lo = next((i for i in range(len(arr)-1) if arr[i] > arr[i+1]), None)
hi = next((i for i in reversed(range(1, len(arr))) if arr[i-1] > arr[i]), None)
if lo is None: return 0
ll = bisect_right(arr, arr[hi], 0, lo+1)
rr = bisect_left(arr, arr[lo], hi, len(arr))
return min(hi - ll, rr - lo - 1) | shortest-subarray-to-be-removed-to-make-array-sorted | [Python3] 6-line | ye15 | 0 | 361 | shortest subarray to be removed to make array sorted | 1,574 | 0.366 | Medium | 23,202 |
https://leetcode.com/problems/count-all-possible-routes/discuss/831260/Python3-top-down-dp | class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
@lru_cache(None)
def fn(n, x):
"""Return all possible routes from n to finish with x fuel."""
if x < 0: return 0 # not going anywhere without fuel
ans = 0
if n == finish: ans += 1
for nn in range(len(locations)):
if nn != n: ans += fn(nn, x-abs(locations[n] - locations[nn]))
return ans
return fn(start, fuel) % 1_000_000_007 | count-all-possible-routes | [Python3] top-down dp | ye15 | 3 | 169 | count all possible routes | 1,575 | 0.568 | Hard | 23,203 |
https://leetcode.com/problems/count-all-possible-routes/discuss/2795376/Python-EASY-TO-UNDERSTAND-Memo-%2B-DFS | class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
# start = initial index
# end = destination index
MOD = (10**9)+7
lenLocations = len(locations)
@cache
def dfs(index, fuel):
# If you have no more fuel and you're at destination:
# You cannot try another other routes, return 1 because you're at destination
if fuel == 0 and index == finish:
return 1
# If no more fuel and not at route:
# You cannot try another other routes, return 1 because you're not at destination
if fuel <= 0:
return 0
# If your current index is destination index, you found an existing route
countWays = 1 if index == finish else 0
# Try every location index (dfs), but you cannot stay at your current index
for nextIndex in range(len(locations)):
if index != nextIndex:
cost = abs(locations[index]-locations[nextIndex])
countWays += dfs(nextIndex,fuel-cost)
return countWays
return dfs(start,fuel) % MOD | count-all-possible-routes | Python - EASY TO UNDERSTAND Memo + DFS | tupsr | 0 | 1 | count all possible routes | 1,575 | 0.568 | Hard | 23,204 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/831516/Python3-one-of-three-letters | class Solution:
def modifyString(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == "?":
for c in "abc":
if (i == 0 or s[i-1] != c) and (i+1 == len(s) or s[i+1] != c):
s[i] = c
break
return "".join(s) | replace-all-s-to-avoid-consecutive-repeating-characters | [Python3] one of three letters | ye15 | 66 | 3,100 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,205 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/831719/Python-3-Solution-for-Beginners-(-3-letter-soln) | class Solution:
def modifyString(self, s: str) -> str:
if len(s)==1: #if input contains only a '?'
if s[0]=='?':
return 'a'
s=list(s)
for i in range(len(s)):
if s[i]=='?':
for c in 'abc':
if i==0 and s[i+1]!=c: #if i=0 means it is first letter so there is no s[ i-1]
s[i]=c
break
if i==len(s)-1 and s[i-1]!=c: #if i=len(s) means it is last letter so there is no s[i+1]
s[i]=c
break
if (i>0 and i<len(s)-1) and s[i-1]!=c and s[i+1]!=c:
s[i]=c
break
return ''.join(s)
``` | replace-all-s-to-avoid-consecutive-repeating-characters | Python 3 Solution for Beginners ( 3 letter soln) | nikhilsmanu | 7 | 995 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,206 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/835260/A-Simple-Python-Solution | class Solution:
def modifyString(self, s: str) -> str:
# covert string to array, so we can replace letter in-place
result = [w for w in s]
N = len(result)
for i in range(N):
if result[i] == '?':
pre = result[i-1] if i-1 >= 0 else ''
nxt = result[i+1] if i+1 < N else ''
# only need to check 3 letters to avoid consecutive repeating chars
for w in ['a', 'b', 'c']:
if w != pre and w != nxt:
result[i] = w
break
return ''.join(result) | replace-all-s-to-avoid-consecutive-repeating-characters | A Simple Python Solution | pochy | 1 | 256 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,207 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/2790170/Simple-Python | class Solution:
def modifyString(self, s: str) -> str:
s= list(s)
for i in range(0, len(s)):
if s[i] == '?' and i == 0:
try:
if s[i + 1] != 'a':
s[i] = 'a'
print('s:', s)
else:
s[i] = 'b'
except:
return 'a'
elif s[i] == '?' and i == len(s)-1:
if s[i - 1] != 'a':
s[i] = 'a'
else:
s[i] = 'b'
else:
if s[i] == '?':
if s[i - 1] != 'a' and s[i + 1] != 'a':
s[i] = 'a'
elif s[i - 1] != 'b' and s[i + 1] != 'b':
s[i] = 'b'
else:
s[i] = 'c'
return ''.join(s) | replace-all-s-to-avoid-consecutive-repeating-characters | Simple Python | Antarab | 0 | 5 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,208 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/2700049/Python-straight-forward | class Solution:
def modifyString(self, s: str) -> str:
stack = []
mark = False
for i in range(len(s)):
if not mark and s[i] != "?":
stack.append(s[i])
elif mark and s[i] != "?":
while stack[-1] == s[i]:
stack[-1] = chr((ord(stack[-1])+1-97)%26+97)
stack.append(s[i])
mark = False
elif s[i] == "?":
if mark:
cur = stack[-1]
while stack[-1] == cur:
cur = chr((ord(stack[-1])+1-97)%26+97)
else:
if stack:
cur = stack[-1]
while stack[-1] == cur:
cur = chr((ord(stack[-1])+1-97)%26+97)
else:
cur = "a"
stack.append(cur)
mark = True
return "".join(stack) | replace-all-s-to-avoid-consecutive-repeating-characters | Python straight forward | Bettita | 0 | 7 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,209 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/2047540/Easy-to-grasp-python-solution-65-faster-and-99-less-memory-usage | class Solution:
def modifyString(self, s: str) -> str:
res = list(s)
# Create a string of lowercase letters
c = string.ascii_lowercase
for i in range(len(res)):
if res[i] == '?':
if i == 0:
# get substring of first two letters
tmp = res[:i+2]
elif i == len(res) - 1:
# get substring of last two letters
tmp = res[i-1:]
else:
# if 'i' is in middle get the substring of three letters
tmp = res[i-1:i+2]
# start at 'a'
# traverse until a letter not found in the substring 'tmp'.
count = 0
while c[count] in tmp:
count += 1
res[i] = c[count]
# finally using join convert it into list
return ''.join(x for x in res) | replace-all-s-to-avoid-consecutive-repeating-characters | Easy to grasp python solution 65% faster and 99 % less memory usage | sirpiyugendarr | 0 | 95 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,210 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/2011951/Python-Clean-and-Simple! | class Solution:
def modifyString(self, s):
s, n = list(s), len(s)-1
for i,c in enumerate(s):
if c == '?':
options = {'a', 'b', 'c'}
if i > 0: options -= {s[i-1]}
if i < n: options -= {s[i+1]}
option = options.pop()
s[i] = option
return "".join(s) | replace-all-s-to-avoid-consecutive-repeating-characters | Python - Clean and Simple! | domthedeveloper | 0 | 114 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,211 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1831135/Python-clear-solution | class Solution:
def modifyString(self, s: str) -> str:
if len(s) == 1:
return "a" if s == "?" else s
s = list(s)
for i in range(len(s)):
if s[i] == "?":
for x in "abc":
if i == 0: # [?a]
if s[i+1] != x:
s[i] = x
elif i == len(s) - 1: # [a?]
if s[i-1] != x:
s[i] = x
else: # [a?b]
if s[i-1] != x and s[i+1] != x:
s[i] = x
return "".join(s) | replace-all-s-to-avoid-consecutive-repeating-characters | Python clear solution | johnnychang | 0 | 71 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,212 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1791304/4-Lines-Python-Solution-oror-50-Faster-(46ms)-oror-Memory-Less-than-90 | class Solution:
def modifyString(self, s: str) -> str:
if s =='?': return 'a'
for i in range(len(s)-1):
if s[i] == '?' : s = s.replace(s[i], [c for c in "abc" if c not in {s[i-1],s[i+1]}][0], 1)
return s.replace(s[-1], [c for c in "ab" if c != s[-2]][0]) if s[-1]=='?' else s | replace-all-s-to-avoid-consecutive-repeating-characters | 4-Lines Python Solution || 50% Faster (46ms) || Memory Less than 90% | Taha-C | 0 | 80 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,213 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1446424/One-pass | class Solution:
def find_letter(self, neighbors):
for c in "abcdefghijklmnopqrstuvwxyz":
if c not in neighbors:
return c
def modifyString(self, s: str) -> str:
len_s = len(s)
if len_s == 0:
return ""
elif len_s == 1:
return "a" if s == "?" else s
len_s1 = len_s - 1
stack = list(s)
for i, c in enumerate(stack):
if c == "?":
if i == 0:
stack[i] = self.find_letter(stack[i + 1])
elif i == len_s1:
stack[i] = self.find_letter(stack[i - 1])
else:
stack[i] = self.find_letter(stack[i - 1] + stack[i + 1])
return "".join(stack) | replace-all-s-to-avoid-consecutive-repeating-characters | One pass | EvgenySH | 0 | 137 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,214 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1426285/Python3-Faster-Than-91.16-Using-only-3-letters | class Solution:
def modifyString(self, s: str) -> str:
if len(s) == 1:
if s == '?':
return 'a'
else:
return s
ss = []
for i in s:
ss += [i]
if ss[0] == '?':
if ss[1] == 'a':
ss[0] = 'b'
else:
ss[0] = 'a'
i = 1
while i < len(ss) - 1:
if ss[i] == '?':
if ss[i - 1] == 'a' or ss[i + 1] == 'a':
if ss[i - 1] == 'b' or ss[i + 1] == 'b':
ss[i] = 'q'
else:
ss[i] = 'b'
else:
ss[i] = 'a'
i += 1
if ss[-1] == '?':
if ss[-2] == 'a':
ss[-1] = 'b'
else:
ss[-1] = 'a'
return "".join(ss) | replace-all-s-to-avoid-consecutive-repeating-characters | Python3 Faster Than 91.16%, Using only 3 letters | Hejita | 0 | 88 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,215 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1370620/Python3-fast-and-simple | class Solution:
def modifyString(self, s: str) -> str:
ans = []
for i, ch in enumerate(s):
if ch != "?":
ans.append(ch)
else:
prev_ch = ans[-1] if i > 0 else ""
next_ch = s[i + 1] if i < len(s) - 1 else ""
if "a" != prev_ch and "a" != next_ch:
ans.append("a")
elif "b" != prev_ch and "b" != next_ch:
ans.append("b")
else:
ans.append("c")
return "".join(ans) | replace-all-s-to-avoid-consecutive-repeating-characters | Python3, fast and simple | MihailP | 0 | 283 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,216 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1317926/Python3-Faster-than-90-submissions-simple-code | class Solution:
def modifyString(self, s: str) -> str:
chars = 'abcdefghijklmnopqrstuvwxyz'
s = list(s)
while s.count('?')!=0:
index = s.index('?')
_prev = s[index-1] if index-1 >=0 else ''
_next = s[index+1] if index+1 <= len(s)-1 else ''
for char in chars:
if char != _prev and char != _next:
s[index] = char
break
return ''.join(s) | replace-all-s-to-avoid-consecutive-repeating-characters | [Python3] Faster than 90% submissions, simple code | GauravKK08 | 0 | 100 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,217 |
https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/1218363/Python3-simple-solution-using-set-beats-97-users | class Solution:
def modifyString(self, s: str) -> str:
if len(s) == 1 and s[0] != '?':
return s[0]
elif len(s) == 1 and s[0] == '?':
return 'a'
else:
x = {'a','b','c'}
res = ''
for i in range(len(s)):
if s[i] == '?':
if i == 0:
res += list(x.difference(set(s[i+1])))[0]
elif i == len(s)-1:
res += list(x.difference(set([s[i-1],res[i-1]])))[0]
else:
res += list(x.difference(set([s[i-1],s[i+1],res[i-1]])))[0]
else:
res += s[i]
return res | replace-all-s-to-avoid-consecutive-repeating-characters | Python3 simple solution using set beats 97% users | EklavyaJoshi | 0 | 67 | replace all s to avoid consecutive repeating characters | 1,576 | 0.491 | Easy | 23,218 |
https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/1658113/Python-intuitive-hashmap-solution-O(n*m)-time | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
sqr1, sqr2 = defaultdict(int), defaultdict(int)
m, n = len(nums1), len(nums2)
for i in range(m):
sqr1[nums1[i]**2] += 1
for j in range(n):
sqr2[nums2[j]**2] += 1
res = 0
for i in range(m-1):
for j in range(i+1, m):
if nums1[i]*nums1[j] in sqr2:
res += sqr2[nums1[i]*nums1[j]]
for i in range(n-1):
for j in range(i+1, n):
if nums2[i]*nums2[j] in sqr1:
res += sqr1[nums2[i]*nums2[j]]
return res | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | Python intuitive hashmap solution, O(n*m) time | byuns9334 | 2 | 114 | number of ways where square of number is equal to product of two numbers | 1,577 | 0.4 | Medium | 23,219 |
https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/1068741/Python-O(n2)-function | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
"""
O(n^2)
"""
def check(nums1, nums2):
# Initialize a dict: value->(value^2, count)
a = {}
for i in nums1:
if i not in a:
a[i] = [i**2, 1]
else:
a[i][-1] += 1
# Initialize a dict: nums2[i] * nums[j] -> count
b = collections.defaultdict(int)
for i in range(len(nums2)):
for j in range(i+1, len(nums2)):
b[nums2[i]*nums2[j]] += 1
# Calculate the result
# result += i^2 count * j*k count for each combination
result = 0
for (i, amount) in a.values():
result += b[i]*amount
return result
# Call above function twice
return check(nums1, nums2) + check(nums2, nums1) | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | Python O(n^2) function | dev-josh | 1 | 126 | number of ways where square of number is equal to product of two numbers | 1,577 | 0.4 | Medium | 23,220 |
https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/835642/Python-Solution-Based-on-Binary-Search-And-Memorization | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
nums1.sort()
nums2.sort()
def lowerbound(target, left, right, nums):
while left < right:
mid = left + (right - left) // 2
if nums[mid] == target:
right = mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid
return left
def higherbound(target, left, right, nums):
while left < right:
mid = left + (right - left) // 2
if nums[mid] == target:
left = mid + 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid
return left
def helper(n, nums, memo):
if n in memo:
return memo[n]
result = 0
for i in range(len(nums)):
if n % nums[i] != 0:
continue
target = n // nums[i]
# find total number of target in nums[i+1:]
lower = lowerbound(target, i+1, len(nums), nums)
higher = higherbound(target, i+1, len(nums), nums)
result += (higher - lower)
memo[n] = result
return result
result = 0
memo1 = {}
for n in nums1:
result += helper(n*n, nums2, memo1)
memo2 = {}
for n in nums2:
result += helper(n*n, nums1, memo2)
return result | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | Python Solution Based on Binary Search And Memorization | pochy | 1 | 98 | number of ways where square of number is equal to product of two numbers | 1,577 | 0.4 | Medium | 23,221 |
https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/831522/Python3-frequency-table | class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
cnt1, cnt2 = Counter(nums1), Counter(nums2)
def fn(x, y, freq):
"""Return count of triplet of nums[i]**2 = nums[j]*nums[k]."""
ans = 0
for xx in x:
xx *= xx
ans += sum(freq[xx//yy] - (yy == xx//yy) for yy in y if not xx%yy and xx//yy in freq)
return ans//2
return fn(nums1, nums2, cnt2) + fn(nums2, nums1, cnt1) | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | [Python3] frequency table | ye15 | 1 | 97 | number of ways where square of number is equal to product of two numbers | 1,577 | 0.4 | Medium | 23,222 |
https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/2812111/Optimal-and-Clean%3A-O(mn)-time-and-O(m%2Bn)-space | class Solution:
# two-sum. search for nums1[i]^2/nums2[k]
# O(mn) time : O(m + n) space
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
def count(arr1, arr2):
res = 0
for n1 in arr1:
n2_freq = defaultdict(int)
for n2 in arr2:
if n1*n1 / n2 in n2_freq:
res += n2_freq[n1*n1 / n2]
n2_freq[n2] += 1
return res
return count(nums1, nums2) + count(nums2, nums1) | number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers | Optimal and Clean: O(mn) time and O(m+n) space | topswe | 0 | 1 | number of ways where square of number is equal to product of two numbers | 1,577 | 0.4 | Medium | 23,223 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/831500/Python3-greedy | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
ans = prev = 0 # index of previously retained letter
for i in range(1, len(s)):
if s[prev] != s[i]: prev = i
else:
ans += min(cost[prev], cost[i])
if cost[prev] < cost[i]: prev = i
return ans | minimum-time-to-make-rope-colorful | [Python3] greedy | ye15 | 58 | 3,800 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,224 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/1559577/Python-Very-Easy-Solution | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
ans = 0
prev = 0
for i in range(1, len(s)):
if s[i] == s[prev]:
if cost[prev] < cost[i]:
ans += cost[prev]
prev = i
else:
ans += cost[i]
else:
prev = i
return ans | minimum-time-to-make-rope-colorful | Python Very Easy Solution | sarahwu0823 | 9 | 537 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,225 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2653025/Python-linear-solution-in-O(N)-Time-complexity-and-O(1)-Space-complexity | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
st,ct,total=0,1,0
sm=neededTime[0]
mx=neededTime[0]
for i in range(1,len(colors)):
if colors[i]==colors[i-1]:
ct+=1
sm+=neededTime[i]
mx=max(mx,neededTime[i])
else:
if ct>1:
total+=(sm-mx)
ct=1
st=i
sm=neededTime[i]
mx=neededTime[i]
if ct>1:
total+=(sm-mx)
return total | minimum-time-to-make-rope-colorful | Python linear solution in O(N) Time complexity and O(1) Space complexity | shubham_1307 | 5 | 220 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,226 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/845209/Python-3-or-Greedy-Clean-6-lines-or-Explanation | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
n, ans = len(s), 0
cur_sum = cur_max = cost[0]
for i in range(1, n):
if s[i-1] == s[i]: cur_sum, cur_max = cur_sum + cost[i], max(cur_max, cost[i])
else: ans, cur_sum, cur_max = ans + cur_sum - cur_max, cost[i], cost[i]
return ans + cur_sum - cur_max | minimum-time-to-make-rope-colorful | Python 3 | Greedy, Clean 6 lines | Explanation | idontknoooo | 4 | 918 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,227 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/1514461/Greedy-oror-Two-Pointer-oror-For-Beginners-oror-well-Explained | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
n = len(s)
if n<2:
return 0
res, i = 0, 0
for j in range(1,n):
if s[i]==s[j]:
res+=min(cost[i],cost[j])
if cost[i]<cost[j]:
i = j
else:
i = j
return res | minimum-time-to-make-rope-colorful | 📌📌 Greedy || Two-Pointer || For-Beginners || well-Explained 🐍 | abhi9Rai | 3 | 293 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,228 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2801404/My-Python-Stack-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
# Stack solution
# Time: O(n)
# Space: O(n)
stack = []
res = 0
min_time = 0
for b, t in zip(colors,neededTime):
if stack and b == stack[-1][0]:
b1, t1 = stack.pop()
min_time += min(t1,t)
if t1 > t:
stack.append((b1,t1))
else:
stack.append((b,t))
else:
stack.append((b,t))
res += min_time
min_time = 0
res += min_time
return res | minimum-time-to-make-rope-colorful | My Python Stack solution | wolfH | 2 | 25 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,229 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2663133/Python3-or-O(N)-or-One-Pass-or-Explained | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
output = 0
for i in range(len(colors)-1):
if colors[i] == colors[i+1]:
output += min(neededTime[i], neededTime[i+1])
neededTime[i+1] = max(neededTime[i], neededTime[i+1])
return output | minimum-time-to-make-rope-colorful | Python3 | O(N) | One Pass | Explained | user0027Rg | 2 | 38 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,230 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655523/O(n)-using-dynamic-programming-and-tracking-consecutive-position-(Examples) | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
print("colors:", colors, "neededTime:", neededTime)
n = len(colors)
dp = [[0] * 2 for _ in range(n+1)]
psame, vsame = 0, 0
for i in range(1,n+1):
dp[i][0] = min(dp[i-1]) + neededTime[i-1]
if i==1 or colors[i-1]!=colors[i-2]:
dp[i][1] = min(dp[i-1])
vsame = neededTime[i-1]
psame = i
else:
dp[i][1] = min(dp[psame-1]) + vsame
vsame = vsame + neededTime[i-1]
print("+ ", i, (colors[i-1],neededTime[i-1]), dp[i-1], f"(pos: {psame}, cost:{vsame})")
ans = min(dp[-1])
print("ans:",ans)
print("="*20, "\n")
return ans
print = lambda *a, **aa: () | minimum-time-to-make-rope-colorful | O(n) using dynamic programming and tracking consecutive position (Examples) | dntai | 1 | 24 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,231 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655389/Python-or-Easy-or-Iterative-or-Stack | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
stack = []
min_time = 0
for i in range(len(colors)):
if stack and colors[stack[-1]] == colors[i]:
if neededTime[stack[-1]] < neededTime[i]:
min_time += neededTime[stack.pop()]
else:
min_time += neededTime[i]
continue
stack.append(i)
return min_time | minimum-time-to-make-rope-colorful | Python | Easy | Iterative | Stack | gurubalanh | 1 | 9 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,232 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654425/Beginner's-Code-Python | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
i=0
s=0
while i<len(colors):
cnt=0
su=0
flag=False
mn=-1
while i<len(colors)-1 and colors[i]==colors[i+1]:
flag=True
mn=max(mn,neededTime[i])
cnt+=1
su+=neededTime[i]
i+=1
if flag:
mn=max(mn,neededTime[i])
su+=neededTime[i]
s+=(su-mn)
i+=1
return s | minimum-time-to-make-rope-colorful | Beginner's Code - Python | prateekgoel7248 | 1 | 50 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,233 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2652999/Python-MinHeap-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
prev_col = ""
#Minheap that we will be using to keep track of smallest balloon size for multiple baloon series.
heap = []
time = 0
for i in range(len(neededTime) -1, -1, -1):
if colors[i] == prev_col:
if not heap:
heapq.heappush(heap, neededTime[i])
else:
if heap[0] < neededTime[i]:
time += heapq.heappop(heap)
heapq.heappush(heap, neededTime[i])
else:
time += neededTime[i]
else:
#Restart heap when balloon colour is alternate
heap = [neededTime[i]]
# Update previous colour
prev_col = colors[i]
return time | minimum-time-to-make-rope-colorful | Python MinHeap solution | KennethWrong | 1 | 13 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,234 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/1808421/Python-Easy-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
ans = 0
for i in range(1,len(colors)):
#If two consecutive colors are same, remove the one with lesser neededTime.
if colors[i] == colors[i-1]:
if neededTime[i] >= neededTime[i-1]:
ans += neededTime[i-1]
else:
#If ith color is removed, then neededTime[i] for next step will be neededTime[i-1]
ans += neededTime[i]
neededTime[i] = neededTime[i-1]
return ans | minimum-time-to-make-rope-colorful | Python Easy Solution | MS1301 | 1 | 105 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,235 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/832166/Simple-and-easy-to-understand-O(N)-solution-in-Python | class Solution:
def minCost(self, s: str, cost: List[int]) -> int:
i = 0
min_cost = 0
while i+1 < len(s):
if s[i] == s[i+1]:
# Identical characters found. Now we will delete the least cost one
if cost[i] < cost[i+1]:
# nothing much to do since we are moving on to next character
min_cost += cost[i]
else:
# next character is deleted, so we will swap the values
min_cost += cost[i+1]
cost[i+1]= cost[i]
i += 1
return min_cost | minimum-time-to-make-rope-colorful | Simple and easy to understand O(N) solution in Python | avi_ | 1 | 135 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,236 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2790646/Easy-Python-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
total_time = 0
i = 1
while i < len(neededTime):
if colors[i] == colors[i-1]:
total_time+=min(neededTime[i],neededTime[i-1])
if neededTime[i-1] > neededTime[i] : neededTime[i],neededTime[i-1] = neededTime[i-1],neededTime[i]
i = i+1
return total_time | minimum-time-to-make-rope-colorful | Easy Python solution | ishitakumardps | 0 | 1 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,237 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2729664/O(N)-solution-or-Greedy-approach-or-presum | class Solution(object):
def minCost(self, colors, neededTime):
"""
:type colors: str
:type neededTime: List[int]
:rtype: int
"""
res=0
maxi=0
pre=0
val=colors[0]
for i in range(len(colors)):
if colors[i]==val:
maxi=max(maxi,neededTime[i])
pre+=neededTime[i]
else:
res+=pre-maxi
pre=neededTime[i]
maxi=neededTime[i]
val=colors[i]
res+=pre-maxi
return res | minimum-time-to-make-rope-colorful | O(N) solution | Greedy approach | presum | sundram_somnath | 0 | 4 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,238 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2718036/Python-solution-beats-93-simple | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
cost=0
for i in range(1,len(colors)):
if colors[i]==colors[i-1]:
cost+=min(neededTime[i],neededTime[i-1])
neededTime[i]=max(neededTime[i],neededTime[i-1])
return cost | minimum-time-to-make-rope-colorful | Python solution beats 93 % simple | vikash_kumar_beniwal | 0 | 4 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,239 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2699821/Python3-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
cost=0
i=0
while (i<len(colors)-1):
j=i+1
maxx=0
count=1
while (j<len(colors) and colors[j]==colors[i]):
maxx=max(maxx,neededTime[j])
cost+=neededTime[j]
j+=1
count+=1
if (count>1):
maxx=max(maxx,neededTime[i])
cost+=neededTime[i]
cost-=maxx
i=j
return cost | minimum-time-to-make-rope-colorful | Python3 Solution | minhhoanghectorjack | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,240 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2699283/Python-Beginner-Friendly | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
i,j=0,0
n=len(colors)
res=0
while i<n:
c=1
x=i
while i+1<n and colors[i]==colors[i+1]:
c+=1
i+=1
i+=1
if c>1:
z=sum(neededTime[x:x+c])-max(neededTime[x:x+c])
res+=z
z=0
return res | minimum-time-to-make-rope-colorful | Python Beginner Friendly | imamnayyar86 | 0 | 1 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,241 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2667864/Another-Python-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
ans=0
n=len(colors)
currentsum=neededTime[0]
maxval=neededTime[0]
for i in range(1,n):
if colors[i]==colors[i-1]:
currentsum+=neededTime[i] #adding value of all consecutive colors
maxval=max(maxval,neededTime[i]) #keeping the max. value of sum series
else:
ans+=currentsum-maxval #now consecutive series is ended so we are inceasing answer
currentsum=neededTime[i]
maxval=neededTime[i]
ans+=currentsum-maxval
return ans
'''
upvote if you like it | minimum-time-to-make-rope-colorful | Another Python Solution | Gyanendramech | 0 | 5 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,242 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2660924/Simple-Python-O(n)-Greedy-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
# Keep tracking of previous balloon color and maximum previous time for that balloon
prev = prev_time = None
# Total time needed (increments if two adjacent balloons found)
total = 0
# Go through all balloons in order
for i, c in enumerate(colors):
# If we find two adjacent balloons
if c == prev:
# Greedy approach: always remove the lowest time balloon (keep the higher one as prev_time)
# Case 1: a previous time is lower, so add it to total
if prev_time < neededTime[i]:
total += prev_time
prev_time = neededTime[i]
# Case 2: current balloon's time is lower
else:
total += neededTime[i]
# If no adjacent balloons of same color, reset prev and prev_time
else:
prev = c
prev_time = neededTime[i]
# Contains total time to remove all but one adjacent balloons of same color
return total | minimum-time-to-make-rope-colorful | Simple Python O(n) Greedy Solution | arnavn101 | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,243 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2659512/Python-Solution-with-easy-explanation | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
res = 0
for i in range(1,len(colors)):
if colors[i-1]==colors[i]:
if neededTime[i] > neededTime[i-1]:
res += neededTime[i-1]
else:
res += neededTime[i]
# Since our current value is the smaller one
# we are addng it to our result(i.e removing the ballon from our series.)
# we will change the value of the current to depict the previous ballon.
neededTime[i] = neededTime[i-1]
return res | minimum-time-to-make-rope-colorful | Python Solution with easy explanation | aryan_codes_here | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,244 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2658970/Python-oror-Array-oror-O(n)-oror-Easy-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
lnth = len(neededTime)
if lnth == 1:
return 0
else:
ans, i, Max, Sum = 0, 0, float('-inf'), 0
while i < lnth - 1:
Max = max(Max, neededTime[i])
Sum += neededTime[i]
if colors[i] != colors[i+1]:
ans += Sum - Max
Sum = 0
Max = float('-inf')
i += 1
if Sum != 0:
Max = max(Max, neededTime[i])
Sum += neededTime[i]
ans += Sum - Max
return ans | minimum-time-to-make-rope-colorful | Python || Array || O(n) || Easy Solution | Rahul_Kantwa | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,245 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2657532/Easy-Python-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
time = 0
prev = 0
for i in range(1,len(colors)):
if colors[prev] == colors[i]:
if neededTime[prev]<neededTime[i]:
time+=neededTime[prev]
else:
time+=neededTime[i]
continue
prev = i
return time | minimum-time-to-make-rope-colorful | Easy Python solution | sanghaviparth99 | 0 | 7 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,246 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2657509/Slide-window-on-consecutive-indices-of-same-color | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
start = end = 0
n = len(colors)
prev = None
time_needed = 0
while(end<n):
if(colors[end] != prev):
prev = colors[end]
start = end
end+=1
else:
# sstart remaims
# inc end till u find new char -> inc sliding window
max_time = total_time = neededTime[start]
while(end<n and colors[end] == prev):
max_time = max(max_time, neededTime[end])
total_time += neededTime[end]
end+=1
time_needed += total_time - max_time
return time_needed | minimum-time-to-make-rope-colorful | Slide window on consecutive indices of same color | crazyplatelady | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,247 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2657400/Python3-Two-Pointers | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
res = 0
i, j = 0, 1
while j < len(colors):
if colors[i] == colors[j]:
if neededTime[i] < neededTime[j]:
res += neededTime[i]
i = j
else:
res += neededTime[j]
else:
i = j
j += 1
return res | minimum-time-to-make-rope-colorful | [Python3] Two Pointers | ruosengao | 0 | 25 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,248 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2657243/Python-oror-Simple-O(n)-solution-using-stacks-oror-Greedy | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
stack = []
ans = 0
for i,j in enumerate(colors):
if not(stack):
stack.append([neededTime[i],j])
else:
if stack[-1][-1]==j:
time,color = stack.pop()
ans += min(time,neededTime[i])
stack.append([max(time,neededTime[i]),j])
else:
stack.append([neededTime[i],j])
return ans | minimum-time-to-make-rope-colorful | [Python] || Simple O(n) solution using stacks || Greedy | anup_omkar | 0 | 4 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,249 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2657053/One-pass-approach-keeping-pointer-to-previous-balloon-color | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
prev_color = (colors[0],0)
cost = 0
for i in range(1,len(colors)):
curr_color = colors[i]
if curr_color != prev_color[0] : #In case the adjacent colors are different, no balloon to be removed
prev_color = (curr_color,i)
continue
#Below code is run if there are adjacent same color balloons and one needs to be removed
if neededTime[i] < neededTime[prev_color[1]]: #the current balloon to be removed
cost+= neededTime[i]
else:
#previous balloon to be removed as it needs lesser time.In this case current color will become the previous color for next balloon in line
cost+=neededTime[prev_color[1]]
prev_color = (curr_color,i)
return cost | minimum-time-to-make-rope-colorful | One pass approach - keeping pointer to previous balloon color | divyanshikathuria | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,250 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656956/Python-Solution-using-Stack | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
ans = 0
stack = []
for i in range(len(colors)-1, -1, -1):
if not stack:
stack.append((colors[i], neededTime[i]))
continue
color, times = stack[-1]
if color == colors[i]:
if times < neededTime[i]:
stack.pop()
stack.append((color, neededTime[i]))
ans += min(neededTime[i], times)
continue
stack.append((colors[i], neededTime[i]))
return ans | minimum-time-to-make-rope-colorful | Python Solution using Stack | vijay_2022 | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,251 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656830/Faster-than-94-or-Simple-greedy-or-Python-or-Explained | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
#check if you have a consecutive block,
#in that block, check the sum of that block
#subtract the higest value
n = len(colors)
totalcost = 0
currsum = []
i = 0
#instead of going back, go forward?
while(i<n-1):
if colors[i+1]==colors[i]:
#consecutives
currsum.append(neededTime[i])
else:
#either its an end of a consecutives,
#or its a normal unique sequence
if currsum:
#its the end of sequence
currsum.append(neededTime[i])
totalcost += (sum(currsum)-max(currsum))
#update currsum and maxi
currsum = []
i+=1
#edge case, what about the last element?
if currsum!=0:
#its the end of sequence
currsum.append(neededTime[i])
totalcost += (sum(currsum)-max(currsum))
return totalcost | minimum-time-to-make-rope-colorful | Faster than 94% | Simple greedy | Python | Explained | ana_2kacer | 0 | 51 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,252 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656811/Python-Simple-98.61-less-memory | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
res=0
cnt=0
for i in range(len(colors)-1):
if colors[i]==colors[i+1]:
if neededTime[i-cnt]>neededTime[i+1-cnt]:
res+=neededTime[i+1-cnt]
neededTime.pop(i+1-cnt)
else:
res+=neededTime[i-cnt]
neededTime.pop(i-cnt)
cnt+=1
return res | minimum-time-to-make-rope-colorful | Python Simple- 98.61% less memory | mg_112002 | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,253 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656739/Python-1-line-O(n) | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
return sum(neededTime)-sum([max(list(map(lambda x: neededTime[x[0]], l))) for _, l in itertools.groupby(enumerate(colors), key=lambda x:x[1])]) | minimum-time-to-make-rope-colorful | Python 1 line O(n) | yk1962 | 0 | 33 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,254 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656397/Python-Concise-and-O(N)-O(1)-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
# introduce variables to save the time
result = 0
# go through the balloons and time
pointer = 0
col = 'A'
last_time = 0
for pointer in range(len(colors)):
# check whether our color is the same as
# the last one
if colors[pointer] == col:
# we need to check the time
if neededTime[pointer] > last_time:
result += last_time
last_time = neededTime[pointer]
else:
result += neededTime[pointer]
else:
last_time = neededTime[pointer]
col = colors[pointer]
return result | minimum-time-to-make-rope-colorful | [Python] - Concise and O(N) - O(1) Solution | Lucew | 0 | 4 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,255 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656396/Python-Concise-and-O(N)-O(1)-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
# introduce variables to save the time
result = 0
# go through the balloons and time
pointer = 0
col = 'A'
last_time = 0
for pointer in range(len(colors)):
# check whether our color is the same as
# the last one
if colors[pointer] == col:
# we need to check the time
if neededTime[pointer] > last_time:
result += last_time
last_time = neededTime[pointer]
else:
result += neededTime[pointer]
else:
last_time = neededTime[pointer]
col = colors[pointer]
return result | minimum-time-to-make-rope-colorful | [Python] - Concise and O(N) - O(1) Solution | Lucew | 0 | 1 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,256 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2656283/Python-or-Greedy-or-O(n) | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
res = 0
n = len(colors)
i = 1
while i<n:
if colors[i] == colors[i-1]:
total_sum = neededTime[i-1]
max_time = neededTime[i-1]
while i<n and colors[i] == colors[i-1]:
total_sum += neededTime[i]
max_time = max(max_time, neededTime[i])
i += 1
res += total_sum - max_time
i += 1
return res | minimum-time-to-make-rope-colorful | Python | Greedy | O(n) | prashants71195 | 0 | 31 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,257 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655997/python3-short-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
temp,s=neededTime[0],0
for i in range(1,len(colors)):
if colors[i]==colors[i-1]:
temp=max(temp,neededTime[i])
else:
s+=temp
temp=neededTime[i]
return sum(neededTime)-(s+temp) | minimum-time-to-make-rope-colorful | python3 short solution | benon | 0 | 42 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,258 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655972/Simple-Python-Heap-Solution-Explained | class Solution:
# simple Heap implementation in python
def minCost(self, colors: str, nt: List[int]) -> int:
i, res = 1, 0
while i < len(colors):
heap = []
while i < len(colors) and colors[i] == colors[i - 1]:
heappush(heap, nt[i - 1]) # Keep adding to heap if same
i += 1
if heap: heappush(heap, nt[i - 1]) # add the last one as it was left
while len(heap) > 1:
res += heappop(heap) # keep popping and adding to the result time lowest time needed first
heap.clear() # clear the heap for future use
i += 1 # since colors[i] != colors[i - 1] if we came till here so simply increase i
return res | minimum-time-to-make-rope-colorful | 🥶 Simple Python Heap Solution Explained 🏑 | shiv-codes | 0 | 16 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,259 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655874/Python3!-As-short-as-it-gets! | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
last_color, max_time, sum_time = '', 0, 0
for c,t in zip(colors, neededTime):
if c == last_color:
max_time = max(t, max_time)
else:
sum_time += max_time
last_color, max_time = c, t
return sum(neededTime) - sum_time - max_time | minimum-time-to-make-rope-colorful | 😎Python3! As short as it gets! | aminjun | 0 | 48 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,260 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655867/Python-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
output = 0
currentColor = ""
currentSequence = []
for t, color in enumerate(colors):
if color != currentColor:
if currentSequence:
output += sum(currentSequence) - max(currentSequence)
currentColor = color
currentSequence = []
currentSequence.append(neededTime[t])
else:
currentSequence.append(neededTime[t])
if currentSequence:
output += sum(currentSequence) - max(currentSequence)
return output | minimum-time-to-make-rope-colorful | Python Solution | AxelDovskog | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,261 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655695/Intuitive-O(n)-time-O(1)-space-python3-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
i=0
j=i+1
time = 0
currsu = 0 # current consecutive same balloons sum
maxsu = 0 # current maximum of the consecutive same balloons
while j<len(colors):
if colors[j]==colors[i]:
currsu += neededTime[j]
maxsu = max(neededTime[j], maxsu)
else:
currsu += neededTime[i]
maxsu = max(neededTime[i], maxsu)
time += currsu-maxsu
currsu = 0
maxsu = 0
i=j
j+=1
if currsu!=0: # this is needed for cases where the last time is not getting calculated for ex: abaaa
currsu += neededTime[i]
maxsu = max(neededTime[i], maxsu)
time += currsu-maxsu
return time | minimum-time-to-make-rope-colorful | Intuitive O(n) time O(1) space python3 solution | nirutgupta78 | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,262 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655664/Python-Using-Dictionary-Approach | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
if len(set(colors))==len(colors):
return 0
d = {}
for i in range(len(colors)):
if d.get(colors[i],-1)==-1:
d[colors[i]]=[i]
else:
d[colors[i]].append(i)
ans = 0
for i in d.values():
for j in range(1,len(i)):
if i[j-1]+1 == i[j]:
ans += min(neededTime[i[j-1]],neededTime[i[j]])
if(neededTime[i[j]]<neededTime[i[j-1]]):
neededTime[i[j]]=neededTime[i[j-1]]
return ans | minimum-time-to-make-rope-colorful | Python Using Dictionary Approach | chandu71202 | 0 | 26 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,263 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655610/Using-single-For-loop | class Solution:
def minCost(self, colors: str, n: List[int]) -> int:
if len(colors)==1:
return 0
ans=0
for i in range(1,len(colors)):
if colors[i-1]==colors[i]:
if n[i-1]>n[i]:
ans+=n[i]
n[i]=n[i-1]
else:
ans+=n[i-1]
return ans | minimum-time-to-make-rope-colorful | Using single For loop | 131901028 | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,264 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655467/Python3-One-pass-O(n) | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
currentBallon = 'Invalid'
count = 0
timeList = []
totalTime = 0
for index in range(len(colors)):
ballon = colors[index]
if ballon == currentBallon:
count += 1
timeList.append(neededTime[index])
else:
if count > 1:
totalTime += sum(timeList) - max(timeList)
currentBallon = ballon
count = 1
timeList = [neededTime[index]]
if count > 1:
totalTime += sum(timeList) - max(timeList)
return totalTime | minimum-time-to-make-rope-colorful | [Python3] One pass O(n) | peatear-anthony | 0 | 45 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,265 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655262/Priority-Queue | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
ans = 0
deq = []
color = "*"
for i in range(len(colors)):
if colors[i]!=color:
while len(deq)>1:
ans += heapq.heappop(deq)
deq = []
heapq.heappush(deq, neededTime[i])
color = colors[i]
while len(deq)>1:
ans += heapq.heappop(deq)
return ans | minimum-time-to-make-rope-colorful | Priority Queue | Woors | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,266 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655150/Python-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
colors = "abaac",
neededTime = [1,2,3,4,5]
ans = 0
prev = 0
for i in range(1, len(colors)):
if colors[i] == colors[prev]:
ans += (neededTime[prev] + neededTime[i] - max(neededTime[prev], neededTime[i]))
if neededTime[prev] < neededTime[i]:
prev = i
else:
prev = i
return ans | minimum-time-to-make-rope-colorful | [Python Solution] | pranshusharma712 | 0 | 45 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,267 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2655052/Simple-Python-3-solution-or-Greedy | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
n = len(colors)
ans = 0
for i in range(1 , n) :
if colors[i] == colors[i-1] :
if neededTime[i] < neededTime[i-1] :
ans+= neededTime[i]
neededTime[i] = neededTime[i-1]
else:
ans += neededTime[i-1]
return ans | minimum-time-to-make-rope-colorful | Simple Python 3 solution | Greedy | 1day_ | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,268 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654982/O(n)-or-O(1)-Easyandclear-with-a-detailed-explanation | class Solution:
def minCost(self, colors, neededTime):
cur_max = cur_sum = neededTime[0]
i, l, ans = 1, len(colors), 0
while i < l:
cur = neededTime[i]
if colors[i] == colors[i-1]:
cur_max = max(cur, cur_max)
cur_sum += cur
else:
ans += cur_sum - cur_max
cur_max = cur_sum = cur
i += 1
return ans + cur_sum - cur_max | minimum-time-to-make-rope-colorful | O(n) | O(1) Easy&clear with a detailed explanation | Cuno_DNFC | 0 | 18 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,269 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654631/O(n)-solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
i = 0
n = len(colors)-1
res = 0
while i < n:
summ = 0
maxx = float("-inf")
while i < n and colors[i] == colors[i+1]:
summ += neededTime[i]
maxx = max(maxx, neededTime[i])
i += 1
if summ > 0:
summ += neededTime[i]
maxx = max(neededTime[i], maxx)
res += summ - maxx
i += 1
return res | minimum-time-to-make-rope-colorful | O(n) solution | namanxk | 0 | 32 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,270 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654585/Python3or-Sliding-Window | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
i = 0
ans = 0
j = 0
while i < len(colors):
max_time = neededTime[i]
j = i
while j < len(colors) and colors[j] == colors[i]:
max_time = max(neededTime[j] , max_time)
ans += neededTime[j]
j += 1
ans -= max_time
i = j
return ans | minimum-time-to-make-rope-colorful | Python3| Sliding Window | thevaibhavdixit | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,271 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654583/Python-or-Two-O(n)-solutions-using-a-sliding-window-two-pointers | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
cost = 0
for i in range(len(colors) - 1):
c1, c2 = colors[i : i+2]
t1, t2 = neededTime[i : i+2]
if c1 == c2:
cost += min(t1, t2)
neededTime[i+1] = max(t1,t2)
return cost | minimum-time-to-make-rope-colorful | Python | Two O(n) solutions using a sliding window two pointers | ahmadheshamzaki | 0 | 42 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,272 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654583/Python-or-Two-O(n)-solutions-using-a-sliding-window-two-pointers | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
l = r = cost = 0
while l < len(colors):
color_total = color_max = 0
while r < len(colors) and colors[l] == colors[r]:
color_total += neededTime[r]
color_max = max(color_max, neededTime[r])
r += 1
cost += color_total - color_max
l = r
return cost | minimum-time-to-make-rope-colorful | Python | Two O(n) solutions using a sliding window two pointers | ahmadheshamzaki | 0 | 42 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,273 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654508/Python-(Faster-than-98)-or-Brute-force | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
minTime = 0
previdx = 0
for i in range(1, len(colors)):
if colors[previdx] == colors[i]:
minTime += min(neededTime[previdx], neededTime[i])
if neededTime[previdx] < neededTime[i]:
previdx = i
else:
previdx = i
return minTime | minimum-time-to-make-rope-colorful | Python (Faster than 98%) | Brute force | KevinJM17 | 0 | 3 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,274 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654491/Python-or-Greedy-or-NOob | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
ans = 0
i = 1
while i<len(colors):
if colors[i]==colors[i-1]:
last = neededTime[i-1]
s = 0
while i<len(colors) and colors[i]==colors[i-1]:
if neededTime[i]>last:
s+=last
last = neededTime[i]
else:
s+=neededTime[i]
i+=1
ans+=s
else:
i+=1
return ans | minimum-time-to-make-rope-colorful | Python | Greedy | NOob | Brillianttyagi | 0 | 33 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,275 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654389/Greedy | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
result = 0;past = [colors[0],0]
for i in range(1,len(colors)):
if colors[i] == past[0]:
if neededTime[i]<neededTime[past[1]]:
result += neededTime[i]
else:
result += neededTime[past[1]]
past = [colors[i],i]
else:
past = [colors[i],i]
return result | minimum-time-to-make-rope-colorful | Greedy | hhunterr | 0 | 2 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,276 |
https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/2654228/O(N)-Easy-Python-Solution | class Solution:
def minCost(self, colors: str, neededTime: List[int]) -> int:
consecutives = dict()
i = 1
prev = colors[0]
count = 0
while i < len(colors):
if colors[i] == prev:
if count not in consecutives:
consecutives[count] = [neededTime[i-1]]
consecutives[count].append(neededTime[i])
else:
prev = colors[i]
count +=1
i+=1
sum_ = 0
for list_ in consecutives.values():
if len(list_) == 1:
sum_ += list_[0]
else:
max_ = 0
for i in list_:
sum_+=i
max_ = max(max_, i)
sum_ -= max_
return sum_ | minimum-time-to-make-rope-colorful | O(N), Easy Python Solution | didarix | 0 | 11 | minimum time to make rope colorful | 1,578 | 0.637 | Medium | 23,277 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1802763/Python-Memory-Efficient-Solution | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
onesx = []
onesy = []
for ri, rv in enumerate(mat):
for ci, cv in enumerate(rv):
if cv == 1:
onesx.append(ri)
onesy.append(ci)
count = 0
for idx in range(len(onesx)):
if onesx.count(onesx[idx]) == 1:
if onesy.count(onesy[idx]) == 1:
count += 1
return count | special-positions-in-a-binary-matrix | 📌 Python Memory-Efficient Solution | croatoan | 4 | 129 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,278 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1465223/Python-Transpose | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
M, N, result = len(mat), len(mat[0]), 0
mat_t = list(zip(*mat)) # transpose
for i in range(M):
for j in range(N):
if mat[i][j] == 1 and \
sum(mat[i]) == 1 and \
sum(mat_t[j]) == 1:
result += 1
return result | special-positions-in-a-binary-matrix | [Python] Transpose | dev-josh | 2 | 136 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,279 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/843936/Python3-5-line-2-pass | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
row, col = [0]*m, [0]*n
for i, j in product(range(m), range(n)):
if mat[i][j]: row[i], col[j] = 1 + row[i], 1 + col[j]
return sum(mat[i][j] and row[i] == 1 and col[j] == 1 for i, j in product(range(m), range(n))) | special-positions-in-a-binary-matrix | [Python3] 5-line 2-pass | ye15 | 2 | 422 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,280 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1407586/Python3-Faster-Than-90.50 | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
transpose = [list(x) for x in zip(*mat)]
c = 0
for row in mat:
if row.count(1) == 1:
idx = row.index(1)
if transpose[idx].count(1) == 1:
c += 1
return c | special-positions-in-a-binary-matrix | Python3 Faster Than 90.50% | Hejita | 1 | 60 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,281 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1398365/Python-Solution-Faster-than-90 | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
matTrans = [list(x) for x in zip(*mat)]
count = 0
for row in mat:
if row.count(1) != 1:
continue
oneIndex = row.index(1)
if matTrans[oneIndex].count(1) == 1:
count += 1
return count | special-positions-in-a-binary-matrix | Python Solution Faster than 90% | peatear-anthony | 1 | 100 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,282 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1370685/Python-3-fast-and-simple-152-ms-faster-than-97.49 | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
row_set = {i for i, r in enumerate(mat) if sum(r) == 1}
return len(["" for c in zip(*mat) if sum(c) == 1 and c.index(1) in row_set]) | special-positions-in-a-binary-matrix | Python 3, fast and simple, 152 ms, faster than 97.49% | MihailP | 1 | 188 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,283 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/2835862/Simple-python-solution | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
n = len(mat)
m = len(mat[0])
#taking transpose of matrix
lst = list(zip(*mat))
res = 0
for i in range(n):
for j in range(m):
#Checking if current element is 1 and sum of elements of current row and column is also 1
if mat[i][j] == 1 and sum(mat[i]) == 1 and sum(lst[j]) == 1:
res += 1
return res | special-positions-in-a-binary-matrix | Simple python solution | aruj900 | 0 | 2 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,284 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/2797879/Python-3-10-lines-easy-to-understand | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
cnt =0
rows = {r : sum(row) for r, row in enumerate(mat)}
columns = {c : sum(col) for c, col in enumerate(zip(*mat))}
rows = {k : v for k, v in rows.items() if v == 1}
columns = {k : v for k, v in columns.items() if v == 1}
for r in rows.keys():
for c in columns.keys():
if mat[r][c] == 1:
cnt += 1
return cnt | special-positions-in-a-binary-matrix | Python 3 - 10 lines - easy to understand | noob_in_prog | 0 | 8 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,285 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/2639717/Python-2-lines | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
cols = list(zip(*mat))
return sum(mat[r][c] and mat[r].count(1) == 1 and cols[c].count(1) == 1
for r in range(len(mat)) for c in range(len(mat[0]))) | special-positions-in-a-binary-matrix | Python 2 lines | SmittyWerbenjagermanjensen | 0 | 6 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,286 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/2639717/Python-2-lines | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
cols = list(zip(*mat))
ans = 0
for r in range(len(mat)):
for c in range(len(mat[0])):
if mat[r][c] == 1 and mat[r].count(1) == 1 and cols[c].count(1) == 1:
ans += 1
return ans | special-positions-in-a-binary-matrix | Python 2 lines | SmittyWerbenjagermanjensen | 0 | 6 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,287 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/2343028/Python-or-97-Time | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
rowSums = []
colSums = []
for i in range(len(mat)):
rowSums.append(sum(mat[i]))
#Transpose
for i in range(len(mat[0])):
lst = []
for j in range(len(mat)):
lst.append(mat[j][i])
colSums.append(sum(lst))
#Transpose
count = 0
for i in range(len(mat)):
for j in range(len(mat[0])):
if rowSums[i] == 1 and colSums[j] == 1 and mat[i][j] == 1:
count +=1
return count | special-positions-in-a-binary-matrix | Python | 97% Time | tq326 | 0 | 30 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,288 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1864972/Python-easy-to-read-and-understand | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
row, col = [0 for _ in range(m)], [0 for _ in range(n)]
for i in range(m):
for j in range(n):
col[j] += mat[i][j]
for j in range(n):
for i in range(m):
row[i] += mat[i][j]
ans = 0
for i in range(m):
for j in range(n):
if mat[i][j] == 1 and row[i] == 1 and col[j] == 1:
ans += 1
return ans | special-positions-in-a-binary-matrix | Python easy to read and understand | sanial2001 | 0 | 106 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,289 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1849998/5-Lines-Python-Solution-oror-85-Faster-oror-Memory-less-than-60 | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
C=list(map(list,zip(*mat))) ; ans=0
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j]==1 and sum(mat[i])==1 and sum(C[j])==1: ans+=1
return ans | special-positions-in-a-binary-matrix | 5-Lines Python Solution || 85% Faster || Memory less than 60% | Taha-C | 0 | 77 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,290 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1837550/Python-Easy-to-understand-Solution | class Solution(object):
def numSpecial(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
sum_row = []
sum_col = []
special = 0
for row in mat:
sum_row.append(sum(row))
for col in zip(*mat):
sum_col.append(sum(col))
for row in range(len(mat)):
if sum_row[row] != 1:
continue
for col in range(len(mat[0])):
if sum_col[col] != 1:
continue
if mat[row][col] ==1:
special +=1
return special
``` | special-positions-in-a-binary-matrix | Python Easy to understand Solution | sarvenaz-ch | 0 | 54 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,291 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1759332/Python-dollarolution | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
mat1 = list(zip(*mat))
count = 0
for i in range(len(mat)):
if mat[i].count(1) == 1:
j = mat[i].index(1)
if mat1[j].count(1) == 1:
count += 1
return count | special-positions-in-a-binary-matrix | Python $olution | AakRay | 0 | 74 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,292 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1673477/Python-real-O(mn)-time-and-O(m%2Bn)-space | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
rows, cols = [], []
for row in mat:
rows.append(sum(row))
for col in zip(*mat):
cols.append(sum(col))
count = 0
for i in range(len(mat)):
for j in range(len(mat[0])):
if mat[i][j] == 1 and rows[i] == 1 and cols[j] == 1:
count += 1
return count | special-positions-in-a-binary-matrix | Python, real O(mn) time and O(m+n) space | yaok09 | 0 | 31 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,293 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1068424/Python3-simple-solution | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
count = 0
for i in range(len(mat)):
if sum(mat[i]) == 1:
j = mat[i].index(1)
x = list(zip(*mat))
if sum(x[j]) == 1:
count += 1
return count | special-positions-in-a-binary-matrix | Python3 simple solution | EklavyaJoshi | 0 | 60 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,294 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/920077/No-sumzip-understandable-O(n*m*max(nm))-solution | class Solution:
def valid(self, mat, n, m, i, j):
# checks all entries along that column avoiding double-count
for a in range(n):
if (a != i) and (mat[a][j] == 1):
return False
# checks all entries along that row avoiding double-count
for b in range(m):
if (b != j) and (mat[i][b] == 1):
return False
return True
def numSpecial(self, mat: List[List[int]]) -> int:
count = 0
n = len(mat)
m = len(mat[0])
for i in range(n):
for j in range(m):
if mat[i][j] == 1 and self.valid(mat, n, m, i, j):
count += 1
return count
`` | special-positions-in-a-binary-matrix | No sum/zip understandable O(n*m*max(n,m)) solution | JuanTheDoggo | 0 | 47 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,295 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/869582/Easy-6-line-python-beats-99.5 | class Solution(object):
def numSpecial(self, mat):
row,col,count,x = len(mat),len(mat[0]),0,[sum(col) for col in zip(*mat)]
for i in range(row):
for j in range(col):
if mat[i][j]==1 and sum(mat[i])==1 and x[j]==1:
count+=1
return count | special-positions-in-a-binary-matrix | Easy 6 line python beats 99.5% | rachitsxn292 | 0 | 191 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,296 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/850504/python3-self-explanatory | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
r = len(mat)
c = len(mat[0])
special = 0
def checkCol(i,j,mat):
c = 0
for x in range(r):
if mat[x][j] == 1:
c += 1
return c == 1
for i in range(r):
for j in range(c):
if mat[i][j] == 1:
temp = mat[i][:j] + mat[i][j+1:]
if temp.count(1) == 0 and checkCol(i,j,mat):
special += 1
return(special) | special-positions-in-a-binary-matrix | python3 self explanatory | harshalkpd93 | 0 | 76 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,297 |
https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/844056/Python-3-or-Hash-Table-O(MN)-or-Explanations | class Solution:
def numSpecial(self, mat: List[List[int]]) -> int:
ans, m, n = 0, len(mat), len(mat[0])
row, col = [0] * m, [0] * n
for i in range(m):
for j in range(n):
row[i] += mat[i][j]
col[j] += mat[i][j]
for i in range(m):
for j in range(n):
if mat[i][j] and row[i] == 1 and col[j] == 1: ans += 1; break
return ans | special-positions-in-a-binary-matrix | Python 3 | Hash Table O(MN) | Explanations | idontknoooo | 0 | 92 | special positions in a binary matrix | 1,582 | 0.654 | Easy | 23,298 |
https://leetcode.com/problems/count-unhappy-friends/discuss/1103620/Readable-python-solution | class Solution:
def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
def find_preferred_friends(x: int) -> List[int]:
"""
Returns friends of x that have a higher preference than partner.
"""
partner = partners[x] # Find the partner of x.
x_friends = friend_prefs[x] # Find all the friends of x.
partner_ranking = x_friends[partner] # Get the partner's ranking amongst those friends.
return list(x_friends)[:partner_ranking] # Return all friends with a preferred lower ranking.
def is_unhappy(x: int) -> bool:
"""
Returns True if person x is unhappy, otherwise False.
"""
# Find the partner for person x.
partner = partners[x]
# Find the friends that person x prefers more than this partner.
preferred_friends = find_preferred_friends(x)
# A friend is unhappy with their partner if there is another friend with a higher preference
# and that friend prefers them over their partner.
return any(friend_prefs[friend][x] <= friend_prefs[friend][partners[friend]]
for friend in preferred_friends)
# Create dictionary to lookup friend preference for any person.
friend_prefs = {
person: {friend: pref for pref, friend in enumerate(friends)}
for person, friends in enumerate(preferences)
}
# Example:
# {0: {1: 0, 3: 1, 2: 2},
# 1: {2: 0, 3: 1, 0: 2},
# 2: {1: 0, 3: 1, 0: 2},
# 3: {0: 0, 2: 1, 1: 2}}
# Create dictionary to find anyone's partner.
partners = {}
for x, y in pairs:
partners[x] = y
partners[y] = x
# Count and return the number of unhappy people.
return sum(is_unhappy(person) for person in range(n)) | count-unhappy-friends | Readable python solution | alexanco | 3 | 325 | count unhappy friends | 1,583 | 0.603 | Medium | 23,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.