post_href
stringlengths 57
213
| python_solutions
stringlengths 71
22.3k
| slug
stringlengths 3
77
| post_title
stringlengths 1
100
| user
stringlengths 3
29
| upvotes
int64 -20
1.2k
| views
int64 0
60.9k
| problem_title
stringlengths 3
77
| number
int64 1
2.48k
| acceptance
float64 0.14
0.91
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
|
---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/minimum-average-difference/discuss/2807092/Python3-O(1)-Space | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
left_sum, right_sum = 0, sum(nums)
left, right = 0, len(nums)
min_value, return_idx= abs(right_sum//right), len(nums)-1
for i in range(0,len(nums) - 1):
left_sum += nums[i]
left+=1
right_sum -= nums[i]
right -=1
curr = abs(left_sum//left - right_sum//right)
if min_value > curr or (min_value == curr and i < return_idx):
min_value = curr
return_idx = i
return return_idx | minimum-average-difference | Python3 - O(1) Space | Saitama1v1 | 0 | 3 | minimum average difference | 2,256 | 0.359 | Medium | 31,200 |
https://leetcode.com/problems/minimum-average-difference/discuss/2675685/Python3-Solution-oror-O(N)-Time-and-O(1)-Space-Complexity | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
n=len(nums)
if n==1:
return 0
for i in range(1,n):
nums[i]=nums[i]+nums[i-1]
totalSum=nums[-1]
minVal,minIdx=10000000,0
l=1
r=n-1
for i in range(n-1):
if abs(int(nums[l-1]/l)-int((totalSum-nums[l-1])/r))<minVal:
minVal=abs(int(nums[l-1]/l)-int((totalSum-nums[l-1])/r))
minIdx=l-1
l,r=l+1,r-1
if int(totalSum/n)<minVal:
return l-1
return minIdx | minimum-average-difference | Python3 Solution || O(N) Time & O(1) Space Complexity | akshatkhanna37 | 0 | 7 | minimum average difference | 2,256 | 0.359 | Medium | 31,201 |
https://leetcode.com/problems/minimum-average-difference/discuss/2592708/Python-Prefix-Sum-Solution | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
n = len(nums)
prefix_sum = []
running_sum = 0
for num in nums:
running_sum += num
prefix_sum.append(running_sum)
difference = float('inf')
index = 0
m = len(prefix_sum)
for i in range(1, m):
operand1 = prefix_sum[i - 1] // i
operand2 = (running_sum - prefix_sum[i - 1]) // (m - i)
if abs(operand1 - operand2) < difference:
difference = abs(operand1 - operand2)
index = i - 1
return n - 1 if running_sum // n < difference else index | minimum-average-difference | Python Prefix Sum Solution | mansoorafzal | 0 | 50 | minimum average difference | 2,256 | 0.359 | Medium | 31,202 |
https://leetcode.com/problems/minimum-average-difference/discuss/2471879/Python-Prefix-Sum-O(n)-Solution | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
S, n = sum(nums), len(nums)
prefixSum = [nums[0]]
for i in range(1, len(nums)):
prefixSum.append(prefixSum[-1] + nums[i])
min_diff, min_index = float('inf'), -float('inf')
for i in range(len(nums)):
if n - i - 1 != 0:
abs_diff = abs(prefixSum[i] // (i+1) - (S - prefixSum[i]) // (n - i - 1))
else:
abs_diff = abs(prefixSum[i] // (i+1))
if abs_diff < min_diff:
min_diff = abs_diff
min_index = i
return min_index | minimum-average-difference | Python Prefix Sum O(n) Solution | Vayne1994 | 0 | 60 | minimum average difference | 2,256 | 0.359 | Medium | 31,203 |
https://leetcode.com/problems/minimum-average-difference/discuss/2347332/Faster-than-92-~-python-solution | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
left,right,mins,n = 0 , sum(nums), float('inf'),len(nums)
for i in range(n):
left += nums[i]
right-= nums[i]
first = left//(i+1)
second = 0 if i+1 ==n else right//(len(nums)-(i+1))
result = abs(first - second)
if(result<mins):
mins=result
res=i
return res
```
``` | minimum-average-difference | Faster than 92% ~ python solution | khayaltech | 0 | 56 | minimum average difference | 2,256 | 0.359 | Medium | 31,204 |
https://leetcode.com/problems/minimum-average-difference/discuss/2107213/Python-easy-intuitive-soln | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
# Logic is simple we use prefix sum property
# Rest is done in one pass
# T(n)=o(n)
left=0
right=sum(nums)
mini=float('inf')
ans=0
for i in range(len(nums)):
left+=nums[i]
right-=nums[i]
x=left//(i+1)
if right==0:
y=0
else:
y=right//(len(nums)-(i+1))
if abs(x-y)<mini:
mini=abs(x-y)
ans=i
return ans | minimum-average-difference | Python, easy , intuitive soln | Aniket_liar07 | 0 | 36 | minimum average difference | 2,256 | 0.359 | Medium | 31,205 |
https://leetcode.com/problems/minimum-average-difference/discuss/2003850/python-java-prefix-sum-(Time-On-space-On(java)-O1(python)) | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
for i in range (1, len(nums)) : nums[i] += nums[i-1]
mini = nums[-1] // len(nums)
id = len(nums) - 1
i = id - 1
l = id
r = 1
while i >= 0 :
x = abs(nums[i] // l - (nums[-1] - nums[i]) // r )
if x <= mini :
mini = x
id = i
i -= 1
l -= 1
r += 1
return id | minimum-average-difference | python, java - prefix sum (Time On, space On(java), O1(python)) | ZX007java | 0 | 53 | minimum average difference | 2,256 | 0.359 | Medium | 31,206 |
https://leetcode.com/problems/minimum-average-difference/discuss/1995420/Python-Solution | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
forward = []
total = 0
for i, num in enumerate(nums):
total += num
forward.append(total // (i + 1))
backward = [0]
total = 0
for i, num in enumerate(nums[::-1][:len(nums) - 1]):
total += num
backward.append(total // (i + 1))
result = float('inf')
n = len(nums)
for i in range(len(forward)):
if result > abs(forward[i] - backward[n - i- 1]):
ans = i
result = abs(forward[i] - backward[n - i - 1])
if len(nums) == 1:
return 0
return ans | minimum-average-difference | Python Solution | user6397p | 0 | 24 | minimum average difference | 2,256 | 0.359 | Medium | 31,207 |
https://leetcode.com/problems/minimum-average-difference/discuss/1995264/Prefix-postfix-Sum-oror-O(n)-Space-Python3 | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
if len(nums) == 1:
if nums[0] == 0:
return 0
if nums[0] == 1:
return 0
temp1 = 0
prefix = []
temp2 = 0
postfix = []
for num in nums:
prefix.append(temp1)
temp1 += num
for i in range(len(nums)-1,-1,-1):
postfix.append(temp2)
temp2 += nums[i]
postfix.reverse()
ans = []
n = len(nums)
for i in range(n-1):
temp = abs((nums[i]+prefix[i])//(i+1)-(postfix[i])//(n-i-1))
ans.append(temp)
#Exception handled in 32 and 33 line
temp = sum(nums)//n
ans.append(temp)
t = float('inf')
![Uploading file...]()
for i in range(len(ans)):
if ans[i]<t:
a = i
t = ans[i]
return a | minimum-average-difference | Prefix postfix Sum || O(n) Space Python3 | COEIT_1903480130037 | 0 | 23 | minimum average difference | 2,256 | 0.359 | Medium | 31,208 |
https://leetcode.com/problems/minimum-average-difference/discuss/1994912/Prefix-Sum-oror-O(n) | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
s=sum(nums)
n=len(nums)
l=[]
c=0
d=0
for i in range(len(nums)-1):
""" Adding nums[i] to c to keep record of sum(nums[:i]) """
c+=nums[i]
""" Subtracting c from sum(nums) so that d become updated """
d=s-c
a=c//(i+1)
b=d//(n-i-1)
l.append(abs(a-b))
""" Appending whole sum(nums) into l as control of execution reaches at the last element of nums"""
l.append(sum(nums)//n)
return l.index(min(l))
``` | minimum-average-difference | Prefix Sum || O(n) | a_dityamishra | 0 | 17 | minimum average difference | 2,256 | 0.359 | Medium | 31,209 |
https://leetcode.com/problems/minimum-average-difference/discuss/1994630/Python3-O(n)-prefix-sum-Solution | class Solution:
def minimumAverageDifference(self, nums: List[int]) -> int:
total_sum = sum(nums)
start = 0
prefix_sum = []
for element in nums:
start += element
prefix_sum.append(start)
mini = sys.maxsize
res = None
size_t = len(nums)
for i in range(len(nums)-1):
diff = abs(floor(prefix_sum[i]/(i+1)) - floor((total_sum - prefix_sum[i])/(size_t - i - 1)))
if diff < mini:
mini = diff
res = i
last_diff = abs(floor(total_sum/size_t))
if last_diff < mini: mini = last_diff; res = size_t - 1
return res | minimum-average-difference | Python3 O(n) prefix sum Solution | xxHRxx | 0 | 20 | minimum average difference | 2,256 | 0.359 | Medium | 31,210 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994806/Simple-python-code | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
vis = [[0]*n for _ in range(m)]
# i - rows, j - colums
# sum(row.count('hit') for row in grid)
for i,j in walls:
vis[i][j] = 2
for i,j in guards:
vis[i][j] = 2
for i,j in guards:
for l in range(j-1,-1,-1):
if self.checkWall(i,l,vis):
break
vis[i][l] = 1
for r in range(j+1,n):
if self.checkWall(i,r,vis):
break
vis[i][r] = 1
for u in range(i-1,-1,-1):
if self.checkWall(u,j,vis):
break
vis[u][j] = 1
for d in range(i+1,m):
if self.checkWall(d,j, vis):
break
vis[d][j] = 1
return sum(row.count(0) for row in vis)
def checkWall(self, i, j, vis):
if vis[i][j] ==2:
return True | count-unguarded-cells-in-the-grid | Simple python code | beast316 | 1 | 37 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,211 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994591/Python-solution-using-DFS. | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
#Create a matrix, hint from question
mat = [[0 for _ in range(n)] for _ in range(m)]
for [i,j] in guards:
mat[i][j] = 1
for [i,j] in walls:
mat[i][j] = -1
#dfs for marking paths.
def dfs(i,j,di):
if i<0 or i>=m or j<0 or j>=n or mat[i][j] == 1 or mat[i][j] == -1:
return
else:
mat[i][j] = 2
i = i + lst[di]
j = j + lst[di+1]
dfs(i,j,di)
lst = [1,0,-1,0,1]
for [i,j] in guards:
for idx in range(4):
k = i + lst[idx]
l = j + lst[idx+1]
dfs(k,l,idx)
#count uncovered cells.
count = 0
for i in range(m):
for j in range(n):
if mat[i][j]==0:
count +=1
return count | count-unguarded-cells-in-the-grid | Python solution using DFS. | avshet_a01 | 1 | 52 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,212 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994560/Python-or-DFS-or-Greedy-or-O(mn) | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
guarded = set()
guard_set = set()
wall_set = set()
for guard in guards: guard_set.add((guard[0], guard[1]))
for wall in walls: wall_set.add((wall[0], wall[1]))
# left, right, bottom, top
directions = [(1, 0), (-1, 0), (0, -1), (0, 1)]
# find all guarded
for guard in guards:
for dx, dy in directions:
x, y = guard
# travel one direction
while 0 <= x + dx < m and 0 <= y + dy < n:
x, y = x + dx , y + dy
if (x, y) in guard_set or (x, y) in wall_set: break
guarded.add((x, y))
# count unguarded
not_guarded_count = 0
for i in range(m):
for j in range(n):
if (i,j) not in guarded and (i, j) not in wall_set and (i, j) not in guard_set:
not_guarded_count += 1
return not_guarded_count | count-unguarded-cells-in-the-grid | Python | DFS | Greedy | O(mn) | rbhandu | 1 | 61 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,213 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/2713446/Python3-Count-as-you-go.-Commented-and-Easy-solution. | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
# make the grid which cells are guarded
unseen = [[1]*n for _ in range(m)]
# initialize a the number of unseen cells
result = m*n
# set all the walls and guards
for rx, cx in walls + guards:
# place the wall
unseen[rx][cx] = 0
# subtract from result
result -= 1
# now go over all the guards and update result
# grx is guard row index
# gcx is guard column index
# brx is "blick" row index (blick is german for view)
# bcx is "blick" column index
for grx, gcx in guards:
# go from this position till the left end or until we hit a wall
for bcx in range(gcx-1, -1, -1):
# check whether we change an unseen box
if unseen[grx][bcx] == 1:
unseen[grx][bcx] = -1
result -= 1
# check whether we hit a wall or other guard
elif unseen[grx][bcx] == 0:
break
# go from this position to the right end or wall
for bcx in range(gcx+1, n):
# check whether we change an unseen box
if unseen[grx][bcx] == 1:
unseen[grx][bcx] = -1
result -= 1
# check whether we hit a wall or other guard
elif unseen[grx][bcx] == 0:
break
# go from this position up and check for end or walls
for brx in range(grx-1, -1, -1):
# check whether we change an unseen box
if unseen[brx][gcx] == 1:
unseen[brx][gcx] = -1
result -= 1
# check whether we hit a wall or other guard
elif unseen[brx][gcx] == 0:
break
# go from this position down and check for end or walls
for brx in range(grx+1, m):
# check whether we change an unseen box
if unseen[brx][gcx] == 1:
unseen[brx][gcx] = -1
result -= 1
# check whether we hit a wall or other guard
elif unseen[brx][gcx] == 0:
break
return result | count-unguarded-cells-in-the-grid | [Python3] - Count as you go. Commented and Easy solution. | Lucew | 0 | 2 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,214 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/2046865/Python3-No-grid-interval-merge-%2B-binary-search | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
amt = (m * n) - len(walls)
walls_x, walls_y = defaultdict(list), defaultdict(list)
ranges_x, ranges_y = defaultdict(list), defaultdict(list)
for x, y in walls:
insort_left(walls_x[x], y)
insort_left(walls_y[y], x)
def range_search(a, i, lim):
if not a:
return (0, lim)
j = bisect_left(a, i)
if j == len(a):
return (a[-1]+1, lim)
if j == 0:
if a[j] < i:
return (a[0]+1, lim)
return (0, a[0])
return (a[j-1]+1, a[j])
for x, y in guards:
insort_left(ranges_x[x], range_search(walls_x[x], y, n))
insort_left(ranges_y[y], range_search(walls_y[y], x, m))
for d in ranges_x, ranges_y:
for s in d:
d[s] = self.merge(d[s])
y_list = sorted(ranges_y)
for ranges in ranges_x, ranges_y:
amt -= sum((c2 - c1) for cs in ranges.values() for c1, c2 in cs)
for x, ys in ranges_x.items():
for y1, y2 in ys:
for y in y_list[bisect_left(y_list, y1):bisect_left(y_list, y2)]:
ip = min(bisect_left(ranges_y[y], (x,)), len(ranges_y[y])-1)
if x in range(*ranges_y[y][ip]) or (ip > 0 and x in range(*ranges_y[y][ip-1])):
amt += 1
return amt
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
out = []
for start, end in intervals:
if not out:
out.append((start, end))
elif out[-1][1] >= start:
out[-1] = out[-1][0], max(end, out[-1][1])
else:
out.append((start, end))
return out | count-unguarded-cells-in-the-grid | [Python3] No grid, interval merge + binary search | NotTheSwimmer | 0 | 68 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,215 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/2046865/Python3-No-grid-interval-merge-%2B-binary-search | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
amt = (m * n) - len(walls)
walls_x, walls_y = defaultdict(list), defaultdict(list)
ranges_x, ranges_y = defaultdict(list), defaultdict(list)
for x, y in walls:
walls_x[x].append(y)
walls_y[y].append(x)
for d in walls_x, walls_y:
for l in d.values():
l.sort()
def range_search(a, i, lim):
if not a:
return (0, lim)
j = bisect_left(a, i)
if j == len(a):
return (a[-1]+1, lim)
if j == 0:
if a[j] < i:
return (a[0]+1, lim)
return (0, a[0])
return (a[j-1]+1, a[j])
for x, y in guards:
ranges_x[x].append(range_search(walls_x[x], y, n))
ranges_y[y].append(range_search(walls_y[y], x, m))
for d in ranges_x, ranges_y:
for s in d:
d[s] = self.merge(d[s])
y_list = sorted(ranges_y)
for x, ys in ranges_x.items():
for y1, y2 in ys:
amt -= (y2 - y1)
yl = bisect_left(y_list, y1)
yr = bisect_left(y_list, y2)
for y in y_list[yl:yr]:
if x not in range(ranges_y[y][0][0], ranges_y[y][-1][1]):
continue
ip = min(bisect_left(ranges_y[y], (x,)), len(ranges_y[y])-1)
if x in range(*ranges_y[y][ip]) or (ip > 0 and x in range(*ranges_y[y][ip-1])):
amt += 1
for y, xs in ranges_y.items():
for x1, x2 in xs:
amt -= (x2 - x1)
return amt
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
out = []
for start, end in intervals:
if not out:
out.append((start, end))
elif out[-1][1] >= start:
out[-1] = out[-1][0], max(end, out[-1][1])
else:
out.append((start, end))
return out | count-unguarded-cells-in-the-grid | [Python3] No grid, interval merge + binary search | NotTheSwimmer | 0 | 68 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,216 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/2001783/Set-of-cells-iterate-over-guards-58-speed | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
set_g = set((r, c) for r, c in guards)
set_w = set((r, c) for r, c in walls)
set_cells = set((r, c) for r in range(m) for c in range(n))
set_cells -= set_g
set_cells -= set_w
seen_cells = set()
for guard_r, guard_c in set_g:
# right
r, c = guard_r, guard_c + 1
while (r, c) in set_cells:
seen_cells.add((r, c))
c += 1
# left
r, c = guard_r, guard_c - 1
while (r, c) in set_cells:
seen_cells.add((r, c))
c -= 1
# down
r, c = guard_r + 1, guard_c
while (r, c) in set_cells:
seen_cells.add((r, c))
r += 1
# up
r, c = guard_r - 1, guard_c
while (r, c) in set_cells:
seen_cells.add((r, c))
r -= 1
return len(set_cells - seen_cells) | count-unguarded-cells-in-the-grid | Set of cells, iterate over guards, 58% speed | EvgenySH | 0 | 20 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,217 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1999394/Python3-or-DP-or-Explained-solution | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
mat = [['X' for _ in range(n)] for _ in range(m)]
for row, col in guards:
mat[row][col] = 'G'
for row, col in walls:
mat[row][col] = 'W'
seen_guard = False
ans = 0
# from left to right
for i in range(m):
# flag is deactivated for each row
seen_guard = False
for j in range(n):
# curr cell has guard
# activate flag
if mat[i][j] == 'G':
seen_guard = True
# curr cell has wall
# deactivate the flag
elif mat[i][j] == 'W':
seen_guard = False
# open cell
# close if a guard watching
elif mat[i][j] == 'X':
if seen_guard:
mat[i][j] = 'O'
else:
ans += 1
#print(ans)
# from right to left
for i in range(m):
# flag is deactivated for each row
seen_guard = False
for j in range(n - 1, -1 , -1):
if mat[i][j] == 'O':
continue
# curr cell has guard
# activate flag
elif mat[i][j] == 'G':
seen_guard = True
# curr cell has wall
# deactivate the flag
elif mat[i][j] == 'W':
seen_guard = False
# open cell
# close if a guard watching
elif mat[i][j] == 'X':
if seen_guard:
mat[i][j] = 'O'
ans -= 1
# from top to bottom
for j in range(n):
# flag is deactivated for each row
seen_guard = False
for i in range(m):
if mat[i][j] == 'O':
continue
# curr cell has guard
# activate flag
elif mat[i][j] == 'G':
seen_guard = True
# curr cell has wall
# deactivate the flag
elif mat[i][j] == 'W':
seen_guard = False
# open cell
# close if a guard watching
elif mat[i][j] == 'X':
if seen_guard:
mat[i][j] = 'O'
ans -= 1
# from bottom to top
for j in range(n):
# flag is deactivated for each row
seen_guard = False
for i in range(m - 1, -1, -1):
if mat[i][j] == 'O':
continue
# curr cell has guard
# activate flag
elif mat[i][j] == 'G':
seen_guard = True
# curr cell has wall
# deactivate the flag
elif mat[i][j] == 'W':
seen_guard = False
# open cell
# close if a guard watching
elif mat[i][j] == 'X':
if seen_guard:
mat[i][j] = 'O'
ans -= 1
return ans | count-unguarded-cells-in-the-grid | Python3 | DP | Explained solution | showing_up_each_day | 0 | 18 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,218 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994920/Greedy-Python-Solution-oror-100-Faster-oror-Memory-less-than-67 | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
G=set() ; M=[[0]*n for _ in range(m)]
for i,j in walls: M[i][j]=1
for i,j in guards: M[i][j]=2
for i,j in guards:
j1=j-1
while j1>=0:
if M[i][j1] in (1,2): break
G.add((i,j1))
j1-=1
j1=j+1
while j1<n:
if M[i][j1] in (1,2): break
G.add((i,j1))
j1+=1
i1=i-1
while i1>=0:
if M[i1][j] in (1,2): break
G.add((i1,j))
i1-=1
i1=i+1
while i1<m:
if M[i1][j] in (1,2): break
G.add((i1,j))
i1+=1
return m*n-len(guards)-len(walls)-len(G) | count-unguarded-cells-in-the-grid | Greedy Python Solution || 100% Faster || Memory less than 67% | Taha-C | 0 | 12 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,219 |
https://leetcode.com/problems/count-unguarded-cells-in-the-grid/discuss/1994679/Python3-two-pass-O(mn)-Solution | class Solution:
def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:
grid = [[0]*n for _ in range(m)]
for x, y in guards:
grid[x][y] = 'G'
for x, y in walls:
grid[x][y] = 'W'
grid2 = [[0]*n for _ in range(m)]
for x, y in guards:
grid2[x][y] = 'G'
for x, y in walls:
grid2[x][y] = 'W'
for i in range(m):
cache = []
has_G = False
for j in range(n):
if grid[i][j] == 0:
cache.append(j)
elif grid[i][j] == 'G':
if cache:
for k in cache:
grid[i][k] = 'O'
cache = []
has_G = True
else:
if has_G:
if cache:
for k in cache:
grid[i][k] = 'O'
cache = []
has_G = False
else:
cache = []
if cache:
if has_G:
for k in cache:
grid[i][k] = 'O'
for j in range(n):
cache = []
has_G = False
for i in range(m):
if grid2[i][j] == 0:
cache.append(i)
elif grid2[i][j] == 'G':
if cache:
for k in cache:
grid2[k][j] = 'O'
cache = []
has_G = True
else:
if has_G:
if cache:
for k in cache:
grid2[k][j] = 'O'
cache = []
has_G = False
else:
cache = []
if cache:
if has_G:
for k in cache:
grid2[k][j] = 'O'
res = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 0 and grid2[i][j] == 0: res += 1
return res | count-unguarded-cells-in-the-grid | Python3 two pass O(mn) Solution | xxHRxx | 0 | 17 | count unguarded cells in the grid | 2,257 | 0.522 | Medium | 31,220 |
https://leetcode.com/problems/escape-the-spreading-fire/discuss/2005513/Python3-BFS-%2B-DFS-%2B-Binary-Search-Solution | class Solution:
def maximumMinutes(self, grid: List[List[int]]) -> int:
#region growing to assign each grass with the time that it will catch fire
m, n = len(grid), len(grid[0])
start = []
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
start.append([i,j])
grid[i][j] = 'F'
elif grid[i][j] == 2:
grid[i][j] = 'W'
visited = set()
for element in start: visited.add(tuple(element))
time = 1
while start:
new_start = []
for x, y in start:
if x >= 1:
if grid[x-1][y] == 0 and (x-1, y) not in visited:
new_start.append([x-1, y])
visited.add((x-1, y))
grid[x-1][y] = time
if x < m-1:
if grid[x+1][y] == 0 and (x+1, y) not in visited:
new_start.append([x+1, y])
visited.add((x+1, y))
grid[x+1][y] = time
if y >= 1:
if grid[x][y-1] == 0 and (x, y-1) not in visited:
new_start.append([x, y-1])
visited.add((x, y-1))
grid[x][y-1] = time
if y < n-1:
if grid[x][y+1] == 0 and (x, y+1) not in visited:
new_start.append([x, y+1])
visited.add((x, y+1))
grid[x][y+1] = time
time += 1
start = new_start
#memo variable will save time from search path that is already proved to be impossible
memo = {}
def search(x, y, time, visited):
if (x,y) in memo and time >= memo[(x,y)]: return False
if time > grid[-1][-1]: return False
if x == m-1 and y == n-1:
if grid[x][y] == 0:
return True
else:
if grid[x][y] >= time:
return True
else:
if grid[x][y] == time: return False
visited.add((x,y))
if x >= 1:
if grid[x-1][y] != 'W' and grid[x-1][y] != 'F' and grid[x-1][y] > time and (x-1, y) not in visited:
res = search(x-1, y, time+1, visited)
if res: return True
if x < m-1:
if grid[x+1][y] != 'W' and grid[x+1][y] != 'F' and grid[x+1][y] > time and (x+1, y) not in visited:
res = search(x+1, y, time+1, visited)
if res: return True
if y >= 1:
if grid[x][y-1] != 'W' and grid[x][y-1] != 'F' and grid[x][y-1] > time and (x, y-1) not in visited:
res = search(x, y-1, time+1, visited)
if res: return True
if y < n-1:
if grid[x][y+1] != 'W' and grid[x][y+1] != 'F' and grid[x][y+1] > time and (x, y+1) not in visited:
res = search(x, y+1, time+1, visited)
if res: return True
visited.remove((x,y))
if (x,y) not in memo: memo[(x,y)] = time
else: memo[(x,y)] = min(time, memo[(x,y)])
return False
if grid[0][0] == 0:
if search(0, 0, -sys.maxsize, set()): return 10**9
else: return -1
else:
start, end = 0, grid[0][0]-1
#binary search
while start < end:
mid = ceil((start + end)/2)
if search(0, 0, mid, set()):
start = mid
else:
end = mid - 1
if start != 0: return start
else:
if search(0, 0, 0, set()): return 0
else: return -1 | escape-the-spreading-fire | Python3 BFS + DFS + Binary Search Solution | xxHRxx | 0 | 44 | escape the spreading fire | 2,258 | 0.347 | Hard | 31,221 |
https://leetcode.com/problems/escape-the-spreading-fire/discuss/1995390/Python-3Binary-search | class Solution:
def maximumMinutes(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
def nei(x, y):
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] != 2:
yield nx, ny
# recreate array to store earliest time caught fire for each grassland
arr = [[0] * n for _ in range(m)]
for x in range(m):
for y in range(n):
if grid[x][y] == 0:
arr[x][y] = float('inf')
elif grid[x][y] == 1:
arr[x][y] = -1
elif grid[x][y] == 2:
arr[x][y] = -2
# start from each fire and compute earliest time to reach each grass
def fire_reach_grass(i, j):
q = [(0, i, j)]
while q:
new_q = []
for t, x, y in q:
for nx, ny in nei(x, y):
if arr[nx][ny] <= t + 1: continue
arr[nx][ny] = t + 1
new_q.append((t+1, nx, ny))
q = new_q
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
fire_reach_grass(i, j)
def person_reach_safehouse(delay):
q = [(delay, 0, 0)]
vis = defaultdict(lambda: float('inf'), {(0, 0): 0})
while q:
new_q = []
for t, x, y in q:
for nx, ny in nei(x, y):
# reach safehouse and fire spread at same time is allowed
if nx == m - 1 and ny == n - 1 and arr[nx][ny] >= t + 1: return True
# otherwise reach at same time at grassland is not allowed
if arr[nx][ny] == -1 or arr[nx][ny] <= t + 1 or vis[nx, ny] <= t + 1: continue
vis[nx, ny] = t + 1
new_q.append((t+1, nx, ny))
q = new_q
return False
# binary search to find the maximum delay time
l, h = 0, m*n
while l < h:
mid = l + (h - l + 1) // 2
if person_reach_safehouse(mid):
l = mid
if mid == m*n: return 10**9
else:
if mid == 0: return -1
h = mid - 1
return l if person_reach_safehouse(l) else -1 | escape-the-spreading-fire | [Python 3]Binary search | chestnut890123 | 0 | 35 | escape the spreading fire | 2,258 | 0.347 | Hard | 31,222 |
https://leetcode.com/problems/escape-the-spreading-fire/discuss/1994651/python-bfs-%2B-binary-search-%2B-preprocessing | class Solution:
def maximumMinutes(self, grid: List[List[int]]) -> int:
R, C = len(grid), len(grid[0])
lo = 0
hi = 1000000000
fire = [[float('inf')] * C for _ in range(R)]
q = deque()
for r in range(R):
for c in range(C):
if grid[r][c] == 1:
fire[r][c] = 0
q.appendleft((r, c))
step = 0
while q:
nq = deque()
while q:
r, c = q.pop()
for dr, dc in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
rr, cc = r + dr, c + dc
if 0 <= rr < R and 0 <= cc < C and grid[rr][cc] == 0 and fire[rr][cc] == float('inf'):
nq.appendleft((rr, cc))
fire[rr][cc] = min(fire[rr][cc], step + 1)
step += 1
q = nq
def check(mid):
q = deque([(0, 0)])
v = {(0, 0): mid}
while q:
r, c = q.pop()
step = v[r, c]
if r == R - 1 and c == C - 1:
return True
for dr, dc in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
rr, cc = dr + r, c + dc
if 0 <= rr < R and 0 <= cc < C and grid[rr][cc] == 0 and (rr, cc) not in v and \
(step + 1 < fire[rr][cc] or (rr, cc) == (R - 1, C - 1) and step + 1 <= fire[rr][cc] ):
q.appendleft((rr, cc))
v[rr, cc] = step + 1
return False
while lo < hi:
mid = (lo + hi + 1) // 2
if check(mid):
lo = mid
else:
hi = mid - 1
if check(lo):
return lo
return -1 | escape-the-spreading-fire | python bfs + binary search + preprocessing | WRWRW | 0 | 40 | escape the spreading fire | 2,258 | 0.347 | Hard | 31,223 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2074599/Python-O(N)-solution-oror-Faster-than-99-submissions-oror-Detailed-explanation. | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
# Initializing the last index as zero
last_index = 0
#iterating each number to find the occurences, \
# and to find if the number is greater than the next element \
for num in range(1, len(number)):
# Handling [case 1] and [case 2]
if number[num-1] == digit:
if int(number[num]) > int(number[num-1]):
return number[:num-1] + number[num:]
else:
last_index = num - 1
# If digit is the last number (last occurence) in the string [case 3]
if number[-1] == digit:
last_index = len(number) - 1
return number[:last_index] + number[last_index + 1:] | remove-digit-from-number-to-maximize-result | 🔥🔥🔥Python O(N) solution || Faster than 99% submissions || Detailed explanation. | litdatascience | 16 | 1,400 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,224 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/1996355/Python-3-Brute-Force-Easy-Solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
ans = 0
for i, dig in enumerate(list(number)):
if dig == digit:
ans = max(ans, int(number[:i]+number[i+1:]))
return str(ans) | remove-digit-from-number-to-maximize-result | [Python 3] Brute Force Easy Solution | hari19041 | 9 | 613 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,225 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/1996949/Easy-Solution-oror-O(n) | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
l=[]
for i in range(len(number)):
if number[i]==digit:
l.append(int(number[:i]+number[i+1:]))
return str(max(l)) | remove-digit-from-number-to-maximize-result | Easy Solution || O(n) | a_dityamishra | 2 | 66 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,226 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2074471/Python-3-Brute-Force-Single-Statment | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
return max (
number[:i] + number[i+1:]
for i in range(len(number))
if number[i] == digit
) | remove-digit-from-number-to-maximize-result | [Python 3] Brute Force - Single Statment | Lindelt | 1 | 81 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,227 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2033135/Python-solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
ans = []
for ind,i in enumerate(number):
if i == digit:
ans.append(int(number[:ind]+number[ind+1:]))
return str(max(ans)) | remove-digit-from-number-to-maximize-result | Python solution | StikS32 | 1 | 129 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,228 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/1996778/python-easy-solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
last = -1
for i in range (len(number)) :
if number[i] == digit :
last = i
if i != len(number) - 1 and number[i] < number[i+1] :
return number[0:i] + number[i+1:]
return number[0:last] + number[last+1:] | remove-digit-from-number-to-maximize-result | python - easy solution | ZX007java | 1 | 256 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,229 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2845059/python | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
ans = '0'
for i, num in enumerate(number):
if num == digit:
ans = max(number[:i] + number[i + 1:], ans)
return ans | remove-digit-from-number-to-maximize-result | python | xy01 | 0 | 2 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,230 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2811483/Python3-oror-Easy-solution-using-String-Slicing | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
ans=[]
for i in range(len(number)):
if number[i] ==digit:
s=number[:i]+number[i+1:]
ans.append(int(s))
return str(max(ans)) | remove-digit-from-number-to-maximize-result | [Python3] || Easy solution using String Slicing | divyanshuan | 0 | 3 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,231 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2801137/Python-Solution%3A-Using-Join-Method | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
l=[x for x in number]
large=0
for i in range (len(l)):
if l[i] == digit:
n=''.join(l[:i])+''.join(l[i+1:])
if(int(n)>large):
large=int(n)
return str(large) | remove-digit-from-number-to-maximize-result | Python Solution: Using Join Method | CharuArora_ | 0 | 2 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,232 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2781970/Python-solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
maxi = 0
for i in range(len(number)):
if number[i]==digit:
if maxi< int(number[:i]+number[i+1:]):
maxi = int(number[:i]+number[i+1:])
return str(maxi) | remove-digit-from-number-to-maximize-result | Python solution | Rajeev_varma008 | 0 | 4 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,233 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2705095/Easy-to-Understand-or-Python | class Solution(object):
def removeDigit(self, number, digit):
ans = 0
for i in range(len(number)):
if number[i] == digit:
temp = number[:i] + number[i+1:]
if int(temp) > ans:
ans = int(temp)
return str(ans) | remove-digit-from-number-to-maximize-result | Easy to Understand | Python | its_krish_here | 0 | 6 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,234 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2703141/Python%3A-Single-for-and-if-statement-solution-with-comments | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
#iterate through the number
hold = number
arr = []
for i in range(0, len(number)):
number = hold
#if digit is found, "remove" the current digit, and put everything before number[i] and
#everything after number [i] into the arr
if number[i] == digit:
arr.append(number[:i]+number[i+1:])
#use a bulit in max function to return the maximum value in all stored values
return max(arr) | remove-digit-from-number-to-maximize-result | Python: Single for and if statement solution with comments | findarian1 | 0 | 4 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,235 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2688986/Simple-Python-Solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
arr=[]
n=len(number)
for i in range(n):
if number[i]==digit:
arr.append(int(number[:i]+number[i+1:]))
return str(max(arr)) | remove-digit-from-number-to-maximize-result | Simple Python Solution | Siddharth_singh | 0 | 5 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,236 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2666909/Easy-and-optimal | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
res=0
for i in range(0,len(number)):
if(number[i]==digit):
d=int(number[:i]+number[i+1:])
res=max(res,d)
return str(res) | remove-digit-from-number-to-maximize-result | Easy and optimal | Raghunath_Reddy | 0 | 3 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,237 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2614068/Python-Simple-Python-Solution-Using-Brute-Force | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
result = 0
for i in range(len(number)):
if number[i] == digit:
new_number = number[:i] + number[i+1:]
result = max(result, int(new_number))
return str(result) | remove-digit-from-number-to-maximize-result | [ Python ] ✅✅ Simple Python Solution Using Brute Force🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 23 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,238 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2457988/3-liner-python-solution-99.73-faster | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
ans = ''
for i in range(len(number)):
if number[i] == digit:
ans = max(ans, number[:i]+number[i+1:])
return ans | remove-digit-from-number-to-maximize-result | 3 liner python solution, 99.73% faster | yash921 | 0 | 90 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,239 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2328727/Python-easy-Solution-or-O(Nor1)-or-No-Slicing | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
mark,found = -1,0
number = list(number)
for i in range(len(number)):
if i!=len(number)-1 and number[i]==digit:
if int(number[i+1])>int(number[i]):
mark = i
found = -1
break
elif int(number[i+1])<int(number[i]):
mark = i
if number[len(number)-1] == digit and found==0:
mark = len(number)-1
number.pop(mark)
ans = "".join(number)
return ans | remove-digit-from-number-to-maximize-result | Python easy Solution | O(N|1) | No Slicing | user7457RV | 0 | 52 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,240 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2248744/Python-Solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
result = ''
for i in range(len(number)):
if number[i] == digit:
result = max(number[:i] + number[i + 1:], result)
return result | remove-digit-from-number-to-maximize-result | Python Solution | hgalytoby | 0 | 67 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,241 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2248744/Python-Solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
i = number.find(digit)
result = ''
while i != -1:
result = max(number[:i] + number[i + 1:], result)
i = number.find(digit, i + 1)
return result | remove-digit-from-number-to-maximize-result | Python Solution | hgalytoby | 0 | 67 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,242 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2159123/Python-oror-Straight-Forward | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
max_ = '0'
for i, l in enumerate(number):
if l == digit:
if number[:i] + number[i+1:] > max_: max_ = number[:i] + number[i+1:]
return max_ | remove-digit-from-number-to-maximize-result | Python || Straight Forward | morpheusdurden | 0 | 137 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,243 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2017064/Easy-Solution-python3 | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
res=""
for x in range(len(number)):
if number[x]==digit:
if x<len(number)-1:
if number[x]<number[x+1]:
return number[0:x]+number[x+1:]
for x in range(len(number)-1,-1,-1):
if number[x]==digit:
return number[0:x]+number[x+1:] | remove-digit-from-number-to-maximize-result | Easy Solution python3 | moazmar | 0 | 84 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,244 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2015393/Python-easy-solution-for-beginners | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
res_nums = set()
pos = 0
for i in range(number.count(digit)):
ind = number.index(digit, pos, len(number))
res = number[:ind] + number[ind+1:]
if int(res) not in res_nums:
res_nums.add(int(res))
pos = ind + 1
return str(max(res_nums)) | remove-digit-from-number-to-maximize-result | Python easy solution for beginners | alishak1999 | 0 | 74 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,245 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2013546/Python-Easy-To-Understand-Solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
s, index = "", -1
for i in range(len(number)):
if number[i] == digit:
temp = number[0 : i] + number[i + 1 :]
if s != "":
if int(s) < int(temp):
index, s = i, temp
else:
s = temp
return s | remove-digit-from-number-to-maximize-result | Python Easy To Understand Solution | Hejita | 0 | 54 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,246 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2003767/Python-Clean-and-Simple! | class Solution:
def removeDigit(self, num, digit):
maxNum = 0
for i,c in enumerate(num):
if c == digit:
newNum = int(num[:i]+num[i+1:])
maxNum = max(maxNum, newNum)
return str(maxNum) | remove-digit-from-number-to-maximize-result | Python - Clean and Simple! | domthedeveloper | 0 | 80 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,247 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/1998155/Python-one-liner | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
return max(number[:i]+number[i+1:] for i, c in enumerate(number) if c == digit) | remove-digit-from-number-to-maximize-result | Python one liner | blue_sky5 | 0 | 42 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,248 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/1996526/python-3-oror-simple-O(n) | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
last = -1
n = len(number)
for i in range(n - 1):
if number[i] == digit:
if number[i] < number[i + 1]:
return number[:i] + number[i + 1:]
last = i
if number[n - 1] == digit:
last = n - 1
return number[:last] + number[last + 1:] | remove-digit-from-number-to-maximize-result | python 3 || simple O(n) | dereky4 | 0 | 71 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,249 |
https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/1996444/Python-beginner-friendly-solution | class Solution:
def removeDigit(self, number: str, digit: str) -> str:
res_nums = set()
pos = 0
for i in range(number.count(digit)):
ind = number.index(digit, pos, len(number))
res = number[:ind] + number[ind+1:]
if int(res) not in res_nums:
res_nums.add(int(res))
pos = ind + 1
return str(max(res_nums)) | remove-digit-from-number-to-maximize-result | Python beginner friendly solution | alishak1999 | 0 | 52 | remove digit from number to maximize result | 2,259 | 0.47 | Easy | 31,250 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996393/Python3-or-Beginner-friendly-explained-or | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
minPick = float('inf')
seen = {}
for i, n in enumerate(cards):
if n in seen:
if i - seen[n] + 1 < minPick:
minPick = i - seen[n] + 1
seen[n] = i
if minPick == float('inf'):
return -1
return minPick | minimum-consecutive-cards-to-pick-up | Python3 | Beginner-friendly explained | | hanjo108 | 22 | 919 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,251 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2729646/Python3-or-HashMaps | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
HashMap={}
lengths=[]
for i,j in enumerate(cards):
if j in HashMap:
lengths.append(abs(HashMap[j]-i)+1)
HashMap[j]=i
else:
HashMap[j]=i
if len(lengths)>0:
return min(lengths)
else:
return -1`` | minimum-consecutive-cards-to-pick-up | Python3 | HashMaps | gpavanik | 1 | 62 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,252 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2099186/PYTHON-oror-EASY-oror-SET-and-DICTIONARY | class Solution:
def minimumCardPickup(self, a: List[int]) -> int:
d=set()
s={}
n=len(a)
for i in range(n):
if a[i] in s:
d.add(a[i])
s[a[i]].append(i)
else:
s[a[i]]=[i]
if len(d)==0:
return -1
for i in d:
for j in range(len(s[i])-1):
n=min(n,s[i][j+1]-s[i][j])
return n+1 | minimum-consecutive-cards-to-pick-up | 🐍 PYTHON 🐍 || EASY || SET & DICTIONARY | karan_8082 | 1 | 71 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,253 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996822/python-easy-hash-solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
table = dict()
answer = len(cards)
for i in range (len(cards)) :
if cards[i] in table :
answer = min(answer, i - table[cards[i]])
table[cards[i]] = i
if answer == len(cards) : answer = -2
return answer + 1 | minimum-consecutive-cards-to-pick-up | python - easy hash solution | ZX007java | 1 | 62 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,254 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2846080/Py-Hash-O(N) | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
cards_dict = defaultdict(list)
ans = float("inf")
for i in range(len(cards)):
cards_dict[cards[i]].append(i)
for key in cards_dict:
arr = cards_dict[key]
for j in range(len(arr) - 1):
ans = min(ans, (arr[j + 1] - arr[j] + 1))
return ans if ans < float("inf") else -1 | minimum-consecutive-cards-to-pick-up | Py Hash O(N) | haly-leshchuk | 0 | 1 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,255 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2823135/Python-solution-using-dictionaries | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
from collections import defaultdict
mydict = defaultdict(list)
for i,aCard in enumerate(cards):
mydict[aCard].append(i)
mydict = dict([(k,v) for k,v in mydict.items() if len(v)>1])
smallest = 1e9
target = -1
for k,v in mydict.items():
for i in range(len(v) - 1):
if (v[i+1 ] -v[i] +1) < smallest:
smallest = v[i+1] -v[i] +1
target = k
if smallest ==1e9:
return -1
else:
return smallest | minimum-consecutive-cards-to-pick-up | Python solution using dictionaries | user5580aS | 0 | 1 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,256 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2798274/Python%3A-Easy-Sliding-Window-Using-Set | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
left = 0
right = 0
_min = math.inf
s = set()
while right < len(cards):
if cards[right] in s:
while left < right and cards[right] in s:
_min = min(right - left + 1, _min)
s.remove(cards[left])
left += 1
s.add(cards[right])
right += 1
return -1 if _min == math.inf else _min | minimum-consecutive-cards-to-pick-up | Python: Easy Sliding Window Using Set | supreethshaker | 0 | 2 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,257 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2780096/Python-easy-solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
seen = {}
length = inf
n = len(cards)
for i in range(n):
if cards[i] in seen:
length = min(length, i-seen.get(cards[i])+1)
seen[cards[i]] = i
return length if length!=inf else -1 | minimum-consecutive-cards-to-pick-up | Python easy solution | dhanu084 | 0 | 3 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,258 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2645345/python-simple-sliding-window-solution-O(n) | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
minimal = float('inf')
count = {}
sW = 0
for eW in range(len(cards)):
count[cards[eW]] = 1 + count.get(cards[eW], 0)
# print(cards[sW:eW+1])
while count[cards[eW]] > 1:
count[cards[sW]] -= 1
minimal = eW - sW + 1 if minimal > eW - sW +1 else minimal
sW += 1
return minimal if minimal != float('inf') else -1 | minimum-consecutive-cards-to-pick-up | python simple sliding window solution O(n) | bilal12542 | 0 | 4 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,259 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2639267/Easy-solution-in-O(n)-or-Python-or-HashMap | class Solution(object):
def minimumCardPickup(self, cards):
"""
:type cards: List[int]
:rtype: int
"""
windowStart=0
minimum=float("inf")
hashMap = {}
for i in range(len(cards)):
if cards[i] not in hashMap:
hashMap[cards[i]]=i
else:
minimum = abs(min(minimum, i-hashMap[cards[i]]+1))
#of two same values are togather
if minimum == 2:
return minimum
hashMap[cards[i]]=i
return minimum if minimum != float("inf") else -1 | minimum-consecutive-cards-to-pick-up | Easy solution in O(n) | Python | HashMap | msherazedu | 0 | 9 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,260 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2614470/Python-one-pass-solution-or-O(n) | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
if len(cards) == len(set(cards)): #saves time
return -1
pos = {} # to store the indexs
res = float('inf')
for i in range(len(cards)):
if cards[i] in pos: #if the current value appears the first time add it to dictionary
res = min(res, (i- pos[cards[i]]) + 1) #take the minimum
pos[cards[i]] = i
else:
pos[cards[i]] = i
return res if res != inf else -1 | minimum-consecutive-cards-to-pick-up | Python one pass solution | O(n) | pandish | 0 | 12 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,261 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2433358/python-most-efficient(97-beats)-and-short-soln-using-hashmap-dictionary | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
d={}
ans=float('inf')
for i in range(len(cards)):
if cards[i] in d:
if i-d[cards[i]]+1 <ans:
ans=i-d[cards[i]]+1
d[cards[i]]=i
else:
d[cards[i]] =i
return ans if ans!=float('inf') else -1 | minimum-consecutive-cards-to-pick-up | python most efficient(97% beats) and short soln using hashmap dictionary | benon | 0 | 39 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,262 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2159133/Python-oror-Easy-Solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
seen = defaultdict(int)
min_ = inf
for i, c in enumerate(cards):
if c in seen: min_ = min( i - seen[c] + 1, min_)
seen[c] = i
if min_ != inf: return min_
else: return - 1 | minimum-consecutive-cards-to-pick-up | Python || Easy Solution | morpheusdurden | 0 | 79 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,263 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2127780/Python-3-Interview-Answer-or-Clean-and-Easy-Readability | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
seen, left, result = {}, 0, math.inf
for right in range(len(cards)):
if cards[right] in seen:
result = min(result, right - seen[cards[right]] + 1)
left += 1
seen[cards[right]] = right
return result if result != math.inf else -1 | minimum-consecutive-cards-to-pick-up | [Python 3] Interview Answer | Clean & Easy Readability | Cut | 0 | 38 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,264 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2127780/Python-3-Interview-Answer-or-Clean-and-Easy-Readability | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
seen, left, result = {}, 0, math.inf
for i, num in enumerate(cards):
if num in seen:
result = min(result, i - seen[num] + 1)
left += 1
seen[num] = i
return result if result != math.inf else -1 | minimum-consecutive-cards-to-pick-up | [Python 3] Interview Answer | Clean & Easy Readability | Cut | 0 | 38 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,265 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2015757/Python-3-Easy-Index-Hash-Map-Solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
indices = defaultdict(list)
for i, card in enumerate(cards):
indices[card].append(i)
ans = inf
for idx, inds in indices.items():
for i in range(1, len(inds)):
ans = min(ans, inds[i]-inds[i-1]+1)
if ans == inf:
return -1
return ans | minimum-consecutive-cards-to-pick-up | [Python 3] Easy Index Hash Map Solution | hari19041 | 0 | 30 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,266 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2009434/python-3-oror-hash-map-solution-oror-O(n)O(n) | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
cardIndices = {}
res = len(cards) + 1
for i, card in enumerate(cards):
if card in cardIndices:
res = min(res, i - cardIndices[card] + 1)
cardIndices[card] = i
return res if res != len(cards) + 1 else -1 | minimum-consecutive-cards-to-pick-up | python 3 || hash map solution || O(n)/O(n) | dereky4 | 0 | 23 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,267 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/2002089/Python-or-Track-last-occurrence-or-O(n) | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
mapping = {}
shortest = -1
for i, card in enumerate(cards):
if card in mapping:
if shortest == -1:
shortest = i-mapping[card] + 1
else:
shortest = min(shortest, i - mapping[card] + 1)
mapping[card] = i
return shortest | minimum-consecutive-cards-to-pick-up | Python | Track last occurrence | O(n) | shamydin | 0 | 25 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,268 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1999088/Python3-Sliding-Window-O(n)-Solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
#sliding window
dicts = {}
start = 0
res = sys.maxsize
while start < len(cards):
target = cards[start]
if target not in dicts:
dicts[target] = start
else:
res = min(res, start - dicts[target] + 1)
dicts[target] = start
start += 1
return res if res != sys.maxsize else -1 | minimum-consecutive-cards-to-pick-up | Python3 Sliding Window O(n) Solution | xxHRxx | 0 | 26 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,269 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996968/Easy-Python-Solution-oror-O(n) | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
d=dict()
l=[]
for i in range(len(cards)):
""" If cards[i] not found in d means it is coming first time """
if d.get(cards[i])==None:
d[cards[i]]=i
""" If found means 2 or third occurence subtract index of previous one and this one and add 1 to it as this is inclusive range """
elif d.get(cards[i])!=None:
l.append(i-d[cards[i]]+1)
""" Update d[cards[i]] so that if more numbers will come they have updated value to calculate """
d[cards[i]]=i
if len(l)>0:
return min(l)
return -1 | minimum-consecutive-cards-to-pick-up | Easy Python Solution || O(n) | a_dityamishra | 0 | 27 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,270 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996686/Python-Track-Last-Index-using-Hashset | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
last_index = defaultdict(int) # store last index of a card
res = math.inf
for i,x in enumerate(cards):
# if a pair is found, calculate the number of cards using last_index dict
if x in last_index:
res = min(res, i - last_index[x]+1)
last_index[x] = i
return -1 if res == math.inf else res | minimum-consecutive-cards-to-pick-up | Python - Track Last Index using Hashset | constantine786 | 0 | 14 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,271 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996527/Python-O(N)-Time-oror-Easy-to-Understand-oror-Straight-forward-solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
occur = {}
for i, val in enumerate(cards):
if(val in occur):
occur[val].append(i)
else:
occur[val] = [i]
print(occur)
dist = float("inf")
for key, val_list in occur.items():
if len(val_list) == 1: continue
else:
for i in range(len(val_list)-1):
dist = min(dist, val_list[i+1] - val_list[i] + 1)
return dist if dist != float("inf") else -1 | minimum-consecutive-cards-to-pick-up | Python O(N) Time || Easy to Understand || Straight forward solution | shiva1gandluri | 0 | 21 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,272 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996255/Python-Solution | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
d = {}
ans = -1
for i in range(len(cards)):
if cards[i] in d:
if ans != -1:
ans = min(i - d[cards[i]] + 1, ans)
else:
ans = i - d[cards[i]] + 1
d[cards[i]] = i
return ans | minimum-consecutive-cards-to-pick-up | Python Solution | user6397p | 0 | 23 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,273 |
https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996207/Python-or-Easy-to-Understand | class Solution:
def minimumCardPickup(self, cards: List[int]) -> int:
dic = defaultdict(int)
min_num = float('inf')
for i, num in enumerate(cards):
if num not in dic:
dic[num] = i
else:
min_num = min(min_num, i - dic[num] + 1)
dic[num] = i
if min_num == float('inf'):
return -1
else:
return min_num | minimum-consecutive-cards-to-pick-up | Python | Easy to Understand | Mikey98 | 0 | 37 | minimum consecutive cards to pick up | 2,260 | 0.517 | Medium | 31,274 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996643/Python-Simple-Count-all-combinations | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
n = len(nums)
sub_arrays = set()
# generate all combinations of subarray
for start in range(n):
cnt = 0
temp = ''
for i in range(start, n):
if nums[i]%p == 0:
cnt+=1
temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format
if cnt>k: # check for termination
break
sub_arrays.add(temp)
return len(sub_arrays) | k-divisible-elements-subarrays | ✅ Python - Simple Count all combinations | constantine786 | 20 | 885 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,275 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996394/Python3-Backtracking | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
def dfs(idx, k, path):
nonlocal res, visited
if idx == len(nums):
visited.add(tuple(path[:]))
return
if nums[idx] % p == 0 and k > 0:
path.append(nums[idx])
if tuple(path) not in visited:
visited.add(tuple(path))
res += 1
dfs(idx + 1, k - 1, path)
elif nums[idx] % p != 0:
path.append(nums[idx])
if tuple(path) not in visited:
visited.add(tuple(path))
res += 1
dfs(idx + 1, k, path)
res = 0
visited = set()
for i in range(len(nums)):
dfs(i, k, [])
return res | k-divisible-elements-subarrays | [Python3] Backtracking | alanlihy1805 | 2 | 74 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,276 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2732292/Python3-Rolling-Hash-Simple-Solution | class Solution:
POW = 397
MODULO = 100000000069
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
arr = list(map(lambda x: 1 if x % p == 0 else 0, nums))
ans_set = set[int]()
for i in range(len(arr)):
cnt_one = 0
hash1 = 0
for j in range(i, len(arr)):
hash1 = (hash1 * Solution.POW + nums[j] + (j + 1 - i)) % Solution.MODULO
if arr[j] == 1:
cnt_one += 1
if cnt_one <= k:
ans_set.add(hash1)
else:
break
return len(ans_set) | k-divisible-elements-subarrays | [Python3] Rolling Hash Simple Solution | huangweijing | 1 | 94 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,277 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2002206/Easily-implemented-using-Trie | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
trie = {}
cnt = 0
for i in range(len(nums)):
count = 0
divis = 0 #contain count of element in array divisible by p
d = trie
for j in range(i,len(nums)):
if nums[j] % p == 0:
divis += 1
if divis > k:
break
if nums[j] not in d:
d[nums[j]] = {}
count += 1
d = d[nums[j]]
cnt += count #count contain all subarrays that can be made from nums[i:j]
return cnt``` | k-divisible-elements-subarrays | Easily implemented using Trie | rohit_vishwas_ | 1 | 118 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,278 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2833480/Python-(Simple-Maths) | class Solution:
def countDistinct(self, nums, k, p):
n, seen = len(nums), set()
for i in range(n):
s, count = "", 0
for j in range(i,n):
if nums[j]%p == 0:
count += 1
if count > k:
break
s += str(nums[j]) + "#"
seen.add(s)
return len(seen) | k-divisible-elements-subarrays | Python (Simple Maths) | rnotappl | 0 | 2 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,279 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2780155/Python-soltion-using-set | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
n = len(nums)
res = 0
seen = set()
for i in range(n):
divisible = 0
for j in range(i,n):
divisible+=1 if nums[j]%p == 0 else 0
if divisible > k:
break
subarray = tuple(nums[i:j+1])
if subarray in seen:
continue
seen.add(subarray)
res+=1
return res | k-divisible-elements-subarrays | Python soltion using set | dhanu084 | 0 | 7 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,280 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2159136/Python-oror-Straight-Forward | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
n = len(nums)
seen = set()
for i in range(n):
for j in range(i,n):
count = 0
for l in range(i,j+1):
if nums[l]%p == 0: count += 1
if count <= k: seen.add(tuple(nums[i:j+1]))
return len(seen) | k-divisible-elements-subarrays | Python || Straight Forward | morpheusdurden | 0 | 101 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,281 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/2025972/Python-Simple-DFS | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
ans = []
past = set()
def dfs(path, ind):
tmp = 0
for s in path:
if int(s)%p == 0:
tmp += 1
if tmp <= k and tuple(path) not in past:
ans.append(path)
past.add(tuple(path))
if ind+1 < len(nums):
dfs(path + [nums[ind+1]], ind+1)
for i in range(len(nums)):
dfs([nums[i]], i)
return len(ans) | k-divisible-elements-subarrays | Python Simple DFS | yseeker | 0 | 115 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,282 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1999168/Python3-Hashmap-%2B-prefix-sum-O(n2)-Solution | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
flag = []
for element in nums:
if element % p == 0: flag.append(1)
else: flag.append(0)
added = set()
prefix_sum = [0]
start = 0
for element in flag:
start += element
prefix_sum.append(start)
for i in range(1, len(nums)+1):
for j in range(i, len(nums)+1):
target = prefix_sum[j] - prefix_sum[i-1]
arr = tuple(nums[i-1:j])
if target <= k and tuple(arr) not in added:
added.add(tuple(arr))
return len(added) | k-divisible-elements-subarrays | Python3 Hashmap + prefix sum O(n^2) Solution | xxHRxx | 0 | 33 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,283 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1998963/Python-Solution | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
from collections import defaultdict
arr=defaultdict(int)
answer=0
count=0
for i in range(len(nums)):
count=0
res=''
for j in range(i,len(nums)):
if nums[j]%p!=0:
res+=(str(nums[j])+'*')
if arr[res]==0:
answer+=1
arr[res]=1
else:
count+=1
res += (str(nums[j])+'*')
if count<=k:
if arr[res] == 0:
answer += 1
arr[res] = 1
else:
break
return answer | k-divisible-elements-subarrays | Python Solution | g0urav | 0 | 32 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,284 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996249/Python-or-Easy-to-Understand | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
used = set()
n = len(nums)
count = 0
for i in range(n):
divisible_num = 0
s = []
for j in range(i, n):
if nums[j] % p == 0:
divisible_num += 1
if divisible_num <= k:
s.append(nums[j])
if tuple(s) not in used:
used.add(tuple(s))
count += 1
else:
continue
elif divisible_num > k:
break
return count | k-divisible-elements-subarrays | Python | Easy to Understand | Mikey98 | 0 | 59 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,285 |
https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996594/Python-O(N2)-Time-oror-Hashset | class Solution:
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
result = set()
N = len(nums)
K = k
for i in range(N):
k = K
for j in range(i,N):
if k>0:
if nums[j] % p == 0:
k -= 1
s = str(nums[i:j+1])
if s not in result:
result.add(s)
elif nums[j] % p != 0:
s = str(nums[i:j+1])
if s not in result:
result.add(s)
else:
break
return len(result) | k-divisible-elements-subarrays | Python O(N^2) Time || Hashset | shiva1gandluri | -1 | 117 | k divisible elements subarrays | 2,261 | 0.476 | Medium | 31,286 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996203/DP | class Solution:
def appealSum(self, s: str) -> int:
res, cur, prev = 0, 0, defaultdict(lambda: -1)
for i, ch in enumerate(s):
cur += i - prev[ch]
prev[ch] = i
res += cur
return res | total-appeal-of-a-string | DP | votrubac | 245 | 10,100 | total appeal of a string | 2,262 | 0.583 | Hard | 31,287 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996300/Python3-or-O(N)-O(1)-or-detail-for-beginners | class Solution:
def appealSum(self, s: str) -> int:
lastSeenMap = {s[0]: 0}
prev, curr, res = 1, 0, 1
for i in range(1, len(s)):
if s[i] in lastSeenMap:
curr = prev + (i - lastSeenMap[s[i]])
else:
curr = prev + (i + 1)
res += curr
prev = curr
lastSeenMap[s[i]] = i
return res | total-appeal-of-a-string | Python3 | O(N) / O(1) | detail for beginners | hanjo108 | 93 | 3,400 | total appeal of a string | 2,262 | 0.583 | Hard | 31,288 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1999226/Combinatorics | class Solution:
def appealSum(self, s: str) -> int:
res, n, prev = 0, len(s), defaultdict(lambda: -1)
for i, ch in enumerate(s):
res += (i - prev[ch]) * (n - i)
prev[ch] = i
return res | total-appeal-of-a-string | Combinatorics | votrubac | 62 | 3,400 | total appeal of a string | 2,262 | 0.583 | Hard | 31,289 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996270/Python-Hashmap-O(N)-Solution-with-Detailed-Explanations-Clean-and-Concise | class Solution:
def appealSum(self, s: str) -> int:
n = len(s)
dp = [0] * n
dp[0] = 1
hashmap = {s[0]: 0}
for i in range(1, n):
if s[i] not in hashmap:
dp[i] = dp[i - 1] + (i + 1)
hashmap[s[i]] = i
else:
dp[i] = dp[i - 1] + (i - hashmap[s[i]])
hashmap[s[i]] = i
return sum(dp) | total-appeal-of-a-string | [Python] Hashmap O(N) Solution with Detailed Explanations, Clean & Concise | xil899 | 6 | 294 | total appeal of a string | 2,262 | 0.583 | Hard | 31,290 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996270/Python-Hashmap-O(N)-Solution-with-Detailed-Explanations-Clean-and-Concise | class Solution:
def appealSum(self, s: str) -> int:
n = len(s)
curSum, cumSum = 1, 1
hashmap = {s[0]: 0}
for i in range(1, n):
if s[i] not in hashmap:
curSum += i + 1
else:
curSum += i - hashmap[s[i]]
cumSum += curSum
hashmap[s[i]] = i
return cumSum | total-appeal-of-a-string | [Python] Hashmap O(N) Solution with Detailed Explanations, Clean & Concise | xil899 | 6 | 294 | total appeal of a string | 2,262 | 0.583 | Hard | 31,291 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996330/Python-or-Hashtable-One-Pass-O(n)-with-Illustration | class Solution:
def appealSum(self, s: str) -> int:
prev = {}
total, curr = 0, 0
for i, c in enumerate(s):
if c in prev:
curr += i + 1 - (prev[c])
prev[c] = (i + 1)
else:
prev[c] = (i+1)
curr += i + 1
total += curr
return total | total-appeal-of-a-string | Python | Hashtable One Pass O(n) with Illustration | owen1605 | 3 | 242 | total appeal of a string | 2,262 | 0.583 | Hard | 31,292 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/2098355/Python-Solution-with-Explanation | class Solution:
def appealSum(self, s: str) -> int:
pre = [-1] * 26
ans = 0
n = len(s)
for i in range(n):
ans += (i - pre[ord(s[i]) - 97]) * (n - i)
pre[ord(s[i]) - 97] = i
return ans | total-appeal-of-a-string | Python Solution with Explanation | k3232908 | 1 | 191 | total appeal of a string | 2,262 | 0.583 | Hard | 31,293 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996754/python-3-oror-dynamic-programming-oror-O(n)O(1) | class Solution:
def appealSum(self, s: str) -> int:
last = collections.defaultdict(lambda: 0)
curAppeal = totalAppeal = 0
for i, c in enumerate(s):
curAppeal += i + 1 - last[c]
last[c] = i + 1
totalAppeal += curAppeal
return totalAppeal | total-appeal-of-a-string | python 3 || dynamic programming || O(n)/O(1) | dereky4 | 1 | 61 | total appeal of a string | 2,262 | 0.583 | Hard | 31,294 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/2774285/7-Line-Python-DP-O(N)-Time-O(1)-Space | class Solution:
def appealSum(self, s: str) -> int:
pre, ans, last_i = 0, 0, [-1] * 26
for i in range(len(s)):
order = ord(s[i]) - ord('a')
pre += i - last_i[order]
ans += pre
last_i[order] = i
return ans | total-appeal-of-a-string | 7 Line Python / DP / O(N) Time / O(1) Space | GregHuang | 0 | 4 | total appeal of a string | 2,262 | 0.583 | Hard | 31,295 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/2564449/Python-simple-one-pass | class Solution:
def appealSum(self, s: str) -> int:
n = len(s)
prev = [-1] * n
index = {}
for i, c in enumerate(s):
if c in index:
prev[i] = index[c]
index[c] = i
res = 0
for i, c in enumerate(s):
res += (n - i) * (i - prev[i])
return res | total-appeal-of-a-string | Python simple one pass | shubhamnishad25 | 0 | 115 | total appeal of a string | 2,262 | 0.583 | Hard | 31,296 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/2043129/DP-Python | class Solution:
def appealSum(self, s: str) -> int:
# dp
# f(i): appeal for all substr end at i
# f(i) = f(i-1) + (i - last_index[s[i]])
last_index = collections.defaultdict(lambda: -1)
last_appeal = total_appeal = 0
for i, char in enumerate(s):
last_appeal += i - last_index[char]
total_appeal += last_appeal
last_index[char] = i
return total_appeal | total-appeal-of-a-string | DP - Python | bz2342 | 0 | 85 | total appeal of a string | 2,262 | 0.583 | Hard | 31,297 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/2003801/Python-Solution | class Solution:
def appealSum(self, s: str) -> int:
from collections import defaultdict
arr=defaultdict(int)
result=0
for i in range(len(s)):
arr[s[i]]=i+1
result+=(sum(arr.values()))
return result | total-appeal-of-a-string | Python Solution | g0urav | 0 | 62 | total appeal of a string | 2,262 | 0.583 | Hard | 31,298 |
https://leetcode.com/problems/total-appeal-of-a-string/discuss/1998363/Python-3Hint-solution-O(n*26) | class Solution:
def appealSum(self, s: str) -> int:
n = len(s)
vis = {}
ans = 0
for i in range(n+1):
for k in vis:
ans += 1 + vis[k]
if i < n:
vis[s[i]] = i
return ans | total-appeal-of-a-string | [Python 3]Hint solution O(n*26) | chestnut890123 | 0 | 42 | total appeal of a string | 2,262 | 0.583 | Hard | 31,299 |
Subsets and Splits