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/remove-all-occurrences-of-a-substring/discuss/2517608/Python-or-Solution-or-Easy-to-read-and-understand
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while(part in s):
index = s.find(part)
s = s[0:index] + s[index + len(part):]
return s
|
remove-all-occurrences-of-a-substring
|
Python | Solution | Easy to read and understand
|
Wartem
| 0
| 69
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,000
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2509095/Python3-Solution-with-using-stack
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
stack = []
for char in s:
stack.append(char)
if len(stack) >= len(part):
if ''.join(stack[-len(part):]) == part:
for _ in range(len(part)):
stack.pop()
return ''.join(stack)
|
remove-all-occurrences-of-a-substring
|
[Python3] Solution with using stack
|
maosipov11
| 0
| 36
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,001
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2180270/Easy-python-solution-using-index-lookup-75-speed-mem
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
m, n = len(s), len(part)
i = 0
while i < m - n +1:
if part in s:
i = s.index(part)
s = s[:i] + s[i+n:]
else:
break
return s
|
remove-all-occurrences-of-a-substring
|
Easy python solution using index lookup - 75% speed, mem
|
user2855PM
| 0
| 24
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,002
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2157657/python-easy-to-read-and-understand-or-stack
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
res = ''
for i in s:
res = res+i
while len(res) >= len(part):
#print(res)
index = len(res)-len(part)
if res[index:] == part:
temp = res[:index]
res = temp
else:
break
return res
|
remove-all-occurrences-of-a-substring
|
python easy to read and understand | stack
|
sanial2001
| 0
| 57
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,003
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/2088490/Not-use-functions-use-basic-pointer-to-solve-this-problem
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
#k is the pointer
k=0
while k<=len(s)-len(part):
if s[k:k+len(part)]==part:
if k==0:
s=s[k+len(part):]
elif k==len(s)-len(part):
s=s[:k]
else:
s=s[:k]+s[k+len(part):]
#k minus len(part), because substring before k may consist of the 'part'
k-=len(part)
k+=1
return s
|
remove-all-occurrences-of-a-substring
|
Not use functions, use basic pointer to solve this problem
|
XRFXRF
| 0
| 40
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,004
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1787513/Python-Easy-Solution...
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
for i in range(len(s)):
s=s.replace(part,"",1)
return s
|
remove-all-occurrences-of-a-substring
|
Python Easy Solution...
|
AjayKadiri
| 0
| 40
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,005
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1452529/Explanation-using-stack
|
class Solution(object):
def removeOccurrences(self, s, p):
st=[]
for i ,v in enumerate(s):
st.append(v)
if len(st)>=len(p) and v==p[-1]:
j=len(p)
sl=len(st)
while j>0 and sl>0 and st[sl-1]==p[j-1]:
sl-=1
j-=1
if j>1:
sl=len(st)
st=st[:sl]
#print (st)
return "".join(st)
|
remove-all-occurrences-of-a-substring
|
Explanation using stack
|
paul_dream
| 0
| 192
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,006
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1344090/Python-simple-fast-stack
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
stack = ''
for i in range(len(s)+1):
while stack[-len(part):] == part:
stack = stack[:-len(part)]
stack = stack + s[i] if i < len(s) else stack
return stack
|
remove-all-occurrences-of-a-substring
|
[Python] simple fast stack
|
cruim
| 0
| 158
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,007
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1328021/Python-3-or-Faster-Beats-98-and-Most-Easiest-Solution
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while(part in s):
s=s.replace(part,"",1)
return s
|
remove-all-occurrences-of-a-substring
|
Python 3 | Faster Beats 98% and Most Easiest Solution
|
ankurgupta_
| 0
| 295
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,008
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1315886/Python-3-Prefix-function-or-O(n%2Bm)-T-or-O(n%2Bm)-S
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
def prefix_function(string):
result = [0] * len(string)
for i in range(1, len(string)):
k = result[i - 1]
while k > 0 and string[i] != string[k]:
k = result[k-1]
if string[i] == string[k]:
k += 1
result[i] = k
return result
pi = prefix_function(part)
stack = []
iter_index, index = 0, 0
while iter_index < len(s):
ch = s[iter_index]
if part[index] == ch:
index += 1
stack.append((ch, index))
if index == len(part):
for _ in range(len(part)):
stack.pop()
if len(stack) > 0:
_, index = stack[-1]
else:
index = 0
elif index > 0:
index = pi[index-1]
iter_index -= 1
else:
stack.append((ch, index))
iter_index += 1
return ''.join(ch for ch, _ in stack)
|
remove-all-occurrences-of-a-substring
|
Python 3 Prefix function | O(n+m) T | O(n+m) S
|
CiFFiRO
| 0
| 50
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,009
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1306156/Python-easy-to-understand
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s=s.replace(part,"",1)
return s
|
remove-all-occurrences-of-a-substring
|
Python easy-to-understand
|
mk_mohtashim
| 0
| 95
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,010
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1302571/Python3-Simplest-solution-100-faster-than-all-submissions
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
len_part = len(part)
while True:
index = s.find(part)
if index == -1:
break
else:
s = s[:index] + s[index + len_part:]
return s
|
remove-all-occurrences-of-a-substring
|
[Python3] Simplest solution, 100% faster than all submissions
|
GauravKK08
| 0
| 40
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,011
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1299658/Python3-solution-using-replace()-method
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part,'')
return s
|
remove-all-occurrences-of-a-substring
|
Python3 solution using replace() method
|
EklavyaJoshi
| 0
| 23
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,012
|
https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1299658/Python3-solution-using-replace()-method
|
class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
if part in s:
a = s.index(part)
return self.removeOccurrences(s[:a] + s[a+len(part):], part)
else:
return s
|
remove-all-occurrences-of-a-substring
|
Python3 solution using replace() method
|
EklavyaJoshi
| 0
| 23
|
remove all occurrences of a substring
| 1,910
| 0.742
|
Medium
| 27,013
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298531/4-lines-oror-96-faster-oror-Easy-approach
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
ma=0
mi=0
for num in nums:
ma=max(ma,num-mi)
mi=min(mi,num-ma)
return ma
|
maximum-alternating-subsequence-sum
|
📌 4 lines || 96% faster || Easy-approach 🐍
|
abhi9Rai
| 7
| 358
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,014
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/2167909/DP-and-DFS-or-Very-Clearly-Explained!-or-O(n)-Time
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
dp = [[0,0] for _ in range(n)] # initialize dp
dp[0][0] = nums[0] # pre-define
dp[0][1] = 0 # pre-define
for i in range(1, n): # iterate through nums starting from index 1
dp[i][0] = max(nums[i] + dp[i-1][1], dp[i-1][0]) # find which value is higher between choosing or not choosing when the last value is plus.
dp[i][1] = max(-nums[i] + dp[i-1][0], dp[i-1][1]) # find which value is higher between choosing or not choosing when the last value is minus.
return max(dp[-1]) # find the maximum of the last array of dp of whether the last value is plus or minus, this will be our answer.
|
maximum-alternating-subsequence-sum
|
🔥 DP and DFS | Very Clearly Explained! | O(n) Time
|
PythonerAlex
| 6
| 152
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,015
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/2167909/DP-and-DFS-or-Very-Clearly-Explained!-or-O(n)-Time
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
@cache
def dfs(i: int, p: bool) -> int:
if i>=n:
return 0
# if choose
num = nums[i] if p else -nums[i]
choose = num + dfs(i+1, not p)
# if not choose
not_choose = dfs(i+1, p)
return max(choose, not_choose)
return dfs(0, True)
|
maximum-alternating-subsequence-sum
|
🔥 DP and DFS | Very Clearly Explained! | O(n) Time
|
PythonerAlex
| 6
| 152
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,016
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1539208/Python-3-or-DP-O(N)-or-Explanation
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
# even: max alternating sum of an even-length subsequence
# odd: max alternating sum of an odd-length subsequence
even = odd = 0
for num in nums:
even, odd = max(even, odd-num), max(odd, even+num)
return max(even, odd)
|
maximum-alternating-subsequence-sum
|
Python 3 | DP, O(N) | Explanation
|
idontknoooo
| 4
| 269
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,017
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298474/Python3-alternating-peaks-and-valleys
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
vals = []
for x in nums:
if not vals or vals[-1] != x:
vals.append(x)
peaks, valleys = [], []
for i in range(len(vals)):
if (-inf if i == 0 else vals[i-1]) < vals[i] > (-inf if i+1 == len(vals) else vals[i+1]): peaks.append(vals[i])
if 0 < i < len(vals)-1 and vals[i-1] > vals[i] < vals[i+1]: valleys.append(vals[i])
if len(peaks) == len(valleys): valleys.pop()
return sum(peaks) - sum(valleys)
|
maximum-alternating-subsequence-sum
|
[Python3] alternating peaks & valleys
|
ye15
| 3
| 129
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,018
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298474/Python3-alternating-peaks-and-valleys
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
return sum(max(0, nums[i-1] - nums[i]) for i in range(1, len(nums))) + nums[-1]
|
maximum-alternating-subsequence-sum
|
[Python3] alternating peaks & valleys
|
ye15
| 3
| 129
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,019
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/2295791/Python-Easy-memoization
|
class Solution(object):
def maxAlternatingSum(self, nums):
dp = {}
def max_sum(arr,i,add = False):
if i>=len(arr):
return 0
if (i,add) in dp:
return dp[(i,add)]
nothing = max_sum(arr,i+1, add)
if not add:
added = max_sum(arr,i+1,True) + arr[i]
dp[(i,add)] = max(added,nothing)
elif add:
subs = max_sum(arr,i+1, False) -arr[i]
dp[(i,add)] = max(nothing, subs)
return dp[(i,add)]
return max_sum(nums,0)
|
maximum-alternating-subsequence-sum
|
Python Easy memoization
|
Abhi_009
| 1
| 48
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,020
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1410393/Python-Another-way-to-think-about-greedy
|
class Solution:
# 996 ms, 99.7%. Time: O(N). Space: O(N)
def maxAlternatingSum(self, nums: List[int]) -> int:
seq = [nums[0]] # to store the sequence
inc = True # flag for increasing/decreasing
for n1, n2 in zip(nums, nums[1:]):
if (n2 > n1) == inc: # same as if (n2 > n1 and inc == True) or (n2 <= 1 and inc == False)
seq[-1] = n2 # we always choose the best option as noted above.
else:
# else, use it as new valid and flip the flag.
seq.append(n2)
inc = not inc
# we always want odd-length seq because we exclude the last odd-index number.
if len(seq) % 2 == 0: seq.pop()
return sum(seq[::2]) - sum(seq[1::2])
|
maximum-alternating-subsequence-sum
|
[Python] Another way to think about greedy
|
JummyEgg
| 1
| 140
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,021
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/2731451/Python3-or-easy-solution
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
nums = [0] + nums
ans = 0
for i in range(1,len(nums)):
if(nums[i]-nums[i-1]>0):
ans+=nums[i]-nums[i-1]
return ans
|
maximum-alternating-subsequence-sum
|
Python3 | easy solution
|
ty2134029
| 0
| 3
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,022
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/2571320/Python-Memo-or-Recursion
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
memo = {}
def dp(index,count):
if index>=len(nums):
return 0
elif (index,count) in memo:
return memo[(index,count)]
else:
if count:
m = max(dp(index+1,False)+nums[index],dp(index+1,count))
else:
m = max(dp(index+1,True)-nums[index],dp(index+1,count))
memo[(index,count)] = m
return memo[(index,count)]
return dp(0,True)
|
maximum-alternating-subsequence-sum
|
Python Memo | Recursion
|
Brillianttyagi
| 0
| 26
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,023
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/2058829/python3-dp-solution-for-reference.
|
class Solution:
def maxAlternatingSum(self, nums) -> int:
N = len(nums)
dp = [[0,0] for _ in range(N)]
dp[0] = [nums[0], 0]
ans = nums[0]
for n in range(1, N):
a, b = max(nums[n], dp[n-1][0], dp[n-1][1]+nums[n]), max(dp[n-1][1], dp[n-1][0]-nums[n])
ans = max(ans, a, b)
dp[n] = [a,b]
return ans
|
maximum-alternating-subsequence-sum
|
[python3] dp solution for reference.
|
vadhri_venkat
| 0
| 48
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,024
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298661/Python-just-like-wiggle-subsequence-O(N)-O(1)
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
inc=nums[0]
turn=-1
f=False
dec=0
for x in range(len(nums)):
dec=max(dec,inc-nums[x])
inc=max(inc, dec+nums[x])
return max(inc,dec)
|
maximum-alternating-subsequence-sum
|
Python, just like wiggle subsequence O(N), O(1)
|
abhinav4202
| 0
| 91
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,025
|
https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298464/Python-O(N)-Time-O(N)-space
|
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
dp_odd = [0]*n
dp_even = [0]*n
dp_even[0] = nums[0]
max_even = nums[0]
max_odd = 0
ans = nums[0]
i = 1
while i<n:
dp_odd[i] = max_even - nums[i]
dp_even[i] = max_odd + nums[i]
max_even = max(max_even, dp_even[i])
max_odd = max(max_odd,dp_odd[i] )
ans = max(ans, dp_odd[i], dp_even[i])
i += 1
return ans
|
maximum-alternating-subsequence-sum
|
Python O(N) Time O(N) space
|
the_buggy_soul
| 0
| 60
|
maximum alternating subsequence sum
| 1,911
| 0.593
|
Medium
| 27,026
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2822079/Python-oror-96.20-Faster-oror-2-Lines-oror-Sorting
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]*nums[-2])-(nums[0]*nums[1])
|
maximum-product-difference-between-two-pairs
|
Python || 96.20% Faster || 2 Lines || Sorting
|
DareDevil_007
| 1
| 44
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,027
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1988209/Python-Easiest-Solution-With-Explanation-or-Sorting-or-Beg-to-adv
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort() # sorting the list, to access first 2 lowest elems & 2 highest elems as we have to calulate max diff of pairs after product.
prod_pair_1 = nums[0] * nums[1] # product of 2 lowest elems in the list.
prod_pair_2 = nums[-1] * nums[-2] # product of 2 highest elems in the list.
max_diff = prod_pair_2 - prod_pair_1 # calulating the diff of the product of the above mentioend two paris.
return max_diff # returning the max difference bet the product.
|
maximum-product-difference-between-two-pairs
|
Python Easiest Solution With Explanation | Sorting | Beg to adv
|
rlakshay14
| 1
| 59
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,028
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1900027/Easiest-solutions-with-O(nlogn)-and-O(n)-Time-Complexity-and-O(1)-Space-Complexity
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[len(nums)-1]*nums[len(nums)-2]) - (nums[0]*nums[1])
|
maximum-product-difference-between-two-pairs
|
Easiest solutions with O(nlogn) and O(n) Time Complexity and O(1) Space Complexity
|
Shewe_codes
| 1
| 63
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,029
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1900027/Easiest-solutions-with-O(nlogn)-and-O(n)-Time-Complexity-and-O(1)-Space-Complexity
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
m,n= max(nums),min(nums)
nums.remove(m)
nums.remove(n)
return (m*max(nums)) - (n*min(nums))
|
maximum-product-difference-between-two-pairs
|
Easiest solutions with O(nlogn) and O(n) Time Complexity and O(1) Space Complexity
|
Shewe_codes
| 1
| 63
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,030
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1538479/One-pass-to-find-4-values-99-speed
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
min1 = min2 = inf
max1 = max2 = 0
for n in nums:
if n < min1:
min2 = min1
min1 = n
elif n < min2:
min2 = n
if n > max2:
max1 = max2
max2 = n
elif n > max1:
max1 = n
return max1 * max2 - min1 * min2
|
maximum-product-difference-between-two-pairs
|
One pass to find 4 values, 99% speed
|
EvgenySH
| 1
| 127
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,031
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1383351/Python-3-heapq-simple-and-fast-time-O(n)-space-O(1)
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
maxs = nums[:4]
mins = []
heapify(maxs)
heappush(mins, -heappop(maxs))
heappush(mins, -heappop(maxs))
for n in nums[4:]:
if n > maxs[0]:
n = heappushpop(maxs, n)
if n < -mins[0]:
heappushpop(mins, -n)
return maxs[0] * maxs[1] - mins[0] * mins[1]
|
maximum-product-difference-between-two-pairs
|
Python 3, heapq, simple and fast, time O(n), space O(1)
|
MihailP
| 1
| 137
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,032
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1302045/Python3-simple-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max1 = max(nums)
nums.remove(max1)
max2 = max(nums)*max1
min1 = min(nums)
nums.remove(min1)
min2 = min(nums)*min1
return max2-min2
|
maximum-product-difference-between-two-pairs
|
Python3 simple solution
|
Sanyamx1x
| 1
| 171
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,033
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2843386/1-Line-Solution-Python3
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
return ((sorted(nums)[-1]*sorted(nums)[-2])-(sorted(nums)[0]*sorted(nums)[1]))
|
maximum-product-difference-between-two-pairs
|
1 Line Solution Python3
|
vovatoshev1986
| 0
| 1
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,034
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2839405/Python-or-Faster-then-98-people-or-Simple
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
p=sorted(nums)
return (p[-1]*p[-2])-(p[0]*p[1])
|
maximum-product-difference-between-two-pairs
|
Python | Faster then 98% people | Simple
|
priyanshupriyam123vv
| 0
| 2
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,035
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2835773/Python3-Linear-Time-Solution-(One-Pass)
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
# initialize minimum and second minimum of the array
minmin = float('inf')
mined = float('inf')
# intialize maximum and second maximum
maxmax = 0
maxed = 0
# make one pass through the array
for num in nums:
# the number is smaller than the minimum
if num < minmin:
# bubble minimum up to second minimum
mined = minmin
# save the number as minimum
minmin = num
# the number is smaller than the second minimum
elif num < mined:
# save the number
mined = num
# the number is bigger than the maximum
if num > maxmax:
# push old maximum down
maxed = maxmax
# save the number
maxmax = num
# the number is bigger than the secod maximum
elif num > maxed:
# save the number
maxed = num
return maxmax*maxed - minmin*mined
|
maximum-product-difference-between-two-pairs
|
[Python3] - Linear Time Solution (One-Pass)
|
Lucew
| 0
| 1
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,036
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2831478/Python-Solution
|
class Solution:
def maxProductDifference(self, nums: list[int]):
max_nums = max(nums)
min_nums = min(nums)
nums.remove(max_nums)
nums.remove(min_nums)
max_1_nums = max(nums)
min_1_nums = min(nums)
product = (max_nums) * (max_1_nums) - (min_nums) * (min_1_nums)
return product
|
maximum-product-difference-between-two-pairs
|
Python Solution
|
heli_kolambekar
| 0
| 1
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,037
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2819002/Python-2-Line-Solution-Easy
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
s = sorted(nums)
return ((s[-1] * s[-2]) - (s[0] * s[1]))
|
maximum-product-difference-between-two-pairs
|
Python 2 Line Solution Easy
|
Jashan6
| 0
| 1
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,038
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2814233/Python3-Time-O(N)-Space-O(1)-NO-SORTing
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
first_small, second_small = 10**4 + 1, 10**4 + 1
first_big, second_big = -1, -1 # first_big > second_big
for num in nums:
if num < first_small:
second_small = first_small
first_small = num
elif num < second_small:
second_small = num
if num > first_big:
second_big = first_big
first_big = num
elif num > second_big:
second_big = num
return (first_big * second_big) - (first_small * second_small)
|
maximum-product-difference-between-two-pairs
|
[Python3] Time = O(N), Space = O(1), NO SORTing
|
SoluMilken
| 0
| 1
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,039
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2788170/Max-diffrence-between-two-pairs
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
maxprod = nums[len(nums)-1] * nums[len(nums)-2]
minprod = nums[0] * nums[1]
return maxprod - minprod
|
maximum-product-difference-between-two-pairs
|
Max diffrence between two pairs
|
khanismail_1
| 0
| 5
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,040
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2750907/one-line-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
return sorted(nums)[-1]*sorted(nums)[-2] - sorted(nums)[0]*sorted(nums)[1]
|
maximum-product-difference-between-two-pairs
|
one line solution
|
user6046z
| 0
| 2
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,041
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2735982/Python3-Solution-Simple-two-lines
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return abs(nums[0]*nums[1] - nums[-1]*nums[-2])
|
maximum-product-difference-between-two-pairs
|
Python3 Solution Simple - two lines
|
sipi09
| 0
| 2
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,042
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2661927/python-easy-2-line-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums=sorted(nums)
return (abs((nums[0]*nums[1])-(nums[-1]*nums[-2])))
|
maximum-product-difference-between-two-pairs
|
python easy 2 line solution
|
lalli307
| 0
| 1
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,043
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2622616/simple-python-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
small = nums[0] * nums[1]
large = nums[-1] * nums[-2]
return large - small
|
maximum-product-difference-between-two-pairs
|
simple python solution
|
Gilbert770
| 0
| 8
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,044
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2576564/Python3-oror-Best-Solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max1 = max2 = -1
min1 = min2 = float('inf')
for i in range(len(nums)):
if nums[i]>max1:
max2 = max1
max1 = nums[i]
else:
max2 = max(max2,nums[i])
for i in range(len(nums)-1,-1,-1):
if nums[i]<min1:
min2 = min1
min1 = nums[i]
else:
min2 = min(min2,nums[i])
return (max1*max2)-(min1*min2)
|
maximum-product-difference-between-two-pairs
|
Python3 || Best Solution
|
shacid
| 0
| 4
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,045
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2554396/EASY-PYTHON3-SOLUTION
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]*nums[-2])-(nums[0]*nums[1])
|
maximum-product-difference-between-two-pairs
|
✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔
|
rajukommula
| 0
| 12
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,046
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2523426/2-Line-Solution-Python
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]*nums[-2]) - (nums[0]*nums[1])
|
maximum-product-difference-between-two-pairs
|
2 Line Solution - Python
|
cyberl0rd
| 0
| 24
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,047
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2432151/PYTHON-3-easy-two-liner-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return ((nums[-1]*nums[-2])-(nums[0]*nums[1]))
|
maximum-product-difference-between-two-pairs
|
PYTHON 3 easy two-liner solution
|
trickycat10
| 0
| 24
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,048
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2398653/Simple-Python-Solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
a,b = nums[0],nums[1]
c,d = nums[-2],nums[-1]
diff = a*b-c*d
return abs(diff)
|
maximum-product-difference-between-two-pairs
|
Simple Python Solution
|
NishantKr1
| 0
| 25
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,049
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2389083/Solved-using-sort-function
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
sorted_nums = sorted(nums)
w, x, y, z = sorted_nums[0], sorted_nums[1], sorted_nums[-2], sorted_nums[-1]
return (y * z) - (w * x)
|
maximum-product-difference-between-two-pairs
|
Solved using sort function
|
samanehghafouri
| 0
| 2
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,050
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2375838/Python3-Solution-with-using-sorting
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
if len(nums) < 4:
return 0
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
|
maximum-product-difference-between-two-pairs
|
[Python3] Solution with using sorting
|
maosipov11
| 0
| 5
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,051
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2263649/Python-solution-O(N)-time-complexity-and-O(1)-space-complexity
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max1=0 #the greatest number
max2=0 #the 2nd greatest number
min1=10000 #the lowest number
min2=10000 #the 2nd lowest number
for i in nums:
if i>max1:
max2=max1
max1=i
elif i>max2:
max2=i
if i<min1:
min2=min1
min1=i
elif i<min2:
min2=i
return (max1*max2-min2*min1)
|
maximum-product-difference-between-two-pairs
|
Python solution O(N) time complexity and O(1) space complexity
|
thunder34
| 0
| 15
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,052
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1875184/Python-dollarolution-(98-Faster-and-95-better-memory)
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
x1,x2 = 0,0
y1,y2 = 10**5,10**5
for i in nums:
if i > x2:
if i > x1:
x2, x1 = x1, i
else:
x2 = i
if i < y2:
if i < y1:
y2, y1 = y1, i
else:
y2 = i
return (x1*x2) - (y1*y2)
|
maximum-product-difference-between-two-pairs
|
Python $olution (98% Faster & 95% better memory)
|
AakRay
| 0
| 43
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,053
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1837054/Simple-Python-Solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1]*nums[-2] - nums[0]*nums[1]
|
maximum-product-difference-between-two-pairs
|
Simple Python Solution
|
himanshu11sgh
| 0
| 27
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,054
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1818668/2-Lines-Python-Solution-oror-87-Faster-oror-Memory-less-than-10
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1]*nums[-2] - nums[0]*nums[1]
|
maximum-product-difference-between-two-pairs
|
2-Lines Python Solution || 87% Faster || Memory less than 10%
|
Taha-C
| 0
| 43
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,055
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1798550/Python-3-O(n)
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max_num = self.max_number(nums)
nums.remove(max_num)
sec_max_num = self.max_number(nums)
min_num = self.min_number(nums)
nums.remove(min_num)
sec_min_num = self.min_number(nums)
return (max_num * sec_max_num) - (min_num * sec_min_num)
def max_number(self, nums: List[int]) -> int:
max_num = nums[0]
for i in range(len(nums)):
if max_num < nums[i]:
max_num = nums[i]
return max_num
def min_number(self, nums: List[int]) -> int:
min_num = nums[0]
for i in range(len(nums)):
if min_num > nums[i]:
min_num = nums[i]
return min_num
|
maximum-product-difference-between-two-pairs
|
Python 3 O(n)
|
AprDev2011
| 0
| 22
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,056
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1768564/Python3-Simple-1-Liner
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
return nums.pop(nums.index(max(nums)))*nums.pop(nums.index(max(nums))) - nums.pop(nums.index(min(nums)))*nums.pop(nums.index(min(nums)))
|
maximum-product-difference-between-two-pairs
|
Python3 Simple 1-Liner
|
ATNemeth
| 0
| 34
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,057
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1654668/Using-sort()-in-Python-3
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
array1 = sorted(nums)
product = (array1[len(array1)-1] * array1[len(array1)-2]) - (array1[0] * array1[1])
return product
|
maximum-product-difference-between-two-pairs
|
Using sort() in Python 3
|
piyushkumarpiyushkumar6
| 0
| 37
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,058
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1587810/two-simple-solutions-or-python-or-faster-than-~100
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max1 = max(nums)
nums.pop(nums.index(max1))
max2 = max(nums)
min1 = min(nums)
nums.pop(nums.index(min1))
min2 = min(nums)
return max1*max2 - min1*min2
|
maximum-product-difference-between-two-pairs
|
two simple solutions | python | faster than ~100%
|
anandanshul001
| 0
| 95
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,059
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1587810/two-simple-solutions-or-python-or-faster-than-~100
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]*nums[-2] - nums[0]*nums[1])
|
maximum-product-difference-between-two-pairs
|
two simple solutions | python | faster than ~100%
|
anandanshul001
| 0
| 95
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,060
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1540770/O(n)-time-%2B-O(1)-space-solution-on-Python
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
it = iter(nums)
prev, m = 0, next(it)
prev_min, _min = 10 ** 4 + 1, m
for k in it:
if k > m:
prev, m = m, k
elif k > prev:
prev = k
if k < _min:
prev_min, _min = _min, k
elif k < prev_min:
prev_min = k
return m * prev - prev_min * _min
|
maximum-product-difference-between-two-pairs
|
O(n)-time + O(1)-space solution on Python
|
mousun224
| 0
| 74
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,061
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1447584/Easy-to-understand-python-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums = sorted(nums)
return (nums[-1]*nums[-2] - nums[0]*nums[1])
|
maximum-product-difference-between-two-pairs
|
Easy to understand python solution
|
sid_upadhyayula
| 0
| 80
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,062
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1440949/Faster-than-99-and-easy-to-understand-Python-solution
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
counter = 0
new_list = []
while counter <= 1:
max_num = max(nums)
new_list.append(max_num)
nums.remove(max_num)
counter += 1
while 1 < counter <= 3:
min_num = min(nums)
new_list.append(min_num)
nums.remove(min_num)
counter += 1
return ((new_list[0]*new_list[1]) - (new_list[2] * new_list[3]))
|
maximum-product-difference-between-two-pairs
|
Faster than 99% and easy to understand Python solution
|
zhivkob
| 0
| 104
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,063
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1413953/Python3-Faster-than-91.92-of-the-Solutions-O(n)-approach
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
max1 = 0
max2 = 0
min1 = 10001
min2 = 10001
for num in nums:
if num >= max1:
max2 = max1
max1 = num
elif num < max1 and num >= max2:
max2 = num
if num <= min1:
min2 = min1
min1 = num
elif num > min1 and num <= min2:
min2 = num
print(max1,max2)
print(min1,min2)
return max1*max2-min1*min2
|
maximum-product-difference-between-two-pairs
|
Python3 - Faster than 91.92% of the Solutions - O(n) approach
|
harshitgupta323
| 0
| 84
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,064
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1334067/Python%3A-Faster-than-95.-O(nlogn)-and-O(1)-with-explaination
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
"""The product difference is maximum when one pair is smallest
and one pair is largest.
Idea is to sort the array and choose first two and last two elements.
"""
nums.sort()
return nums[-1]*nums[-2] - nums[0]*nums[1]
|
maximum-product-difference-between-two-pairs
|
Python: Faster than 95%. O(nlogn) and O(1) with explaination
|
er1shivam
| 0
| 103
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,065
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1299712/Python-or-Heapify-or-O(n)-Time-O(1)-Space
|
class Solution:
def get_product(self, nums):
heapq.heapify(nums)
return heapq.heappop(nums) * heapq.heappop(nums)
def maxProductDifference(self, nums: List[int]) -> int:
min_prod = self.get_product(nums)
for i in range(len(nums)): nums[i] = -nums[i]
max_prod = self.get_product(nums)
return max_prod - min_prod
|
maximum-product-difference-between-two-pairs
|
Python | Heapify | O(n) Time O(1) Space
|
leeteatsleep
| 0
| 92
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,066
|
https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/1299521/Python3-greedy
|
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
|
maximum-product-difference-between-two-pairs
|
[Python3] greedy
|
ye15
| 0
| 39
|
maximum product difference between two pairs
| 1,913
| 0.814
|
Easy
| 27,067
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1299526/Python3-brute-force
|
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0]) # dimensions
for r in range(min(m, n)//2):
i = j = r
vals = []
for jj in range(j, n-j-1): vals.append(grid[i][jj])
for ii in range(i, m-i-1): vals.append(grid[ii][n-j-1])
for jj in range(n-j-1, j, -1): vals.append(grid[m-i-1][jj])
for ii in range(m-i-1, i, -1): vals.append(grid[ii][j])
kk = k % len(vals)
vals = vals[kk:] + vals[:kk]
x = 0
for jj in range(j, n-j-1): grid[i][jj] = vals[x]; x += 1
for ii in range(i, m-i-1): grid[ii][n-j-1] = vals[x]; x += 1
for jj in range(n-j-1, j, -1): grid[m-i-1][jj] = vals[x]; x += 1
for ii in range(m-i-1, i, -1): grid[ii][j] = vals[x]; x += 1
return grid
|
cyclically-rotating-a-grid
|
[Python3] brute-force
|
ye15
| 24
| 988
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,068
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1299564/Simple-Approach-oror-Well-explained-oror-95-faster
|
class Solution:
def rotateGrid(self, mat: List[List[int]], k: int) -> List[List[int]]:
top = 0
bottom = len(mat)-1
left = 0
right = len(mat[0])-1
res = []
# storing in res all the boundry matrix elements.
while left<right and top<bottom:
local=[]
for i in range(left,right+1):
local.append(mat[top][i])
top+=1
for i in range(top,bottom+1):
local.append(mat[i][right])
right-=1
for i in range(right,left-1,-1):
local.append(mat[bottom][i])
bottom-=1
for i in range(bottom,top-1,-1):
local.append(mat[i][left])
left+=1
res.append(local)
# rotating the elements by k.
for ele in res:
l=len(ele)
r=k%l
ele[::]=ele[r:]+ele[:r]
# Again storing in the matrix.
top = 0
bottom = len(mat)-1
left = 0
right = len(mat[0])-1
while left<right and top<bottom:
local=res.pop(0)
for i in range(left,right+1):
mat[top][i] = local.pop(0)
top+=1
for i in range(top,bottom+1):
mat[i][right] = local.pop(0)
right-=1
for i in range(right,left-1,-1):
mat[bottom][i] = local.pop(0)
bottom-=1
for i in range(bottom,top-1,-1):
mat[i][left] = local.pop(0)
left+=1
return mat
|
cyclically-rotating-a-grid
|
📌 Simple-Approach || Well-explained || 95% faster 🐍
|
abhi9Rai
| 5
| 182
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,069
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1299645/Python3-Rotate-each-layer-or-Clean-Code
|
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
t, b = 0, m - 1
l, r = 0, n - 1
result = [[0] * n for _ in range(m)]
while t < b and l < r:
index = []
index += [[i,l] for i in range(t, b)] # left side
index += [[b,j] for j in range(l, r)] # bottom side
index += [[i,r] for i in range(b, t, -1)] # right side
index += [[t,j] for j in range(r, l, -1)] # top side
rotate = k % len(index)
for i, (x, y) in enumerate(index):
rx, ry = index[(i + rotate) % len(index)]
result[rx][ry] = grid[x][y]
t += 1
b -= 1
l += 1
r -= 1
return result
|
cyclically-rotating-a-grid
|
[Python3] Rotate each layer | Clean Code
|
juihsiuhsu
| 3
| 69
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,070
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1316844/Python-or-Faster-Than-96-or-With-Comments
|
class Solution:
def assign(self, temp, rows, cols, i, j, arr, topL, topR, bottomR, bottomL):
ix = 0
# top row
while j < topR[1]:
temp[i][j] = arr[ix]
ix += 1
j += 1
# last column
while i < bottomR[0]:
temp[i][j] = arr[ix]
ix += 1
i += 1
# last row
while j > bottomL[1]:
temp[i][j] = arr[ix]
ix += 1
j -= 1
# first column
while i > topR[0]:
temp[i][j] = arr[ix]
ix += 1
i -= 1
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows, cols, i, j = len(grid), len(grid[0]), 0, 0
# Marking the 4 points, which will act as boundaries
topLeft, topRight, bottomRight, bottomLeft = [0,0],[0,cols-1],[rows-1, cols-1],[rows-1, 0]
temp = [[-1 for _ in range(cols)] for __ in range(rows) ]
while topLeft[0] < rows//2 and topLeft[0] < cols//2:
arr = []
# top row
while j < topRight[1]:
arr.append(grid[i][j])
j += 1
# last column
while i < bottomRight[0]:
arr.append(grid[i][j])
i += 1
# last row
while j > bottomLeft[1]:
arr.append(grid[i][j])
j -= 1
# first column
while i > topRight[0]:
arr.append(grid[i][j])
i -= 1
n = len(arr)
arr = arr[k % n:] + arr[:k % n] # Taking modulus value
self.assign(temp, rows, cols, i, j, arr,topLeft, topRight, bottomRight, bottomLeft )
i += 1
j += 1
topLeft[0] += 1
topLeft[1] += 1
topRight[0] += 1
topRight[1] -= 1
bottomRight[0] -= 1
bottomRight[1] -= 1
bottomLeft[0] -= 1
bottomLeft[1] += 1
return temp
|
cyclically-rotating-a-grid
|
Python | Faster Than 96% | With Comments
|
paramvs8
| 1
| 163
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,071
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/2850385/Spaghetti-Code-what-did-i-write.....
|
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
#element ordered in row manner, grouped by layer
rows=len(grid)
cols=len(grid[0])
layers=min(rows//2,cols//2)
sliced_grid=[[] for _ in range(layers)]
for i in range(rows):
layers_in_this_row=min(i+1,rows-i)
for j in range(cols):
sliced_grid[min(min(j,cols-j-1),layers_in_this_row-1)].append(grid[i][j])
print(sliced_grid)
#reshape layer, element ordered in clockwise manner
reshaped=[[0 for __ in range(len(slice)) ] for slice in sliced_grid]
for layer,layer_item in enumerate(sliced_grid):
back_trace_id=-1
back=True
top_row_element_count=cols-layer*2
for idx,item in enumerate(layer_item):
if idx<top_row_element_count:
reshaped[layer][idx]=item
elif idx<len(layer_item)-top_row_element_count and back:
reshaped[layer][back_trace_id]=item
back=not back
back_trace_id-=1
elif idx<len(layer_item)-top_row_element_count and not back:
reshaped[layer][idx+back_trace_id+1]=item
back=not back
else:
reshaped[layer][back_trace_id]=item
back_trace_id-=1
print(reshaped)
#reconstruct to traditional row format, rotate by offset
offset=k
reconstruct=[[0 for _ in range(cols)] for _ in range(rows)]
offset_count=[[0,len(reshaped[layer])-1,True] for layer in range(layers)]
for i in range(rows):
layers_in_this_row=min(i+1,rows-i)
for j in range(cols):
layer=min(min(j,cols-j-1),layers_in_this_row-1)
top_row_element_count=cols-layer*2
if offset_count[layer][0]<top_row_element_count:
reconstruct[i][j]=reshaped[layer][(offset+offset_count[layer][0])%len(reshaped[layer])]
offset_count[layer][0]+=1
elif offset_count[layer][0]<len(reshaped[layer])-top_row_element_count and offset_count[layer][2]:
reconstruct[i][j]=reshaped[layer][(offset+offset_count[layer][1])%len(reshaped[layer])]
offset_count[layer][0]+=1
offset_count[layer][1]-=1
offset_count[layer][2] = not offset_count[layer][2]
elif offset_count[layer][0]<len(reshaped[layer])-top_row_element_count and not offset_count[layer][2]:
reconstruct[i][j]=reshaped[layer][(offset+offset_count[layer][0]-(len(reshaped[layer])-offset_count[layer][1]-1))%len(reshaped[layer])]
offset_count[layer][0]+=1
offset_count[layer][2] = not offset_count[layer][2]
else:
reconstruct[i][j]=reshaped[layer][(offset+offset_count[layer][1])%len(reshaped[layer])]
offset_count[layer][1]-=1
print(reconstruct)
return reconstruct
|
cyclically-rotating-a-grid
|
[Spaghetti Code] what did i write.....
|
CodeAnxietyDisorder
| 0
| 1
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,072
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1437044/Python-3-or-Ad-hoc-O(M*N)-or-Explanation
|
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
i, j, r, c = 0, 0, m, n
while i < r and j < c:
values = [] # add current layer to a list for easier rotation
for jj in range(j, c-1):
values.append(grid[i][jj])
for ii in range(i, r-1):
values.append(grid[ii][c-1])
for jj in range(c-1, j, -1):
values.append(grid[r-1][jj])
for ii in range(r-1, i, -1):
values.append(grid[ii][j])
kk = k % len(values) # avoid redundant rotation
values = values[kk:] + values[:kk] # rotate
idx = 0 # overwrite matrix
for jj in range(j, c-1):
grid[i][jj] = values[idx]
idx += 1
for ii in range(i, r-1):
grid[ii][c-1] = values[idx]
idx += 1
for jj in range(c-1, j, -1):
grid[r-1][jj] = values[idx]
idx += 1
for ii in range(r-1, i, -1):
grid[ii][j] = values[idx]
idx += 1
i, j, r, c = i+1, j+1, r-1, c-1
return grid
|
cyclically-rotating-a-grid
|
Python 3 | Ad-hoc, O(M*N) | Explanation
|
idontknoooo
| 0
| 135
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,073
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1366345/Layer-by-layer-88-speed
|
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
rows, cols = len(grid), len(grid[0])
for i in range(min(rows // 2, cols // 2)):
rows1_i, cols1_i = rows - 1 - i, cols - 1 - i
layer_idx = ([(i, j) for j in range(i, cols1_i)] +
[(j, cols1_i) for j in range(i, rows1_i)] +
[(rows1_i, j) for j in range(cols1_i, i, -1)] +
[(j, i) for j in range(rows1_i, i, -1)])
layer = [grid[r][c] for r, c in layer_idx]
shift_idx = k % len(layer)
layer = layer[shift_idx:] + layer[:shift_idx]
for val, (r, c) in zip(layer, layer_idx):
grid[r][c] = val
return grid
|
cyclically-rotating-a-grid
|
Layer by layer, 88% speed
|
EvgenySH
| 0
| 80
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,074
|
https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1300929/Python-3-Rotation-and-reassign-(160ms)
|
class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
ans = [[0] * n for _ in range(m)]
# x, y is starting point; m, n is desired length and width of the layer
def helper(x, y, l, w):
tmp = deque([grid[x][y]])
a, b = 0, 0
# extract all number in the layer
while len(tmp) < 2 * (l + w) - 4:
if a == 0 and b < w - 1:
b += 1
elif b == w - 1 and a < l - 1:
a += 1
elif a == l - 1 and b > 0:
b -= 1
elif b == 0 and a > 0:
a -= 1
tmp.append(grid[x + a][y + b])
# rotate counter-clockwise
tmp.rotate(len(tmp) - k % len(tmp))
# reassign
a, b = 0, 0
ans[x][y] = tmp.popleft()
while tmp:
if a == 0 and b < w - 1:
b += 1
elif b == w - 1 and a < l - 1:
a += 1
elif a == l - 1 and b > 0:
b -= 1
elif b == 0 and a > 0:
a -= 1
ans[x + a][y + b] = tmp.popleft()
x, y = 0, 0
while m >= 2 and n >= 2:
helper(x, y, m, n)
x += 1
y += 1
m -= 2
n -= 2
return ans
|
cyclically-rotating-a-grid
|
[Python 3] Rotation and reassign (160ms)
|
chestnut890123
| 0
| 61
|
cyclically rotating a grid
| 1,914
| 0.481
|
Medium
| 27,075
|
https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1299537/Python3-freq-table-w.-mask
|
class Solution:
def wonderfulSubstrings(self, word: str) -> int:
ans = mask = 0
freq = defaultdict(int, {0: 1})
for ch in word:
mask ^= 1 << ord(ch)-97
ans += freq[mask]
for i in range(10): ans += freq[mask ^ 1 << i]
freq[mask] += 1
return ans
|
number-of-wonderful-substrings
|
[Python3] freq table w. mask
|
ye15
| 11
| 678
|
number of wonderful substrings
| 1,915
| 0.45
|
Medium
| 27,076
|
https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1300877/Python-O(n)-solution-with-comments-Prefix-sum-bit-mask
|
class Solution:
def wonderfulSubstrings(self, word: str) -> int:
# we are representing each char with a bit, 0 for count being even and 1 for odd
# 10 char from a to j
# array to store 2^10 numbers
dp=[0]*1024
# jihgfedcba -> 0000000000
curr=0 # 000..(0-> 10 times)
# since we are starting with curr as 0 make dp[0]=1
dp[0]=1
# result
res=0
for c in word:
# 1<<i sets i th bit to 1 and else to 0
# xor will toggle the bit
curr^= (1<<(ord(c)-ord('a')))
# if curr occurred earlier at j and now at i then [j+1: i] has all zeroes
# this was to count all zeroes case
res+=dp[curr]
# now to check if these 100000..,010000..,001.. cases can be acheived using brute force
# we want to see if curr ^ delta = 10000.. or 010000.. etc
# curr^delta =1000... then
# curr ^ 1000.. = delta
for i in range(10):
res+=dp[curr ^(1<<i)]
dp[curr]+=1
return res
|
number-of-wonderful-substrings
|
Python O(n) solution with comments, Prefix sum, bit mask
|
madhukar0011
| 5
| 587
|
number of wonderful substrings
| 1,915
| 0.45
|
Medium
| 27,077
|
https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1300891/Python-3-Prefix-bit-mask
|
class Solution:
def wonderfulSubstrings(self, word: str) -> int:
n = len(word)
mask = 0
prefix = defaultdict(int)
prefix[0] += 1
ans = 0
for w in word:
mask ^= 1 << (ord(w) - ord('a'))
# no difference
ans += prefix[mask]
for i in range(10):
# only differed by one digit
tmp = mask ^ (1 << i)
ans += prefix[tmp]
prefix[mask] += 1
return ans
|
number-of-wonderful-substrings
|
[Python 3] Prefix bit mask
|
chestnut890123
| 0
| 252
|
number of wonderful substrings
| 1,915
| 0.45
|
Medium
| 27,078
|
https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/discuss/1299545/Python3-post-order-dfs
|
class Solution:
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
tree = defaultdict(list)
for i, x in enumerate(prevRoom): tree[x].append(i)
def fn(n):
"""Return number of nodes and ways to build sub-tree."""
if not tree[n]: return 1, 1 # leaf
c, m = 0, 1
for nn in tree[n]:
cc, mm = fn(nn)
c += cc
m = (m * comb(c, cc) * mm) % 1_000_000_007
return c+1, m
return fn(0)[1]
|
count-ways-to-build-rooms-in-an-ant-colony
|
[Python3] post-order dfs
|
ye15
| 8
| 762
|
count ways to build rooms in an ant colony
| 1,916
| 0.493
|
Hard
| 27,079
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1314345/Python3-1-line
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))]
|
build-array-from-permutation
|
[Python3] 1-line
|
ye15
| 11
| 1,800
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,080
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1911063/python3orbrute-force-or-optimalorbrute-force
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
# time:O(N) space:O(N)
ans=[0]*len(nums)
for i in range(len(nums)):
ans[i] = nums[nums[i]]
return ans
|
build-array-from-permutation
|
python3|brute force | optimal|brute force
|
YaBhiThikHai
| 2
| 147
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,081
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1856306/Python-(Simple-Approach-and-Beginner-friendly)
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
arr = []
for i in range (0,len(nums)):
arr.append(nums[nums[i]])
return arr
|
build-array-from-permutation
|
Python (Simple Approach and Beginner-friendly)
|
vishvavariya
| 2
| 138
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,082
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1801351/Python-63.33
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
result = [0] * len(nums)
for n in nums:
result[n] = nums[nums[n]]
return result
|
build-array-from-permutation
|
Python -- 63.33%
|
jwhunt19
| 2
| 365
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,083
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1950411/One-line-Python-solution
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))]
|
build-array-from-permutation
|
One line Python solution
|
amannarayansingh10
| 1
| 116
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,084
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1875204/Python-dollarolution
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
v = []
for i in nums:
v.append(nums[i])
return v
|
build-array-from-permutation
|
Python $olution
|
AakRay
| 1
| 111
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,085
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1860733/Python-solution-memory-usage-lesser-than-93
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
res = []
for i in range(len(nums)):
res.append(nums[nums[i]])
return res
|
build-array-from-permutation
|
Python solution memory usage lesser than 93%
|
alishak1999
| 1
| 151
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,086
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1694342/**-Python-code%3A
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
ans=[0]*len(nums)
for i in range(0,len(nums)):
ans[i]= nums[nums[i]]
return ans
|
build-array-from-permutation
|
** Python code:
|
Anilchouhan181
| 1
| 198
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,087
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1540037/List-comprehension-93-speed
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))]
|
build-array-from-permutation
|
List comprehension, 93% speed
|
EvgenySH
| 1
| 158
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,088
|
https://leetcode.com/problems/build-array-from-permutation/discuss/1314390/Python3-Copy-and-paste-from-the-description
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
ans=[None for _ in range(len(nums))]
for i,e in enumerate(nums):
ans[i] = nums[nums[i]]
return ans
|
build-array-from-permutation
|
[Python3] Copy and paste from the description
|
mikeyliu
| 1
| 273
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,089
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2845384/1-line
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))]
|
build-array-from-permutation
|
1 line
|
Tushar_051
| 0
| 1
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,090
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2837023/Python-Fast-and-Simple-Solution
|
class Solution:
def buildArray(self, nums):
ans = []
length = len(nums)
for i in range(length):
ans.append(nums[nums[i]])
return ans
|
build-array-from-permutation
|
Python - Fast & Simple Solution
|
BladeStew
| 0
| 5
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,091
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2818702/simple-python-solution
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
d = []
for i in range(len(nums)):
d.append(nums[nums[i]])
return d
|
build-array-from-permutation
|
simple python solution
|
ft3793
| 0
| 3
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,092
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2815423/Fastest-and-Simplest-Solution-Python-(One-Liner-Code)
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(0, len(nums))]
|
build-array-from-permutation
|
Fastest and Simplest Solution - Python (One-Liner Code)
|
PranavBhatt
| 0
| 2
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,093
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2800819/PYTHON3-BEST
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))]
|
build-array-from-permutation
|
PYTHON3 BEST
|
Gurugubelli_Anil
| 0
| 2
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,094
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2785777/Solution
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return ([nums[i] for i in nums])
|
build-array-from-permutation
|
Solution
|
vovatoshev1986
| 0
| 2
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,095
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2776670/easy-python-solution
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
new_nums=[]
for i in nums:
new_nums.append(nums[i])
return new_nums
|
build-array-from-permutation
|
easy python solution
|
user7798V
| 0
| 4
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,096
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2744029/Python-1-line-code
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return[nums[n] for n in nums]
|
build-array-from-permutation
|
Python 1 line code
|
kumar_anand05
| 0
| 9
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,097
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2733852/Python-Soluation-For-Build-Array-from-Permutation
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[val] for val in nums]
|
build-array-from-permutation
|
Python Soluation For Build Array from Permutation
|
ankansmaiti
| 0
| 6
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,098
|
https://leetcode.com/problems/build-array-from-permutation/discuss/2719215/python-code
|
class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
r=[0]*len(nums)
for i in range(len(nums)):
r[i]=nums[nums[i]]
return r
|
build-array-from-permutation
|
python code
|
Vtu14918
| 0
| 5
|
build array from permutation
| 1,920
| 0.912
|
Easy
| 27,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.