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/sum-of-beauty-in-the-array/discuss/1471998/Python3-Beats-100-Solution
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
n = len(nums)
ans = 0
maxPre = nums[0]
minNums = nums[-1]
minPost = [0]*(n-1)
for i in range(n-2, 0, -1):
minPost[i] = minNums
if nums[i] < minNums:
minNums = nums[i]
for i in range(1, n-1):
if nums[i] > maxPre and nums[i] < minPost[i]:
ans += 2
elif nums[i] > nums[i-1] and nums[i] < nums[i+1]:
ans += 1
if nums[i] > maxPre:
maxPre = nums[i]
return ans
|
sum-of-beauty-in-the-array
|
[Python3] Beats 100% Solution
|
leefycode
| 0
| 55
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,100
|
https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1477019/Python3-bfs
|
class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
freq = [0] * 26
for ch in s: freq[ord(ch)-97] += 1
cand = [chr(i+97) for i, x in enumerate(freq) if x >= k] # valid candidates
def fn(ss):
"""Return True if ss is a k-repeated sub-sequence of s."""
i = cnt = 0
for ch in s:
if ss[i] == ch:
i += 1
if i == len(ss):
if (cnt := cnt + 1) == k: return True
i = 0
return False
ans = ""
queue = deque([""])
while queue:
x = queue.popleft()
for ch in cand:
xx = x + ch
if fn(xx):
ans = xx
queue.append(xx)
return ans
|
longest-subsequence-repeated-k-times
|
[Python3] bfs
|
ye15
| 9
| 409
|
longest subsequence repeated k times
| 2,014
| 0.556
|
Hard
| 28,101
|
https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1640640/python3%3A-2-solutions
|
class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
def helper(subString, string):
n, m = len(subString), len(string)
i, j = 0, 0
while i < n and j < m:
if subString[i] == string[j]:
i += 1
j += 1
return i == n
counter = defaultdict(lambda: 0)
for char in s:
counter[char] += 1
chars = [key for key in counter if counter[key] >= k]
chars.sort()
ans = ""
stack = [""]
while stack:
prefix = stack.pop(0)
for char in chars:
word = prefix + char
if helper(word*k, s):
stack.append(word)
ans = word
return ans
|
longest-subsequence-repeated-k-times
|
python3: 2 solutions
|
reynaldocv
| 0
| 130
|
longest subsequence repeated k times
| 2,014
| 0.556
|
Hard
| 28,102
|
https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1640640/python3%3A-2-solutions
|
class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
def helper(subString, string):
string = iter(string)
return all(c in string for c in subString)
counter = defaultdict(lambda: 0)
for char in s:
counter[char] += 1
chars = ""
for key in counter:
if counter[key]//k:
chars += key*(counter[key]//k)
for i in range(len(chars), 0, -1):
possibilities = set()
for comb in combinations(chars, i):
for perm in permutations(comb):
subString = "".join(perm)
possibilities.add(subString)
possibilities = sorted(possibilities, key = lambda item: (len(item), item), reverse = True)
for pos in possibilities:
if helper(pos*k, s):
return pos
return ""
|
longest-subsequence-repeated-k-times
|
python3: 2 solutions
|
reynaldocv
| 0
| 130
|
longest subsequence repeated k times
| 2,014
| 0.556
|
Hard
| 28,103
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1486318/Python3-prefix-min
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
ans = -1
prefix = inf
for i, x in enumerate(nums):
if i and x > prefix: ans = max(ans, x - prefix)
prefix = min(prefix, x)
return ans
|
maximum-difference-between-increasing-elements
|
[Python3] prefix min
|
ye15
| 6
| 557
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,104
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1698964/Python3-oror-easy-to-understand-oror-O(n)
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
mn,mx=float('inf'),-1
for i in range(len(nums)):
mn=min(mn,nums[i])
mx=max(mx,nums[i]-mn)
if mx==0: return -1
return mx
|
maximum-difference-between-increasing-elements
|
Python3 || easy to understand || O(n)
|
Anilchouhan181
| 3
| 237
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,105
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2070302/Python-easy-explained-with-comments-oror-O(n)-Time-O(1)-space-oror-Beats-91
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
curr_min = nums[0]
ans = 0
for i in nums:
if i < curr_min:
curr_min = i
ans = max(ans, i-curr_min)
return -1 if ans == 0 else ans
|
maximum-difference-between-increasing-elements
|
Python 🐍 easy, explained with comments || O(n) Time O(1) space || Beats 91%
|
dc_devesh7
| 2
| 173
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,106
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1492114/Python3-solution-or-O(n)-faster-than-99
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
my_max = -1
min_here = math.inf # the minimum element until i-th position
for i in range(len(nums)):
if min_here > nums[i]:
min_here = nums[i]
dif = nums[i] - min_here
if my_max < dif and dif != 0: # the difference mustn't be 0 because nums[i] < nums[j] so they can't be equals
my_max = dif
return my_max
|
maximum-difference-between-increasing-elements
|
Python3 solution | O(n) faster than 99%
|
FlorinnC1
| 2
| 382
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,107
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2501990/Python3-Straightforward-O(n)-no-extra-space-w-comments
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
output = -1
low = 10**9 # Set because of question constraints
for i in range(len(nums)):
# If we come across a new lowest number, keep track of it
low = min(low, nums[i])
# If the current number is greater than our lowest - and if their difference is greater than
# the largest distance seen yet, save this distance
if nums[i] > low: output = max(output, nums[i] - low)
return output
|
maximum-difference-between-increasing-elements
|
[Python3] Straightforward O(n) no extra space w comments
|
connorthecrowe
| 1
| 116
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,108
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1788479/Python3-O(n)-Time-and-O(1)-Space-Complexity-Simple-Solution.
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
greatest, curr_min = 0, nums[0]
for i in range(1, len(nums)):
# find the minimum of values such that their index <= i
curr_min = min(nums[i], curr_min)
# if a new minimum is found:
# nums[i] - curr_min = 0, i.e. nums[i] - nums[i] = 0
# else: (i < j is implied)
# we take the maximum of -- greatest and num[i] - curr_min
greatest = max(nums[i] - curr_min, greatest)
return greatest if greatest > 0 else -1
|
maximum-difference-between-increasing-elements
|
[Python3] O(n) Time and O(1) Space Complexity Simple Solution.
|
RamziA961
| 1
| 115
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,109
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1633053/ShortFast-and-Easy-Python.
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
minNum = nums[0]
res = -1
for num in nums:
if num > minNum:
res = max(res,num - minNum)
minNum = min(minNum,num)
return res
|
maximum-difference-between-increasing-elements
|
Short,Fast, and Easy Python.
|
manassehkola
| 1
| 205
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,110
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1553677/Python3-time-O(n)-%2B-space-O(1)
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
prefix_min: int = nums[0]
max_difference: int = -1
for i in range(1, len(nums)):
if prefix_min < nums[i]:
max_difference = max(max_difference, nums[i] - prefix_min)
else:
prefix_min = nums[i]
return max_difference
|
maximum-difference-between-increasing-elements
|
Python3, time O(n) + space O(1)
|
sirenescx
| 1
| 158
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,111
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1486433/Python-or-O(N)-Time-or-O(1)-Space
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
smallest, largest_distance = nums[0] + 1, -1
for num in nums:
if num > smallest:
largest_distance = max(largest_distance, num - smallest)
smallest = min(smallest, num)
return largest_distance
|
maximum-difference-between-increasing-elements
|
Python | O(N) Time | O(1) Space
|
leeteatsleep
| 1
| 155
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,112
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2849983/Python-dp-solution
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
dp1 = [0]*len(nums)
dp2 = [0]*len(nums)
#min
dp1[0] = nums[0]
for i in range(1, len(nums)):
dp1[i] = min(dp1[i-1], nums[i])
#max
dp2[len(nums)-1] = nums[-1]
for i in range(len(nums)-2, -1, -1):
dp2[i] = max(dp2[i+1], nums[i])
res = -1
for i in range(len(nums)):
temp = dp2[i]-dp1[i]
if temp > 0:
res = max(res, temp)
return res
|
maximum-difference-between-increasing-elements
|
Python dp solution
|
ankurkumarpankaj
| 0
| 1
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,113
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2815380/Easiest-solution
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
if nums==sorted(nums)[::-1]:
return -1
list=[]
n=len(nums)
for i in range (n):
for j in range (n):
if j>i and nums[j]>nums[i]:
k=(nums[j]-nums[i])
list.append(k)
return max(list)
|
maximum-difference-between-increasing-elements
|
Easiest solution
|
nishithakonuganti
| 0
| 4
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,114
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2804779/Python-Brute-Force-Solution-O(n2)
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
if nums == sorted(nums)[::-1]:
return -1
res = []
for i in range(len(nums)):
for j in range(len(nums)):
if i < j and nums[i] < nums[j]:
res.append(nums[j]- nums[i])
return max(res)
|
maximum-difference-between-increasing-elements
|
Python Brute Force Solution O(n^2)
|
Jashan6
| 0
| 6
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,115
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2638473/Python-Solution-or-Brute-Force
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
ans=-1
n=len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[j]>nums[i]:
ans=max(ans, nums[j]-nums[i])
return ans
|
maximum-difference-between-increasing-elements
|
Python Solution | Brute Force
|
Siddharth_singh
| 0
| 6
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,116
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2461466/Python-O(n)-Null-Coalescing-Operator-and-Sliding-Window
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
left: int = 0
max_difference: int = 0
for right, r_num in enumerate(nums):
if nums[left] > r_num:
left = right
elif r_num - nums[left] > max_difference:
max_difference = r_num - nums[left]
return max_difference or -1
|
maximum-difference-between-increasing-elements
|
Python O(n) Null Coalescing Operator and Sliding Window
|
WrenPriest
| 0
| 54
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,117
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2380110/EASY-PYTHON-CODE-oror-7-LINER
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
d=-1
for i in range(0,len(nums)-1):
for j in range(i+1,len(nums)):
if nums[j]>nums[i]:
d=max(d,nums[j] - nums[i])
return d
|
maximum-difference-between-increasing-elements
|
EASY PYTHON CODE || 7 LINER
|
keertika27
| 0
| 64
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,118
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/2114286/Python-simple-solution
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
ans = []
for i in range(len(nums)):
for j in range(i, len(nums)):
if i == j: continue
if nums[i] < nums[j]:
ans.append(nums[j]-nums[i])
return max(ans) if ans else -1
|
maximum-difference-between-increasing-elements
|
Python simple solution
|
StikS32
| 0
| 56
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,119
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1952735/Easy-to-understand-Python-O(N)-time-oror-O(1)-space-solution.
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
max_diff, j = 0, 0
i = float("inf")
for n in nums:
i = min(i, n)
j = max(i, n)
max_diff = max(max_diff, j - i)
return -1 if not max_diff else max_diff
|
maximum-difference-between-increasing-elements
|
Easy to understand Python O(N) time || O(1) space solution.
|
mofatah
| 0
| 123
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,120
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1881430/Python-dollarolution-(Mem-use-less-than-99.9)
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
m = -1
for i in range(len(nums)-1):
x = max(nums[i+1:])
if x > nums[i]:
if m < (x -nums[i]):
m = x - nums[i]
return m
|
maximum-difference-between-increasing-elements
|
Python $olution (Mem use less than 99.9%)
|
AakRay
| 0
| 101
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,121
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1787779/Python3-accepted-solution
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
ans = []
for i in range(len(nums)-1):
if(max(nums[i+1:])>nums[i]):
ans.append(max(nums[i+1:]) - nums[i])
if(len(ans)==0):return -1
return max(ans)
|
maximum-difference-between-increasing-elements
|
Python3 accepted solution
|
sreeleetcode19
| 0
| 58
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,122
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1782118/Best-time-to-buy-and-sell-stock-or-Python
|
class Solution:
def maximumDifference(self, prices: List[int]) -> int:
sell, profit = prices[0], 0
for i in range(1, len(prices)):
if prices[i] < sell:
sell = prices[i]
profit = max(profit, prices[i]-sell)
return -1 if profit == 0 else profit
|
maximum-difference-between-increasing-elements
|
Best time to buy and sell stock | Python
|
sanial2001
| 0
| 73
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,123
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1674485/Python3-Memory-Less-Than-96.45
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
mn, diff = nums[0], -1
for i in range(1, len(nums)):
if nums[i] <= mn:
mn = nums[i]
else:
diff = max(diff, nums[i] - mn)
return diff
|
maximum-difference-between-increasing-elements
|
Python3, Memory Less Than 96.45%
|
Hejita
| 0
| 105
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,124
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1674085/WEEB-EXPLAINS-PYTHON-SOLUTION
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
curMin, curMinIdx = float("inf"), 0
curMax, curMaxIdx = -float("inf"), 0
result = -1
for i in range(len(nums)):
if nums[i] < curMin:
curMin = nums[i]
curMinIdx = i
curMax = -float("inf") # reset the max value since we found new min value
elif nums[i] > curMax:
curMax = nums[i]#no need to reset the min value since maxIdx>minIdx for all i in nums
curMaxIdx = i # this is because we traverse nums from left to right
if curMaxIdx > curMinIdx and curMin < curMax: # as stated in the question
maxDiff = curMax - curMin
if maxDiff > result:
result = maxDiff
return result
|
maximum-difference-between-increasing-elements
|
WEEB EXPLAINS PYTHON SOLUTION
|
Skywalker5423
| 0
| 61
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,125
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1584053/Python-3-O(n)-easy-to-understand
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
res = -1
curMin = math.inf
for num in nums:
if num > curMin:
res = max(res, num - curMin)
else:
curMin = num
return res
|
maximum-difference-between-increasing-elements
|
Python 3 O(n) easy to understand
|
dereky4
| 0
| 177
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,126
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1487274/Python-one-pass-O(N)
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
max_diff = 0
min_ = nums[0]
for i in range(1, len(nums)):
min_ = min(min_, nums[i])
max_diff = max(nums[i] - min_, max_diff)
return max_diff if max_diff else -1
|
maximum-difference-between-increasing-elements
|
Python, one pass O(N)
|
blue_sky5
| 0
| 54
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,127
|
https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1486838/Python3-or-Line-solution-O(n)
|
class Solution:
def maximumDifference(self, nums: List[int]) -> int:
# <2 elements in nums seq
if not nums or len(nums) <= 1:
return -1
# initialize current min el (val, index) and max diff
current_min = (float('inf'), -1)
current_diff = nums[1]-nums[0] # min 2 el's in sequence
# O(n) iterations
for i in range(0, len(nums)):
if nums[i] < current_min[0]:
current_min = (min(nums[i], current_min[0]), i) # update min elem
current_diff = max(current_diff, nums[i] - nums[current_min[1]]) # update max diff
return current_diff if current_diff else -1
|
maximum-difference-between-increasing-elements
|
[Python3] | Line solution O(n)
|
patefon
| 0
| 40
|
maximum difference between increasing elements
| 2,016
| 0.535
|
Easy
| 28,128
|
https://leetcode.com/problems/grid-game/discuss/1486349/Python-Easy
|
class Solution(object):
def gridGame(self, grid):
top, bottom = grid
top_sum = sum(top)
bottom_sum = 0
res = float('inf')
for i in range(len(top)):
top_sum -= top[i]
res = min(res, max(top_sum, bottom_sum))
bottom_sum += bottom[i]
return res
|
grid-game
|
Python - Easy
|
lokeshsenthilkumar
| 3
| 181
|
grid game
| 2,017
| 0.43
|
Medium
| 28,129
|
https://leetcode.com/problems/grid-game/discuss/1486321/Python3-greedy
|
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
ans = inf
prefix = 0
suffix = sum(grid[0])
for i in range(len(grid[0])):
suffix -= grid[0][i]
ans = min(ans, max(prefix, suffix))
prefix += grid[1][i]
return ans
|
grid-game
|
[Python3] greedy
|
ye15
| 1
| 111
|
grid game
| 2,017
| 0.43
|
Medium
| 28,130
|
https://leetcode.com/problems/grid-game/discuss/2840437/Python-or-IntuitionPrefix-Sum-or-Diagrams-Pictures-Comments-and-Explanation
|
class Solution:
# optimized prefix sum
def gridGame(self, grid: List[List[int]]) -> int:
n = len(grid[0])
ans = math.inf
topSum = sum(grid[0])
bottomSum = 0
for i in range(n):
topSum -= grid[0][i]
ans = min(ans, max(topSum, bottomSum))
bottomSum += grid[1][i]
return ans
# neetcode's prefix sum method
def gridGame(self, grid: List[List[int]]) -> int:
res = float('inf') # max value
prefixSum1 = [grid[0][0]]
prefixSum2 = [grid[1][0]] # has the first value done so that we can iterate more smoothly
length = len(grid[0])
for i in range(1, length): # from 1 to end because we don't want to deal with an out of bounds error
prefixSum1.append(grid[0][i] + prefixSum1[i-1]) # doing it this way bc it seems faster but you really just want to calculate the prefix sums of each row and save it to the index
prefixSum2.append(grid[1][i] + prefixSum2[i-1])
for i in range(length): # so here we want to calculate the turning point of the first robot
# calculate the values excluding the current index
top_row = prefixSum1[-1] - prefixSum1[i] # so total - the current index (which is the accumulated value of the left side, index inclusive)
bottom_row = prefixSum2[i-1] if i > 0 else 0 # bounds checking here bc 0-1 is -1 and that is not the right place to be.
current = max(top_row, bottom_row) # take the max values of this index that the second robot can grab
res = min(res, current) # the first robot is a bad robot so we want to take the minimum values of all the maxes that we calculate and this here is O(1) space complexity instead of saving it all to an array. In taking the minimum, we take thus maximize robot 1's take and robot 2's take per the properties.
return res
# simple solution (runs out of time due to not storing the calculations)
def gridGame(self, grid: List[List[int]]) -> int:
# this is the simpler code but it doesn't work because of a time limit problem. simply having the prefix sum's already calculated makes this problem ultra efficient
res = float('inf') # max
length = len(grid[0])
for i in range(length): # check each index of the array
# take the sum of everything after the index on the top row and before the index on the bottom row
top = sum(grid[0][i+1:])
bot = sum(grid[1][:i])
current = max(top, bot) # max of robot 2's take if robot 1 were to turn at this specific index
res = min(res, current) # determines robot 2's real take that would maximize robot 1's take
return res
|
grid-game
|
🎉Python | Intuition/Prefix Sum | Diagrams, Pictures, Comments and Explanation
|
Arellano-Jann
| 0
| 1
|
grid game
| 2,017
| 0.43
|
Medium
| 28,131
|
https://leetcode.com/problems/grid-game/discuss/2733267/Python-code-with-easy-approach-and-explanation-o(n)
|
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
#Time: O(n)
#Space: O(n)
#Prefix sum to top line and postfix for bottom grid
#we are taking the max of top or bottom and then do take minimum of it\
#reason being the first robot left us with minimum points only and thats how the solution will be optimized
top,bottom,res= sum(grid[0]),0,float('inf')
for t,b in zip(grid[0],grid[1]):
top=top-t
res=min(res,max(top,bottom))
bottom=bottom+b
return res
|
grid-game
|
Python code with easy approach and explanation o(n)
|
kartikchoudhary96
| 0
| 11
|
grid game
| 2,017
| 0.43
|
Medium
| 28,132
|
https://leetcode.com/problems/grid-game/discuss/1849281/Python-easy-to-read-and-understand-or-prefix-sum
|
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
n = len(grid[0])
top, bottom = sum(grid[0]), 0
ans = float("inf")
for i in range(n):
top -= grid[0][i]
ans = min(ans, max(top, bottom))
bottom += grid[1][i]
return ans
|
grid-game
|
Python easy to read and understand | prefix-sum
|
sanial2001
| 0
| 113
|
grid game
| 2,017
| 0.43
|
Medium
| 28,133
|
https://leetcode.com/problems/grid-game/discuss/1508504/Accumulate-sums
|
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
cols = len(grid[0])
if cols == 1:
return 0
cols1 = cols - 1
for c in range(1, cols):
grid[0][cols1 - c] += grid[0][cols - c]
grid[1][c] += grid[1][c - 1]
return min(max(grid[0][i + 1] if i < cols1 else 0,
grid[1][i - 1] if i > 0 else 0)
for i in range(cols))
|
grid-game
|
Accumulate sums
|
EvgenySH
| 0
| 76
|
grid game
| 2,017
| 0.43
|
Medium
| 28,134
|
https://leetcode.com/problems/grid-game/discuss/1487980/simple-calc-given-the-index-robo-1-shift-down-and-iterate-over-this-index-to-find-answer
|
class Solution:
def gridGame(self, G: List[List[int]]) -> int:
n = len(G[0])
cummG = [0]*(n+1)
for i in range(n-1,-1,-1):
cummG[i] = cummG[i+1] + G[0][i]
lsum = 0
ans = math.inf
for i in range(n):
ans = min(ans,max(cummG[i+1],lsum))
lsum+=G[1][i]
return ans
|
grid-game
|
simple calc given the index robo 1 shift down & iterate over this index to find answer
|
akbc
| 0
| 32
|
grid game
| 2,017
| 0.43
|
Medium
| 28,135
|
https://leetcode.com/problems/grid-game/discuss/1486506/Easy-and-Greedy-oror-98-faster-oror
|
class Solution:
def gridGame(self, grid: List[List[int]]) -> int:
res = float('inf')
top_right_sum = sum(grid[0][1:])
bottom_left_sum = 0
n = len(grid[0])
for i in range(n):
res = min(res,max(top_right_sum,bottom_left_sum))
if i+1<n:
top_right_sum -= grid[0][i+1]
bottom_left_sum += grid[1][i]
return res
|
grid-game
|
📌📌 Easy & Greedy || 98% faster || 🐍
|
abhi9Rai
| 0
| 67
|
grid game
| 2,017
| 0.43
|
Medium
| 28,136
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486326/Python3-row-by-row-and-col-by-col
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
for x in board, zip(*board):
for row in x:
for s in "".join(row).split("#"):
for w in word, word[::-1]:
if len(s) == len(w) and all(ss in (" ", ww) for ss, ww in zip(s, w)): return True
return False
|
check-if-word-can-be-placed-in-crossword
|
[Python3] row-by-row & col-by-col
|
ye15
| 10
| 1,300
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,137
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486326/Python3-row-by-row-and-col-by-col
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
for x in board, zip(*board):
for row in x:
for k, grp in groupby(row, key=lambda x: x != "#"):
grp = list(grp)
if k and len(grp) == len(word):
for w in word, word[::-1]:
if all(gg in (" ", ww) for gg, ww in zip(grp, w)): return True
return False
|
check-if-word-can-be-placed-in-crossword
|
[Python3] row-by-row & col-by-col
|
ye15
| 10
| 1,300
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,138
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486589/Easy-Approach-oror-Just-Think-and-Do-oror-No-Trick
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
words = [word,word[::-1]]
n = len(word)
for B in board,zip(*board):
for row in B:
q = ''.join(row).split("#")
for w in words:
for s in q:
if len(s)==n:
for i in range(n):
if all(s[i]==" " or s[i]==w[i] for i in range(n)): # If you didn't get here then go beloe for detailed one.
return True
return False
|
check-if-word-can-be-placed-in-crossword
|
📌📌 Easy-Approach || Just Think and Do || No Trick 🐍
|
abhi9Rai
| 1
| 167
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,139
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/2245368/Python-Solution-TC%3A-O(MN)-SC%3A-O(MN)
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
def matched(seq, word):
if len(seq) != len(word):
return False
forward, reverse = True, True
for i in range(len(seq)):
if seq[i] != ' ' and seq[i] != word[i]:
forward = False
if seq[-1-i] != ' ' and seq[-1-i] != word[i]:
reverse = False
return forward or reverse
vertical = set()
horizontal = set()
for r in range(m):
for c in range(n):
if board[r][c] == '#':
continue
if (r, c) not in vertical:
seq, i = '', 0
while r + i < m and board[r+i][c] != '#':
vertical.add((r+i, c))
seq += board[r+i][c]
i += 1
if matched(seq, word):
return True
if (r, c) not in horizontal:
seq, i = '', 0
while c + i < n and board[r][c+i] != '#':
horizontal.add((r, c+i))
seq += board[r][c+i]
i += 1
if matched(seq, word):
return True
return False
|
check-if-word-can-be-placed-in-crossword
|
Python Solution / TC: O(MN) / SC: O(MN)
|
LoadIdentity
| 0
| 123
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,140
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/2087228/Intuitive-Python-O(M*N)-run-time
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
nrows = len(board)
ncols = len(board[0])
wlen = len(word)
blocks = []
# extract horizontal blocks of matching length
for row in range(nrows):
count = 0
start = 0
for col in range(ncols + 1):
if col < ncols and board[row][col] != '#':
count += 1
else:
if count == wlen:
blocks.append(board[row][start:col])
count = 0
start = col + 1
# extract vertical blocks of matching length
for col in range(ncols):
count = 0
start = 0
for row in range(nrows + 1):
if row < nrows and board[row][col] != '#':
count += 1
else:
if count == wlen:
blocks.append([board[i][col] for i in range(start, row)])
count = 0
start = row + 1
def checkBlocks(blocks, word):
candidates = blocks
for i, c in enumerate(word):
new_candidates = []
for b in candidates:
if b[i] == c or b[i] == ' ':
new_candidates.append(b)
candidates = new_candidates
return len(candidates) > 0
return checkBlocks(blocks, word) or checkBlocks(blocks, word[::-1])
|
check-if-word-can-be-placed-in-crossword
|
Intuitive Python, O(M*N) run-time
|
boris17
| 0
| 102
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,141
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1918582/Gather-patterns-first-and-match-string-to-all-patterns
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
m, n = len(board), len(board[0])
patterns = []
for row in board:
row = ''.join(row)
patterns.extend([x for x in row.split('#') if x])
patterns.extend([x[::-1] for x in row.split('#') if x])
for col in zip(*board):
col = ''.join(col)
patterns.extend([x for x in col.split('#') if x])
patterns.extend([x[::-1] for x in col.split('#') if x])
patterns = set([x for x in patterns if len(x) == len(word)])
flags = [True] * len(patterns)
for i, c in enumerate(word):
for j, pattern in enumerate(patterns):
if pattern[i] != ' ' and pattern[i] != c:
flags[j] = False
return any(flags)
|
check-if-word-can-be-placed-in-crossword
|
Gather patterns first, and match string to all patterns
|
keren3
| 0
| 58
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,142
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1493656/Python-fast(91)
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
# function for comparing candidate with word in both direction
def _helper(tmp):
for t, w in zip(tmp, word):
if t != " " and t != w:
break
else:
return True
for t, w in zip(tmp[::-1], word):
if t != " " and t != w:
return False
return True
# function for collecting horizontal and vertical candidates
def _check_direction(x, y, is_horizontal=True):
for i in range(x):
tmp = []
for j in range(y):
value = board[i][j] if is_horizontal else board[j][i]
if value != "#":
tmp.append(value)
elif tmp:
if len(tmp) == len(word) and _helper(tmp):
return True
tmp = []
else:
if len(tmp) == len(word) and _helper(tmp):
return True
return False
return _check_direction(len(board), len(board[0])) or \
_check_direction(len(board[0]), len(board), is_horizontal=False)
|
check-if-word-can-be-placed-in-crossword
|
[Python] fast(91%)
|
cruim
| 0
| 245
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,143
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1487973/elementary-but-fast
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
def check(R,i,j):
if i==len(R):
if j==len(word):
return True
else:
return False
if j==len(word):
if R[i]!='#':
return False
else:
return True
if R[i]=='#' or (R[i] !=' ' and R[i]!=word[j]):
return False
if i>0 and j==0 and R[i-1]!='#':
return False
curr = R[i]
R[i] = word[j]
ans = check(R,i+1,j+1)
R[i] = curr
return ans
def help(row):
return any(check(row,i,0) for i in range(len(row)))
for r in board:
if help(r) or help(r[::-1]):
return True
for j in range(len(board[0])):
if help([board[i][j] for i in range(len(board))]):
return True
if help([board[i][j] for i in range(len(board)-1,-1,-1)]):
return True
return False
|
check-if-word-can-be-placed-in-crossword
|
elementary but fast
|
akbc
| 0
| 53
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,144
|
https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486576/Python-Simple-Solution
|
class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
abc='abcdefghijklmnopqrstuvwxyz'
n=len(board)
m=len(board[0])
def check(a,b):
la=len(a)
lb=len(b)
b_=b[::-1]
start=[]
n=0
for i in range(la):
if i==0 and (a[i]==" " or a[i] in abc):
start.append(i)
n+=1
elif i>0 and (a[i]==" " or a[i] in abc) and a[i-1]=="#":
start.append(i)
n+=1
elif i>0 and a[i]=='#' and (a[i-1]==' ' or a[i-1] in abc):
start.append(i)
if i==la-1 and (a[i]==' ' or a[i] in abc):
start.append(i+1)
for i in range(n):
flag=0
flag1=0
if start[2*i+1]-start[2*i] == lb:
for j in range(start[2*i],start[2*i+1]):
k=j-start[2*i]
if not (a[j]==' ' or a[j]==b[k]):
# print(a[j],b[k])
flag=1
break
for j in range(start[2*i],start[2*i+1]):
k=j-start[2*i]
if not (a[j]==' ' or a[j]==b_[k]):
# print(a[j],b[k])
flag1=1
break
if flag==0 or flag1==0:
return True
return False
new=[["" for _ in range(n)] for _ in range(m)]
for i in range(n):
for j in range(m):
new[j][i]=board[i][j]
s=set()
for i in range(n):
s.add("".join(board[i]))
for i in range(m):
s.add("".join(new[i]))
for i in s:
if check(i,word):
return True
return False
|
check-if-word-can-be-placed-in-crossword
|
Python Simple Solution
|
jerinjoseantony
| 0
| 116
|
check if word can be placed in crossword
| 2,018
| 0.494
|
Medium
| 28,145
|
https://leetcode.com/problems/the-score-of-students-solving-math-expression/discuss/1487285/Python3-somewhat-dp
|
class Solution:
def scoreOfStudents(self, s: str, answers: List[int]) -> int:
@cache
def fn(lo, hi):
"""Return possible answers of s[lo:hi]."""
if lo+1 == hi: return {int(s[lo])}
ans = set()
for mid in range(lo+1, hi, 2):
for x in fn(lo, mid):
for y in fn(mid+1, hi):
if s[mid] == "+" and x + y <= 1000: ans.add(x + y)
elif s[mid] == "*" and x * y <= 1000: ans.add(x * y)
return ans
target = eval(s)
cand = fn(0, len(s))
ans = 0
for x in answers:
if x == target: ans += 5
elif x in cand: ans += 2
return ans
|
the-score-of-students-solving-math-expression
|
[Python3] somewhat dp
|
ye15
| 6
| 267
|
the score of students solving math expression
| 2,019
| 0.338
|
Hard
| 28,146
|
https://leetcode.com/problems/the-score-of-students-solving-math-expression/discuss/1487968/all-possible-less1000
|
class Solution:
def scoreOfStudents(self, s: str, answers: List[int]) -> int:
@lru_cache(None)
def allEval(x):
lo = eval(x)
if lo > 1000:
return set()
ans = set([lo])
if '*' not in x or '+' not in x or lo==1000:
return ans
for pos, char in enumerate(x):
if char not in ['+', '*']:
continue
left, right = allEval(x[:pos]), allEval(x[pos+1:])
if char == '+':
ans |= {a + b for a in left for b in right if a+b<=1000}
if char == '*':
ans |= {a * b for a in left for b in right if a*b<=1000}
return ans
S = allEval(s)
correct = eval(s)
return sum(5 if x==correct else (2 if x in S else 0) for x in answers)
|
the-score-of-students-solving-math-expression
|
all possible <=1000
|
akbc
| 0
| 71
|
the score of students solving math expression
| 2,019
| 0.338
|
Hard
| 28,147
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1499000/Python3-simulation
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
ans = []
if len(original) == m*n:
for i in range(0, len(original), n):
ans.append(original[i:i+n])
return ans
|
convert-1d-array-into-2d-array
|
[Python3] simulation
|
ye15
| 36
| 2,800
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,148
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1535074/Python-one-line
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []
|
convert-1d-array-into-2d-array
|
Python one line
|
mqueue
| 11
| 1,100
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,149
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1535074/Python-one-line
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
q = []
for i in range(0, len(original), n):
q.append(original[i:i+n])
return q
|
convert-1d-array-into-2d-array
|
Python one line
|
mqueue
| 11
| 1,100
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,150
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1772903/Easy-Python-Solution
|
class Solution(object):
def construct2DArray(self,original, m, n):
result = []
if len(original)==m*n:
for row in range(m):
result.append(original[n*row:n*row+n])
return result
|
convert-1d-array-into-2d-array
|
Easy Python Solution
|
user4578H
| 3
| 234
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,151
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2768428/Python-oror-Silly-Solution
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if(len(original)!= (m*n)):
return []
matrix = [[0]*n for i in range(m)]
index=0
for rows in range(m):
for cols in range(n):
matrix[rows][cols]= original[index]
index+=1
return matrix
|
convert-1d-array-into-2d-array
|
Python || Silly Solution
|
hasan2599
| 1
| 42
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,152
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2497082/straight-forward-python-code
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
ret = []
for i in range(m):
curr = []
for j in range(n):
curr.append(original[i*n+j])
ret.append(curr)
return ret
|
convert-1d-array-into-2d-array
|
straight forward python code
|
gasohel336
| 1
| 57
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,153
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2407569/Python-O(n2)-Solution-Easy-for-looping
|
class Solution:
def construct2DArray(self, original: List[int], r: int, c: int) -> List[List[int]]:
if len(original) == r*c:
res = [[0 for c in range(c)] for r in range(r)]
idx = 0
for i in range(r):
for j in range(c):
res[i][j] = original[idx]
idx +=1
return res
return None
|
convert-1d-array-into-2d-array
|
Python O(n2) Solution Easy for looping
|
realgautamjakhar
| 1
| 30
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,154
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2156541/Time%3A-O(N-%2B-M)-Space%3A-O(N)
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
# make sure we can create the matrix first (m * n == len(array))
# iterate through m first creatig a new list to append to matrix
# add the elments to the row (new list) by adding the current element in original
# after iteration, return the matrix array
# Time: O(M + N) Space: O(N)
if m * n != len(original):
return []
matrix = [[] for i in range(m)]
curr = 0
for i in range(m):
for j in range(n):
matrix[i].append(original[curr])
curr += 1
return matrix
|
convert-1d-array-into-2d-array
|
Time: O(N + M) Space: O(N)
|
andrewnerdimo
| 1
| 61
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,155
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2093877/Python-simple-solution
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original): return []
ans = []
for i in range(m):
ans.append([])
for j in range(n):
ans[i].append(original.pop(0))
return ans
|
convert-1d-array-into-2d-array
|
Python simple solution
|
StikS32
| 1
| 70
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,156
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1861769/Explicit-Easy-to-Follow-Solution
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if len(original) != m * n:
return []
result = []
i = 0
for _ in range(m):
row = []
for _ in range(n):
row.append(original[i])
i += 1
result.append(row)
return result
|
convert-1d-array-into-2d-array
|
Explicit, Easy to Follow Solution
|
EdwinJagger
| 1
| 70
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,157
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1819304/Python-2-solutions.-Second-one-(97.15-faster)-is-optimized-(time%3AO(n)-space%3AO(n))
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
length = len(original)
arr = []
a = 0
if length != m*n:
return arr
for i in range(m):
col = []
for j in range(n):
col.append(original[a])
a += 1
arr.append(col)
return arr
|
convert-1d-array-into-2d-array
|
[Python] 2 solutions. Second one (97.15% faster) is optimized (time:O(n), space:O(n))
|
jamil117
| 1
| 132
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,158
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1819304/Python-2-solutions.-Second-one-(97.15-faster)-is-optimized-(time%3AO(n)-space%3AO(n))
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
length = len(original)
arr = []
if length != m*n:
return arr
for i in range(0, length, n):
arr.append(original[i:i+n])
return arr
|
convert-1d-array-into-2d-array
|
[Python] 2 solutions. Second one (97.15% faster) is optimized (time:O(n), space:O(n))
|
jamil117
| 1
| 132
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,159
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1678892/Python-or-Index-Conversion
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
a = len(original)
if m * n != a:
return []
res = [[0] * n for _ in range(m)]
for i, val in enumerate(original):
res[i // n][i % n] = val
return res
|
convert-1d-array-into-2d-array
|
Python | Index Conversion
|
jgroszew
| 1
| 137
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,160
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2812022/Easy-numpy-solution-4-lines
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
import numpy as np
if m*n != len(original):
return []
return np.reshape(original,(m,n))
|
convert-1d-array-into-2d-array
|
Easy numpy solution - 4 lines
|
spraj_123
| 0
| 1
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,161
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2724894/Concise-Python-And-Golang-Solution
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
len_original = len(original)
row = n # 横
column = m # 縦
matrix = []
if len_original != (row * column):
return matrix
i = 0
for j in range(row, len_original + 1, row):
line = original[i: j]
matrix.append(line)
i = j
return matrix
|
convert-1d-array-into-2d-array
|
Concise Python And Golang Solution
|
namashin
| 0
| 2
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,162
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2680059/python-oneline
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return ([original[n*i : n*(i+1)] for i in range(m)]) if n*m == len(original) else []
|
convert-1d-array-into-2d-array
|
python oneline
|
kanpassa
| 0
| 7
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,163
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2670551/Python-One-liner-Solution-With-List-Comprehension
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return [original[i:i+n] for i in range(0, m*n, n)] if m*n == len(original) else []
|
convert-1d-array-into-2d-array
|
Python One-liner Solution With List Comprehension
|
kcstar
| 0
| 6
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,164
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2552807/Python-solution
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original): return []
res = []
row = 0
for col in range(m):
res.append(original[row:row+n])
row +=n
return res
|
convert-1d-array-into-2d-array
|
Python solution
|
jnjoroge13
| 0
| 23
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,165
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2398169/Python-Solution-or-Simple-and-Straightforward-Logic-or-Simulated-Skip-Based
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if not (m*n == len(original)):
return []
s = []
for i in range(0,len(original),n):
if original[i:i+n] != []:
s.append(original[i:i+n])
return s
|
convert-1d-array-into-2d-array
|
Python Solution | Simple and Straightforward Logic | Simulated Skip Based
|
Gautam_ProMax
| 0
| 36
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,166
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2339983/Python-or-Slices
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
return [original[row*n: (row+1)*n] for row in range(m)]
|
convert-1d-array-into-2d-array
|
Python | Slices
|
Sonic0588
| 0
| 31
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,167
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/2217974/Python-simple-solution-or-Beats-speed-99
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
l = len(original)
if l != m * n:
return []
ans = []
for i in range(0, l, n):
ans.append(tuple(original[i:i+n]))
return ans
|
convert-1d-array-into-2d-array
|
Python simple solution | Beats speed 99%
|
Bec1l
| 0
| 82
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,168
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1988143/Python-easy-solution-for-beginners
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
res = []
for i in range(0, len(original), n):
row = original[i:i+n]
res.append(row)
if len(res) == m and len(res[0]) == n:
return res
return []
|
convert-1d-array-into-2d-array
|
Python easy solution for beginners
|
alishak1999
| 0
| 94
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,169
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1981330/Python3-Beginner-Friendly-Simplest-Approach
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
else:
ans = [] ; point = 0
for i in range(m):
row = []
for j in range(n):
row.append(original[point])
point += 1
ans.append(row)
return ans
|
convert-1d-array-into-2d-array
|
Python3 Beginner Friendly Simplest Approach
|
alreadyselfish
| 0
| 71
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,170
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1904570/Python-one-line-solution-O(n*m)
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return [original[i: i+n] for i in range(0, len(original), n)] if m * n == len(original) else []
|
convert-1d-array-into-2d-array
|
Python one line solution, O(n*m)
|
sEzio
| 0
| 58
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,171
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1881557/Python-dollarolution-(97-faster-and-81-less-mem)
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
v = []
for i in range(0,m*n,n):
v.append(original[i:i+n])
return v
|
convert-1d-array-into-2d-array
|
Python $olution (97% faster & 81% less mem)
|
AakRay
| 0
| 128
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,172
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1844838/Python-One-Liner-oror-Faster-Than-92-oror-Less-Memory-Than-84
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return [original[i * n:(i + 1) * n] for i in range(m)] if m * n == len(original) else []
|
convert-1d-array-into-2d-array
|
Python One-Liner || Faster Than 92% || Less Memory Than 84%
|
cfandrews
| 0
| 93
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,173
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1836565/4-Lines-Python-Solution-oror-90-Faster-oror-Memory-less-than-85
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if len(original)!=n*m: return []
ans=[]
for i in range(0,len(original),n): ans.append(original[i:i+n])
return ans
|
convert-1d-array-into-2d-array
|
4-Lines Python Solution || 90% Faster || Memory less than 85%
|
Taha-C
| 0
| 80
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,174
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1787781/Python3-accepted-solution
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if(m*n != len(original)): return []
ans = []
for i in range(m):
ans.append(original[i*n:(i*n)+n])
return (ans)
|
convert-1d-array-into-2d-array
|
Python3 accepted solution
|
sreeleetcode19
| 0
| 103
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,175
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1786821/python-3-or-Simple-python-solution-or-O(n)
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
lst = []
for i in range(0,len(original),n):
lst.append(original[i:i+n])
return lst
|
convert-1d-array-into-2d-array
|
python 3 | Simple python solution | O(n)
|
Coding_Tan3
| 0
| 89
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,176
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1633013/Fastclean-and-easy-Python.-3-lines.
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
return [original[i*n:i*n+n] for i in range(m)]
|
convert-1d-array-into-2d-array
|
Fast,clean, and easy Python. 3 lines.
|
manassehkola
| 0
| 177
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,177
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1580763/List-slicing-97-speed
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
return ([original[r * n: (r + 1) * n] for r in range(m)]
if m * n == len(original) else [])
|
convert-1d-array-into-2d-array
|
List slicing, 97% speed
|
EvgenySH
| 0
| 82
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,178
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1500261/Python
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
N = len(original)
if m * n != N:
return []
arr = [[0 for i in range(n)] for j in range(m)]
x, y, idx = 0, 0, 0
while idx < N:
while y < n:
arr[x][y] = original[idx]
idx += 1
y += 1
x+= 1
y = 0
return arr
|
convert-1d-array-into-2d-array
|
Python
|
jlee9077
| 0
| 75
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,179
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1499283/Python-straightforward
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if len(original) != m*n:
return []
result = []
for r in range(m):
result.append([original[r*n + c] for c in range(n)])
return result
|
convert-1d-array-into-2d-array
|
Python, straightforward
|
blue_sky5
| 0
| 121
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,180
|
https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1679412/Easy-python
|
class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
if m*n != len(original):
return []
a1 = []
for i in range(0, m):
a2 = []
for j in range(0, n):
a2.append(original[i*n + j])
a1.append(a2)
return a1
|
convert-1d-array-into-2d-array
|
Easy python
|
gasohel336
| -3
| 200
|
convert 1d array into 2d array
| 2,022
| 0.584
|
Easy
| 28,181
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499007/Python3-freq-table
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
freq = Counter(nums)
ans = 0
for k, v in freq.items():
if target.startswith(k):
suffix = target[len(k):]
ans += v * freq[suffix]
if k == suffix: ans -= freq[suffix]
return ans
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python3] freq table
|
ye15
| 36
| 2,600
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,182
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499029/Python-3-Simple-one-liner-using-permutations()-or-Straightforward
|
class Solution:
def numOfPairs(self, nums, target):
return sum(i + j == target for i, j in permutations(nums, 2))
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python 3] Simple one-liner using permutations() | Straightforward
|
JK0604
| 5
| 556
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,183
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1666741/Python3-simple-solution
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count = 0
for i in range(len(nums)):
for j in range(len(nums)):
if i != j:
res = nums[i] + nums[j]
if target == res:
count += 1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python3 simple solution
|
EklavyaJoshi
| 1
| 148
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,184
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1596875/Python3-Solution-with-using-%22two-sum%22-principal
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
d = collections.defaultdict(int)
for num in nums:
d[num] += 1
res = 0
for num in nums:
if len(num) < len(target) and num == target[:len(num)]:
val = target[len(num):]
val_cnt = d[target[len(num):]]
if val == num:
val_cnt -= 1
res += val_cnt
return res
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python3] Solution with using "two sum" principal
|
maosipov11
| 1
| 104
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,185
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1500283/Two-loops-100-speed
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count, len_nums = 0, len(nums)
for i in range(len_nums - 1):
for j in range(i + 1, len_nums):
if nums[i] + nums[j] == target:
count += 1
if nums[j] + nums[i] == target:
count += 1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Two loops, 100% speed
|
EvgenySH
| 1
| 145
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,186
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2836184/Python3-easy-to-understand
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count = 0
N = len(nums)
for i in range(N):
for j in range(N):
if i != j:
if nums[i] + nums[j] == target:
count += 1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python3 - easy to understand
|
mediocre-coder
| 0
| 3
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,187
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2816240/Beste-Easy-Solution-Bruteforce
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
c=0
for i in range(len(nums)):
lst=[]
lst=nums[:i]+nums[i+1:]
for j in lst:
if nums[i]+j==target:
c+=1
return c
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Beste Easy Solution Bruteforce
|
Kaustubhmishra
| 0
| 5
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,188
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2811615/Python-or-Easy-to-code-or-O(n*n)
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
n = 0
a = target
for i in range(len(nums)):
for j in range(len(nums)):
if i != j and nums[i] + nums[j] == a:
n += 1
return n
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python | Easy to code | O(n*n)
|
bhuvneshwar906
| 0
| 6
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,189
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2811614/Python-or-Easy-to-code-or-O(n*n)
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
n = 0
a = target
for i in range(len(nums)):
for j in range(len(nums)):
if i != j and nums[i] + nums[j] == a:
n += 1
return n
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python | Easy to code | O(n*n)
|
bhuvneshwar906
| 0
| 2
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,190
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2608485/Python-(Simple-Solution-and-Beginner-Friendly)
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
output = 0
for i in range(0, len(nums)):
for j in range(0, len(nums)):
if i != j:
if nums[i]+nums[j] == target:
output+=1
return output
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python (Simple Solution and Beginner-Friendly)
|
vishvavariya
| 0
| 29
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,191
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2551903/Python-Complex-prefix-and-suffix-hash
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
ans = 0
h = {}
d = target[::-1]
for i in range(len(nums)):
if nums[i]==target[0:len(nums[i])]:
if target[len(nums[i]):] in h:
ans+=h[target[len(nums[i]):]]
if nums[i][::-1]==d[0:len(nums[i])]:
if d[len(nums[i]):][::-1] in h:
ans+=h[d[len(nums[i]):][::-1]]
if nums[i] in h:
h[nums[i]] +=1
else:
h[nums[i]] = 1
return ans
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python Complex prefix and suffix hash
|
Brillianttyagi
| 0
| 50
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,192
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2512956/basic-python-solution
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count = 0
for i in range(len(nums)) :
for j in range(len(nums)) :
if (nums[i] + nums[j] == target) and (i != j):
count += 1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
basic python solution
|
sghorai
| 0
| 29
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,193
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/2380408/5-LINER-oror-Beats-99-in-Memory-usage-oror-Beats-45-in-runtime-oror-PYTHON
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
c=0
for i in range(0,len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target and nums[j]+nums[i]==target: c=c+2
elif nums[i]+nums[j]==target or nums[j]+nums[i]==target: c=c+1
return c
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
5 LINER || Beats 99% in Memory usage || Beats 45% in runtime || PYTHON
|
keertika27
| 0
| 52
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,194
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1899393/Python-easy-and-straightforward-solution-with-memory-less-than-72
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count = 0
for i in range(len(nums)):
for j in range(len(nums)):
if i != j:
if nums[i] + nums[j] == target:
count += 1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Python easy and straightforward solution with memory less than 72%
|
alishak1999
| 0
| 114
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,195
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1830012/Ez-sol-oror-Slicing-and-startswith()-oror-explained
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
freq=Counter(nums)
co=0
for key, value in freq.items():
if target.startswith(key):
suffix=target[len(key):]
co+=value*freq[suffix]
if suffix==key: co-=freq[suffix]
return co
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Ez sol || Slicing and startswith() || explained
|
ashu_py22
| 0
| 30
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,196
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1830012/Ez-sol-oror-Slicing-and-startswith()-oror-explained
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
freq=Counter(nums)
co=0
for key, value in freq.items():
if target[:len(key)]==key:
suffix=target[len(key):]
co+=value*freq[suffix]
if suffix==key: co-=freq[suffix]
return co
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Ez sol || Slicing and startswith() || explained
|
ashu_py22
| 0
| 30
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,197
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1631178/Python3-simple
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
current = ''
counts = 0
for i in range(len(nums)):
for j in range(len(nums)):
if i != j:
current = nums[i] + nums[j]
if current == target:
counts += 1
current = ''
return counts
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
[Python3] simple
|
jeehun0719
| 0
| 48
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,198
|
https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1618397/Easy-understanding-Python-solution
|
class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
count=0
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]+nums[j]==target and i!=j:
count+=1
return count
|
number-of-pairs-of-strings-with-concatenation-equal-to-target
|
Easy understanding Python solution
|
1by19cs083
| 0
| 52
|
number of pairs of strings with concatenation equal to target
| 2,023
| 0.729
|
Medium
| 28,199
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.