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/arithmetic-subarrays/discuss/1406723/Python3-solution-clean-code
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def arithmetic(arr): # function to check if the sequence is arithmetic for i in range(len(arr)): if i <= len(arr)-2 and i >= 1: if arr[i+1] - arr[i] != arr[i] - arr[i-1]: return False return True ans = [] for i in range(len(l)): s = nums[l[i]:r[i]+1].copy() # getting the interval made by l[i] and r[i] => s = [l[i], r[i]] s.sort() ans.append(arithmetic(s)) return ans
arithmetic-subarrays
Python3 solution clean code
FlorinnC1
0
52
arithmetic subarrays
1,630
0.8
Medium
23,700
https://leetcode.com/problems/arithmetic-subarrays/discuss/1370794/python3-solution-using-formula
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: visited = [] for start, end in zip(l, r): seq = nums[start:end+1] # using formula for sum of arithmetic sequence form = (max(seq) + min(seq)) * len(seq) // 2 if sum(seq) != form: visited.append(False) else: seq.sort() temp = seq[1] - seq[0] for i in range(1,len(seq)): if seq[i] - seq[i-1] !=temp: visited.append(False) break else: visited.append(True) return visited
arithmetic-subarrays
python3 solution using formula
G0udini
0
53
arithmetic subarrays
1,630
0.8
Medium
23,701
https://leetcode.com/problems/arithmetic-subarrays/discuss/1174539/python-3-solution
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: temp=[] for i in range(len(l)): p=nums[l[i]:r[i]+1] p.sort() flag=True for i in range(2,len(p)): if p[i-1]-p[i-2]!=p[i]-p[i-1]: flag=False temp.append(flag) return(temp)
arithmetic-subarrays
python 3 solution
janhaviborde23
0
93
arithmetic subarrays
1,630
0.8
Medium
23,702
https://leetcode.com/problems/arithmetic-subarrays/discuss/1110072/Python-or-Simple-Clean-Solution
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def check(arr): diff=arr[1]-arr[0] for i in range(len(arr)-1): if arr[i+1]-arr[i]!=diff: return False return True res=[] for l,r in zip(l,r): if r-l==1: res.append(True) else: res.append(check(sorted(nums[l:r+1]))) return res
arithmetic-subarrays
Python | Simple Clean Solution
rajatrai1206
0
70
arithmetic subarrays
1,630
0.8
Medium
23,703
https://leetcode.com/problems/arithmetic-subarrays/discuss/948654/Intuitive-approach
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def is_a_arithmetic_subarray(a, b): sorted_nums = sorted(nums[a:b+1]) p = sorted_nums[1] - sorted_nums[0] for i in range(2, len(sorted_nums)): if sorted_nums[i] - sorted_nums[i-1] != p: return (False, -1) return (True, p) ans = [] for a, b in zip(l, r): if b == a: ans.append(True) continue is_art, p = is_a_arithmetic_subarray(a, b) ans.append(is_art) # print(range_cache) return ans
arithmetic-subarrays
Intuitive approach
puremonkey2001
0
41
arithmetic subarrays
1,630
0.8
Medium
23,704
https://leetcode.com/problems/arithmetic-subarrays/discuss/909086/Python3-5-line-sorting
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ans = [] for ll, rr in zip(l, r): seq = sorted(nums[ll:rr+1]) ans.append(len(set(seq[i] - seq[i-1] for i in range(1, len(seq)))) == 1) return ans
arithmetic-subarrays
[Python3] 5-line sorting
ye15
0
150
arithmetic subarrays
1,630
0.8
Medium
23,705
https://leetcode.com/problems/arithmetic-subarrays/discuss/909086/Python3-5-line-sorting
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: def fn(seq): """Return True if seq is an arithmetic subarray.""" mn, mx = min(seq), max(seq) if mn == mx: return True # edge case step = (mx - mn) / (len(seq) - 1) seq = [(x - mn)/step for x in seq] # standardize seq return len(set(seq)) == len(seq) and all(x.is_integer() for x in seq) return [fn(nums[ll:rr+1]) for ll, rr in zip(l, r)]
arithmetic-subarrays
[Python3] 5-line sorting
ye15
0
150
arithmetic subarrays
1,630
0.8
Medium
23,706
https://leetcode.com/problems/arithmetic-subarrays/discuss/1393675/Python3-Easy-sort-and-set-solutions-beat-90%2B
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ''' Time: O(L*nlogn * n) ''' def check(arr): n = len(arr) if n < 2: return False d = arr[1] - arr[0] for i in range(2, n): if arr[i]-arr[i-1] != d: return False return True ans = [] n = len(l) for idx in range(n): i, j = l[idx], r[idx] sub = nums[i:j+1] ans.append(check(sorted(sub))) return ans
arithmetic-subarrays
[Python3] Easy sort and set solutions beat 90%+
nightybear
-1
52
arithmetic subarrays
1,630
0.8
Medium
23,707
https://leetcode.com/problems/arithmetic-subarrays/discuss/1393675/Python3-Easy-sort-and-set-solutions-beat-90%2B
class Solution: def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]: ''' Time: O(L*n) ''' def check(arr): min_val, max_val, set_val = min(arr), max(arr), set(arr) if len(arr) != len(set_val): return len(set_val) == 1 if (max_val-min_val) % (len(arr)-1) != 0: return False steps = (max_val-min_val) // (len(arr)-1) for i in range(min_val, max_val+1, steps): if i not in set_val: return False return True ans = [] n = len(l) for idx in range(n): i, j = l[idx], r[idx] sub = nums[i:j+1] ans.append(check(sub)) return ans
arithmetic-subarrays
[Python3] Easy sort and set solutions beat 90%+
nightybear
-1
52
arithmetic subarrays
1,630
0.8
Medium
23,708
https://leetcode.com/problems/arithmetic-subarrays/discuss/1284752/Python-Easy-Solution-Faster-Than-99.02
class Solution: def checker(self,nums): i = 2 n = len(nums) diff = nums[1] - nums[0] while i < n: if nums[i] - nums[i-1] != diff: return False i += 1 return True def checkArithmeticSubarrays(self, nums: List[int], left: List[int], right: List[int]) -> List[bool]: m, i, ans = len(left), 0, [] while i < m: l, r = left[i], right[i] sub = nums[l:r+1] sub.sort() ans.append(self.checker(sub)) i += 1 return ans
arithmetic-subarrays
Python Easy Solution Faster Than 99.02%
paramvs8
-1
55
arithmetic subarrays
1,630
0.8
Medium
23,709
https://leetcode.com/problems/path-with-minimum-effort/discuss/909094/Python3-bfs-and-Dijkstra
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: m, n = len(heights), len(heights[0]) queue = {(0, 0): 0} # (0, 0) maximum height so far seen = {(0, 0): 0} # (i, j) -> heights ans = inf while queue: newq = {} # new dictionary for (i, j), h in queue.items(): if i == m-1 and j == n-1: ans = min(ans, h) for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n: hh = max(h, abs(heights[i][j] - heights[ii][jj])) if hh < seen.get((ii, jj), inf): seen[(ii, jj)] = hh newq[(ii, jj)] = hh queue = newq return ans
path-with-minimum-effort
[Python3] bfs & Dijkstra
ye15
2
219
path with minimum effort
1,631
0.554
Medium
23,710
https://leetcode.com/problems/path-with-minimum-effort/discuss/909094/Python3-bfs-and-Dijkstra
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: m, n = len(heights), len(heights[0]) # dimensions seen = {(0, 0): 0} pq = [(0, 0, 0)] while pq: h, i, j = heappop(pq) if i == m-1 and j == n-1: return h for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n: hh = max(h, abs(heights[ii][jj] - heights[i][j])) if (ii, jj) not in seen or hh < seen[ii, jj]: heappush(pq, (hh, ii, jj)) seen[ii, jj] = hh
path-with-minimum-effort
[Python3] bfs & Dijkstra
ye15
2
219
path with minimum effort
1,631
0.554
Medium
23,711
https://leetcode.com/problems/path-with-minimum-effort/discuss/909094/Python3-bfs-and-Dijkstra
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: m, n = len(heights), len(heights[0]) def fn(x): """Return True if given effort is enough.""" stack = [(0, 0)] # i|j|h starting from top-left seen = set() while stack: i, j = stack.pop() seen.add((i, j)) if i == m-1 and j == n-1: return True # reaching bottom-right for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen and abs(heights[ii][jj] - heights[i][j]) <= x: stack.append((ii, jj)) return False lo, hi = 0, 10**6 while lo < hi: mid = lo + hi >> 1 if not fn(mid): lo = mid + 1 else: hi = mid return lo
path-with-minimum-effort
[Python3] bfs & Dijkstra
ye15
2
219
path with minimum effort
1,631
0.554
Medium
23,712
https://leetcode.com/problems/path-with-minimum-effort/discuss/1989967/Python-3-easy-Solution-oror-Faster-than-98.5-oror-Min-Heap-oror-O(mn.log(mn))
class Solution: def minimumEffortPath(self, grid: List[List[int]]) -> int: # Base case if len(grid)==1 and len(grid[0])==1: return 0 row , col = len(grid) , len(grid[0]) visited = set() # set : store indices (i,j) which we have visited already before reaching destination hp = [] # Min heap visited.add((0,0)) i,j = 0,0 # statrt point ans = 0 # while current not equal to destination keep traverse the grid while (i,j) != (row-1,col-1): # down if i+1<row and (i+1,j) not in visited: d = abs(grid[i][j]-grid[i+1][j]) heapq.heappush(hp,[d,i+1,j]) # up if i-1>=0 and (i-1,j) not in visited: d = abs(grid[i][j]-grid[i-1][j]) heapq.heappush(hp,[d,i-1,j]) # right if j+1<col and (i,j+1) not in visited: d = abs(grid[i][j+1]-grid[i][j]) heapq.heappush(hp,[d,i,j+1]) # left if j-1>=0 and (i,j-1) not in visited: d = abs(grid[i][j-1]-grid[i][j]) heapq.heappush(hp,[d,i,j-1]) # top of heap tells us that what is minimum path effort we should take next d,p,q = heapq.heappop(hp) ans = max(ans,d) visited.add((p,q)) # change current point i,j = p,q return ans
path-with-minimum-effort
Python 3 easy Solution || Faster than 98.5% || Min-Heap || O(mn.log(mn))
Laxman_Singh_Saini
1
63
path with minimum effort
1,631
0.554
Medium
23,713
https://leetcode.com/problems/path-with-minimum-effort/discuss/1693676/Python-two-methods%3A-union-find-and-DFS
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: m,n = len(heights),len(heights[0]) parent = list(range(m*n)) rank = [1 for _ in range(m*n)] def find(node): if parent[node]!=node: parent[node] = find(parent[node]) return parent[node] def union(node1, node2): p1,p2 = find(node1),find(node2) if p1==p2: return if rank[p1]>rank[p2]: p1,p2 = p2,p1 parent[p1] = p2 rank[p2] += rank[p1] edges = [] for i in range(m): for j in range(n): if i>0: edges.append((abs(heights[i][j]-heights[i-1][j]),(i-1)*n+j,i*n+j)) if j>0: edges.append((abs(heights[i][j]-heights[i][j-1]),i*n+j-1,i*n+j)) edges.sort() for t in edges: union(t[1],t[2]) if find(0)==find(m*n-1): return t[0] return 0
path-with-minimum-effort
Python two methods: union find & DFS
1579901970cg
1
253
path with minimum effort
1,631
0.554
Medium
23,714
https://leetcode.com/problems/path-with-minimum-effort/discuss/1693676/Python-two-methods%3A-union-find-and-DFS
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: lo,hi = 0,10**6-1 m,n = len(heights),len(heights[0]) def dfs(i,j,pre,target): if (i,j) in visited: return False if i<0 or j<0 or i>m-1 or j>n-1 or abs(heights[i][j]-pre)>target: return False if i==m-1 and j==n-1: return True visited.add((i,j)) return dfs(i+1,j,heights[i][j],target) or\ dfs(i-1,j,heights[i][j],target) or\ dfs(i,j+1,heights[i][j],target) or\ dfs(i,j-1,heights[i][j],target) while lo<=hi: visited = set() mid = (lo+hi)//2 if dfs(0,0,heights[0][0],mid): hi = mid - 1 else: lo = mid + 1 return lo
path-with-minimum-effort
Python two methods: union find & DFS
1579901970cg
1
253
path with minimum effort
1,631
0.554
Medium
23,715
https://leetcode.com/problems/path-with-minimum-effort/discuss/2808461/Python-3-heap-(Priority-Queue)-simple-solution-with-comments
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: visited = set() h = [] drt = [[-1, 0], [0, -1], [1, 0], [0, 1]] max_diff = 0 rows_n = len(heights) cols_n = len(heights[0]) heappush(h, (max_diff, 0, 0)) # start from the top-left corner while True: el_dif, el_r, el_c = heappop(h) # find cell with the least abs. difference if (el_r, el_c) in visited: continue visited.add((el_r, el_c)) max_diff = max(max_diff, el_dif) # potential new maximum difference if (el_r, el_c) == (rows_n - 1, cols_n - 1): break for dr_r, dr_c in drt: if 0 <= el_r + dr_r < rows_n and \ 0 <= el_c + dr_c < cols_n: # add new cells and their absolute differences (with current cell) heappush(h, (abs(heights[el_r][el_c] - heights[el_r + dr_r][el_c + dr_c]), \ el_r + dr_r, el_c + dr_c)) return max_diff
path-with-minimum-effort
Python 3 - heap (Priority Queue) - simple solution - with comments
noob_in_prog
0
4
path with minimum effort
1,631
0.554
Medium
23,716
https://leetcode.com/problems/path-with-minimum-effort/discuss/2708595/Djikstra-simple-BFS
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: n,m = len(heights),len(heights[0]) directions = [(0,1),(1,0),(-1,0),(0,-1)] effort = [[float("inf")]*m for _ in range(n)] effort[0][0] = 0 minHeap = [] heappush(minHeap,(0,0,0)) while minHeap: cur_effort,x,y = heappop(minHeap) for dx,dy in directions: newx,newy = x+dx,y+dy if newx >= 0 and newy >= 0 and newx < n and newy < m: effort_needed = abs(heights[x][y] - heights[newx][newy]) max_effort = max(cur_effort,effort_needed) if max_effort < effort[newx][newy]: effort[newx][newy] = max_effort heappush(minHeap,(max_effort,newx,newy)) return effort[n-1][m-1]
path-with-minimum-effort
Djikstra simple BFS
shriyansnaik
0
8
path with minimum effort
1,631
0.554
Medium
23,717
https://leetcode.com/problems/path-with-minimum-effort/discuss/2653509/Dijkstra-and-binary-search
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: nrows, ncols = len(heights), len(heights[0]) dp = [] dp2 = [] for _ in range(nrows): dp.append([float("inf")] * ncols) dp2.append([float("inf")] * ncols) dp[0][0] = 0 has_changed = False for _ in range(nrows + ncols): for r in range(nrows): for c in range(ncols): dp2[r][c] = dp[r][c] for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): r2, c2 = r + dr, c + dc if 0 <= r2 < nrows and 0 <= c2 < ncols: effort = max(dp[r2][c2], abs(heights[r][c] - heights[r2][c2])) dp2[r][c] = min(dp2[r][c], effort) if dp2[r][c] != dp[r][c]: has_changed = True dp = dp2 if not has_changed: break return dp[-1][-1]
path-with-minimum-effort
Dijkstra and binary search
sticky_bits
0
6
path with minimum effort
1,631
0.554
Medium
23,718
https://leetcode.com/problems/path-with-minimum-effort/discuss/2653509/Dijkstra-and-binary-search
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: nrows, ncols = len(heights), len(heights[0]) def calcEffort(r, c, r2, c2): return abs(heights[r][c]-heights[r2][c2]) left, right = 0, 10000000 visited = set() def dfs(eff, r, c): visited.add((r, c)) if r == nrows - 1 and c == ncols - 1: return True for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)): r2, c2 = r + dr, c + dc if 0 <= r2 < nrows and 0 <= c2 < ncols and (r2, c2) not in visited: if calcEffort(r, c, r2, c2) <= eff: visited.add((r2, c2)) if dfs(eff, r2, c2): return True return False while left < right: mid = left + (right - left) // 2 visited = set() status = dfs(mid, 0, 0) if status: right = mid else: left = mid + 1 return left
path-with-minimum-effort
Dijkstra and binary search
sticky_bits
0
6
path with minimum effort
1,631
0.554
Medium
23,719
https://leetcode.com/problems/path-with-minimum-effort/discuss/2614714/Python3-or-Why-Am-I-getting-TLE-With-DFS-and-Binary-Search
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: m, n = len(heights), len(heights[0]) #To minimize effort, we can consider full range of possible effort values along any path! #Minimum would be 0 for route where all entries have same height and max would be maximum height #out of all cells! #I can do binary search on such search space and for current middle threshold value we are trying, #we need to check if it's possible to form a valid route from top-left to bottom-right while #upholding a constraint! #If so, update answer, but still try lower threshold values to update our answer! We are trying #to minimze the effort! #Otherwise, current threshold is too low and strict, so we have to binary search towards right #to try higher threshold values! four_directions = [[-1,0],[1,0], [0, -1], [0, 1]] #define a dfs helper! #parameters: threshold: current effort upperbound limit, r = current row, c = curent column, #visited = set of tuples keeping track of visited position cells! def dfs(threshold, r, c): nonlocal four_directions, visited #I will only recurse along path that is in-bounds and not already visited! #iterate through each of four neighboring cells! for dr, dc in four_directions: new_r, new_c = r + dr, c + dc #if in-bounds and not already visited! if(0<=new_r<m and 0<=new_c<n and (new_r, new_c) not in visited): #then, check if neighboring cell height abs diff to current cell meets threshold! #if it doesn't don't recurse along that path! if(abs(heights[r][c] - heights[new_r][new_c]) <= threshold): visited.add((r, c)) dfs(threshold, new_r, new_c) ans = None #Binary Search max_effort = float(-inf) for i in range(m): for j in range(n): max_effort = max(max_effort, heights[i][j]) L, H = 0, max_effort #initiate binary search as long as we have one threshold value left to consider! while L <= H: mid = (L + H) // 2 #for this current threshold, we need to initiate dfs to check if it's possible! #for every threshold, it's new dfs! we have to reset visited back to empty set! visited = set() #dfs will return boolean indicating whether threshold allows for at least one route! dfs(mid, 0, 0) #once recursion ends, check if last cell position is in visited! -> If so, route is possible! if((m-1, n-1) in visited): ans = mid #but we have to search to the left! H = mid - 1 continue else: L = mid + 1 continue #once binary search ends, we should have our answer! return ans
path-with-minimum-effort
Python3 | Why Am I getting TLE With DFS and Binary Search?
JOON1234
0
13
path with minimum effort
1,631
0.554
Medium
23,720
https://leetcode.com/problems/path-with-minimum-effort/discuss/2321793/Python3-or-BinarySearch-%2B-BFS
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: l,h=0,1e6+1 while l<h: mid=(l+h)//2 if self.isPossible(heights,mid): h=mid else: l=mid+1 return int(h) def isPossible(self,heights,limit): r,c=len(heights),len(heights[0]) vis=[[False for i in range(c)] for i in range(r)] q=deque() q.append([0,0]) fourDir=[[1,0],[0,1],[-1,0],[0,-1]] while q: currCell=q.popleft() x=currCell[0] y=currCell[1] if x==r-1 and y==c-1: return True for i in fourDir: if x+i[0]>=0 and y+i[1]>=0 and x+i[0]<r and y+i[1]<c and not vis[x+i[0]][y+i[1]]: if abs(heights[x+i[0]][y+i[1]]-heights[x][y])<=limit: q.append([x+i[0],y+i[1]]) vis[x+i[0]][y+i[1]]=True return False
path-with-minimum-effort
[Python3] | BinarySearch + BFS
swapnilsingh421
0
50
path with minimum effort
1,631
0.554
Medium
23,721
https://leetcode.com/problems/path-with-minimum-effort/discuss/1991399/ororPYTHON-SOL-oror-WELL-COMMENTED-oror-WELL-EXPLAINED-oror-DIJKSTRA'S-SOL-oror-EASY-TO-READ-oror
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: # implementing dijkstra's algorithm rows,cols = len(heights),len(heights[0]) # first mark every place unvisited vis = [[False for col in range(cols)] for row in range(rows)] # make minimum effort to reach every place = float('inf') min_effort = [[float('inf') for col in range(cols)] for row in range(rows)] # create a queue and add (0,0) to heap heap = [(0,0,0)] # heap is in the form of (effort,row,col) # set min_effort[0][0] = 0 min_effort[0][0] = 0 # now we run the loop while heap: # we pop out the node with min effort effort,row,col = heapq.heappop(heap) vis[row][col] = True # we try to update the adjacent nodes adjacent = ((row+1,col),(row-1,col),(row,col-1),(row,col+1)) for r,c in adjacent: # check if the node is inside the grid and is unvisited if 0<=r<rows and 0<=c<cols and vis[r][c] == False: newEffort = max(effort,abs(heights[r][c]-heights[row][col])) if newEffort < min_effort[r][c]: # update the node's effort min_effort[r][c] = newEffort # since we have modified the node add to heap heapq.heappush(heap,(newEffort,r,c)) return min_effort[-1][-1]
path-with-minimum-effort
||PYTHON SOL || WELL COMMENTED || WELL EXPLAINED || DIJKSTRA'S SOL || EASY TO READ ||
reaper_27
0
60
path with minimum effort
1,631
0.554
Medium
23,722
https://leetcode.com/problems/path-with-minimum-effort/discuss/1989830/Python3-Solution-with-using-dfs-and-binary-search
class Solution: def can_reach_dest(self, x, y, mid, lrow, lcol, heights,visited): if x == lrow - 1 and y == lcol - 1: # target cell return True visited[x][y] = True # dfs part for dx, dy in [[0,1], [1,0], [0,-1], [-1, 0]]: _x = x + dx _y = y + dy if 0 <= _x < lrow and 0 <= _y < lcol and not visited[_x][_y]: diff = abs(heights[_x][_y] - heights[x][y]) if diff <= mid: visited[_x][_y] = True if self.can_reach_dest(_x, _y, mid, lrow, lcol, heights, visited): return True def minimumEffortPath(self, heights: List[List[int]]) -> int: lrow = len(heights) lcol = len(heights[0]) left, right = 0, 10**6 while left < right: mid = (left + right) // 2 visited = [[False] * lcol for _ in range(lrow)] if self.can_reach_dest(0, 0, mid, lrow, lcol, heights, visited): right = mid else: left = mid + 1 return left
path-with-minimum-effort
[Python3] Solution with using dfs and binary search
maosipov11
0
30
path with minimum effort
1,631
0.554
Medium
23,723
https://leetcode.com/problems/path-with-minimum-effort/discuss/1988810/Python
class Solution: def minimumEffortPath(self, hs: List[List[int]]) -> int: rs, cs = len(hs), len(hs[0]) # format: (max abs difference, row, col) heap = [(0, 0, 0)] # dict stores the maximum abs difference seen up to (row, col) - default +inf seen = defaultdict(lambda: float('inf')) seen[(0, 0)] = 0 while heap: x, r, c = heappop(heap) # check for termination if r == rs - 1 and c == cs - 1: return x for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]: r2, c2 = r + dr, c + dc # If target cell r2, c2 is in bounds and the absolute difference to that cell x2 is smaller than our seen value, then visit if 0 <= r2 < rs and 0 <= c2 < cs and (x2 := abs(hs[r2][c2] - hs[r][c])) < seen[(r2, c2)]: seen[(r2, c2)] = x2 heappush(heap, (max(x, x2), r2, c2))
path-with-minimum-effort
Python
captainspongebob1
0
20
path with minimum effort
1,631
0.554
Medium
23,724
https://leetcode.com/problems/path-with-minimum-effort/discuss/1987784/Python3-solution
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: # return True if it's possible to go from (0,0) to (m-1, n-1) # using only edges of k or less cost. def is_there_a_path(k: int) -> bool: def dfs(x, y): if (x, y) == (m-1, n-1): return True visited.add((x,y)) for dx, dy in ((1,0), (-1,0), (0,1), (0,-1)): if 0 <= x+dx < m and 0 <= y+dy < n and\ (x+dx, y+dy) not in visited and\ abs(heights[x][y]-heights[x+dx][y+dy]) <= k: if dfs(x+dx, y+dy): return True return False visited = set() return dfs(0,0) m, n = len(heights), len(heights[0]) lo, hi = 0, 1_000_000-1 while lo < hi: mid = (lo+hi)//2 if is_there_a_path(mid): hi = mid else: lo = mid + 1 return lo
path-with-minimum-effort
Python3 solution
dalechoi
0
69
path with minimum effort
1,631
0.554
Medium
23,725
https://leetcode.com/problems/path-with-minimum-effort/discuss/1567897/Python3-Short-Dijkstra's
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: h = [(0, 0, 0, 0)] visited = set() while h: weight, x, y, max_diff = heappop(h) # weight is the transition weight, x y are the coordinates, and max_diff is the maximum diff on the path from 0 0 to the current node if (x, y) == (len(heights) - 1, len(heights[0]) - 1): # as per Dijkstra's, the first path to reach the end is optimal return max_diff visited.add((x, y)) # always optimal to avoid cycles for a, b in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: # neighbors if 0 <= a < len(heights) and 0 <= b < len(heights[0]) and (a, b) not in visited: heappush(h, (abs(heights[a][b] - heights[x][y]), a, b, max(abs(heights[a][b] - heights[x][y]), max_diff))) # transition. note how we change max_diff: it's the running max on the path
path-with-minimum-effort
Python3 Short Dijkstra's
danwuSBU
0
147
path with minimum effort
1,631
0.554
Medium
23,726
https://leetcode.com/problems/path-with-minimum-effort/discuss/1096787/Python-AC
class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: M, N = map(len, (heights, heights[0])) heap = [(0, 0, 0)] seen = set() result = 0 while heap: # Pop effort, i, j = heapq.heappop(heap) # Mark seen seen.add((i, j)) # Update minimum "effort" result = max(result, effort) # Success condition if i == M-1 and j == N-1: break # BFS for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]: if not (x >= 0 <= y): continue if x >= M or y >= N: continue if (x, y) in seen: continue effort = abs(heights[i][j] - heights[x][y]) heapq.heappush(heap, (effort, x, y)) return result
path-with-minimum-effort
Python AC
dev-josh
0
192
path with minimum effort
1,631
0.554
Medium
23,727
https://leetcode.com/problems/rank-transform-of-a-matrix/discuss/913790/Python3-UF
class Solution: def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: m, n = len(matrix), len(matrix[0]) # dimension # mapping from value to index mp = {} for i in range(m): for j in range(n): mp.setdefault(matrix[i][j], []).append((i, j)) def find(p): """Find root of p.""" if p != parent[p]: parent[p] = find(parent[p]) return parent[p] rank = [0]*(m+n) ans = [[0]*n for _ in range(m)] for k in sorted(mp): # from minimum to maximum parent = list(range(m+n)) for i, j in mp[k]: ii, jj = find(i), find(m+j) # find parent[ii] = jj # union rank[jj] = max(rank[ii], rank[jj]) # max rank seen = set() for i, j in mp[k]: ii = find(i) if ii not in seen: rank[ii] += 1 seen.add(ii) rank[i] = rank[m+j] = ans[i][j] = rank[ii] return ans
rank-transform-of-a-matrix
[Python3] UF
ye15
5
465
rank transform of a matrix
1,632
0.41
Hard
23,728
https://leetcode.com/problems/rank-transform-of-a-matrix/discuss/2476234/Python-Union-Find-%2B-Graph-%2B-Topological-Sort-%2B-BFS-Queue-heavily-commented
class Solution: def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: m = len(matrix) n = len(matrix[0]) def find_root(x: int, y: int): if parent[x][y] == (x, y): return (x, y) else: r = find_root(parent[x][y][0], parent[x][y][1]) parent[x][y] = r return r def union(x1, y1, x2, y2): root_a = find_root(x1, y1) root_b = find_root(x2, y2) parent[root_b[0]][root_b[1]] = root_a ######################################################## # *parent* records the parent of each point in matrix form # points with same value in the same row/column should have the same parent parent = [[(j, i) for i in range(n)] for j in range(m)] # sort each row, if there are points with same value, union them for i in range(m): value = [] for j in range(n): v = tuple([matrix[i][j], i, j]) value.append(v) value.sort() for k in range(n - 1): if value[k][0] == value[k + 1][0]: union(value[k][1], value[k][2], value[k + 1][1], value[k + 1][2]) # sort each column, if there are points with same value, union them for i in range(n): value = [] for j in range(m): v = tuple([matrix[j][i], j, i]) value.append(v) value.sort() for k in range(m - 1): if value[k][0] == value[k + 1][0]: union(value[k][1], value[k][2], value[k + 1][1], value[k + 1][2]) ######################################################## dic = {} # point index : point that it directs -> in_degree = {} # point index : number of incoming arrows <- # Ex. [20, -21, 14] # sort: -21 (0, 1) -> 14 (0, 2) -> 20 (0, 0) # dic = { (0, 0) : [], (0, 1) : [(0, 2)], (0, 2) : [(0, 0)] } # in_degree = { (0, 0) : 1, (0, 1) : 0, (0, 2) : 1 } # only select "root" points that parent[point] = point itself for i in range(m): for j in range(n): if parent[i][j] == (i, j): dic[(i, j)] = [] in_degree[(i, j)] = 0 # if there are points that parent[point] = its parent but not the "root" ancestor # make parent[point] = the "root" ancestor # Ex. before: parent[4][4] = (4, 4), parent[8][0] = (4, 4), parent[8][4] = (8, 0) # after: parent[4][4] = (4, 4), parent[8][0] = (4, 4), parent[8][4] = (4, 4) for i in range(m): for j in range(n): while parent[i][j] not in dic: parent[i][j] = parent[parent[i][j][0]][parent[i][j][1]] # continue to construct *dic* and *in_degree* # make connections in each row for i in range(m): row = [] for j in range(n): r = tuple([matrix[i][j], parent[i][j][0], parent[i][j][1]]) row.append(r) row.sort() for k in range(n - 1): if row[k][0] < row[k + 1][0]: if (row[k][1], row[k][2]) in dic and (row[k + 1][1], row[k + 1][2]) in dic: if (row[k + 1][1], row[k + 1][2]) not in dic[(row[k][1], row[k][2])]: dic[(row[k][1], row[k][2])].append((row[k + 1][1], row[k + 1][2])) in_degree[(row[k + 1][1], row[k + 1][2])] += 1 # and make connections in each column for i in range(n): col = [] for j in range(m): c = tuple([matrix[j][i], parent[j][i][0], parent[j][i][1]]) col.append(c) col.sort() for k in range(m - 1): if col[k][0] < col[k + 1][0]: if (col[k][1], col[k][2]) in dic and (col[k + 1][1], col[k + 1][2]) in dic: if (col[k + 1][1], col[k + 1][2]) not in dic[(col[k][1], col[k][2])]: dic[(col[k][1], col[k][2])].append((col[k + 1][1], col[k + 1][2])) in_degree[(col[k + 1][1], col[k + 1][2])] += 1 ####################################################################### # *distance* records the rank of the "root" points (just my naming habit) distance = {} # point index : rank for i in range(m): for j in range(n): if parent[i][j] == (i, j): distance[(i, j)] = 0 # first put "root" points that have 0 in_degree (meaning they are the smallest) in queue queue = [] for i in in_degree: if in_degree[i] == 0: queue.append(i) distance[i] = 1 head = 0 tail = len(queue) - 1 while head <= tail: h = queue[head] for p in dic[h]: in_degree[p] -= 1 if in_degree[p] == 0: queue.append(p) distance[p] = distance[h] + 1 head += 1 tail = len(queue) - 1 ####################################################################### # *rank* records the final result in matrix form rank = [[0 for i in range(n)] for j in range(m)] # now we already got the rank of those "root" points recorded in *distance* # let's put them in *rank*, also their descendants' for i in range(m): for j in range(n): rank[i][j] = distance[parent[i][j]] return rank
rank-transform-of-a-matrix
[Python] Union Find + Graph + Topological Sort + BFS Queue, heavily commented
bbshark
0
77
rank transform of a matrix
1,632
0.41
Hard
23,729
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/963292/Python-1-liner
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: return sorted(sorted(nums,reverse=1),key=nums.count)
sort-array-by-increasing-frequency
Python 1-liner
lokeshsenthilkumar
22
1,500
sort array by increasing frequency
1,636
0.687
Easy
23,730
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1446521/Using-Counter-95-speed
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: lst = sorted([(key, freq) for key, freq in Counter(nums).items()], key=lambda tpl: (tpl[1], -tpl[0])) ans = [] for key, freq in lst: ans += [key] * freq return ans
sort-array-by-increasing-frequency
Using Counter, 95% speed
EvgenySH
3
478
sort array by increasing frequency
1,636
0.687
Easy
23,731
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1870522/Python-Clean-and-Concise!-Multiple-Solutions!-One-Liners!
class Solution: def frequencySort(self, nums): c = Counter(nums) nums.sort(reverse=True) nums.sort(key=lambda x: c[x]) return nums
sort-array-by-increasing-frequency
Python - Clean and Concise! Multiple Solutions! One-Liners!
domthedeveloper
2
388
sort array by increasing frequency
1,636
0.687
Easy
23,732
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1870522/Python-Clean-and-Concise!-Multiple-Solutions!-One-Liners!
class Solution: def frequencySort(self, nums): return (lambda c : sorted(sorted(nums, reverse=True), key=lambda x: c[x]))(Counter(nums))
sort-array-by-increasing-frequency
Python - Clean and Concise! Multiple Solutions! One-Liners!
domthedeveloper
2
388
sort array by increasing frequency
1,636
0.687
Easy
23,733
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1870522/Python-Clean-and-Concise!-Multiple-Solutions!-One-Liners!
class Solution: def frequencySort(self, nums): c = Counter(nums) nums.sort(key=lambda x: (c[x], -x)) return nums
sort-array-by-increasing-frequency
Python - Clean and Concise! Multiple Solutions! One-Liners!
domthedeveloper
2
388
sort array by increasing frequency
1,636
0.687
Easy
23,734
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1870522/Python-Clean-and-Concise!-Multiple-Solutions!-One-Liners!
class Solution: def frequencySort(self, nums): return (lambda c : sorted(nums, key=lambda x: (c[x], -x)))(Counter(nums))
sort-array-by-increasing-frequency
Python - Clean and Concise! Multiple Solutions! One-Liners!
domthedeveloper
2
388
sort array by increasing frequency
1,636
0.687
Easy
23,735
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1851859/simple-python-dictionary
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: d = defaultdict(int) for i in nums: d[i] += 1 output = [] for i in sorted(d.items(), key=lambda kv: (kv[1],-kv[0])): output.extend([i[0]]*i[1]) return output
sort-array-by-increasing-frequency
simple python dictionary
gasohel336
2
281
sort array by increasing frequency
1,636
0.687
Easy
23,736
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1411793/Python3-Faster-than-94.95-of-the-Solutions
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: count = {} for num in nums: if num not in count: count[num] = 1 else: count[num] += 1 l = [(k,v) for k,v in count.items()] l.sort(key = lambda x:x[0], reverse=True) l.sort(key = lambda x:x[1]) result = [] for i in l: result.extend([i[0]]*i[1]) return result
sort-array-by-increasing-frequency
Python3 - Faster than 94.95% of the Solutions
harshitgupta323
2
162
sort array by increasing frequency
1,636
0.687
Easy
23,737
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1999997/easy-commented-python-code
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: d = {} count = 0 output = [] nums.sort() # create a dictonary key = frequency and value = list of all numbers with that freq. for i in set(nums): # print(d) if nums.count(i) not in d: d[nums.count(i)] = [i] else: d[nums.count(i)].append(i) # sort lists in the dictonary for i in d: d[i].sort() # main code for i in sorted(d): # sorting if freq. is 1 if len(d[i]) == 1: for j in range(i): output.append(d[i][0]) else: # sorting in decending order if freq in >1 for j in reversed(d[i]): for k in range(i): output.append(j) return output
sort-array-by-increasing-frequency
easy commented python code
dakash682
1
279
sort array by increasing frequency
1,636
0.687
Easy
23,738
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1605085/Python3-Sorting-with-Counter
class Solution: def frequencySort(self,nums): res=[] for item,count in Counter(sorted(nums)).most_common()[::-1]: res+=[item]*count return res
sort-array-by-increasing-frequency
Python3 Sorting with Counter
description
1
336
sort array by increasing frequency
1,636
0.687
Easy
23,739
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1582660/Python-Easy-to-Understand-Counter-Beats-95-Runtime
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: counter = Counter(nums) sorted_count = [[key] * count for key, count in sorted(counter.items(), key=lambda kv: (kv[1], -kv[0]))] return itertools.chain(*sorted_count)
sort-array-by-increasing-frequency
[Python] Easy to Understand - Counter - Beats 95% Runtime
matthewaj
1
599
sort array by increasing frequency
1,636
0.687
Easy
23,740
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2811224/Easy-To-Understand-or-Beginner-Level-Code-or-Python
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: ans = list() r = Counter(nums) r = Counter(nums).most_common() def sorting(x): return x[0] def sorting1(y): return y[1] r.sort(key=sorting, reverse=True) r.sort(key=sorting1) for i in r: a,b = i ans.extend([a]*b) return ans
sort-array-by-increasing-frequency
Easy To Understand | Beginner Level Code | Python
beingdillig
0
4
sort array by increasing frequency
1,636
0.687
Easy
23,741
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2775514/PYTHON-1-LINER
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: return sorted(sorted(nums,reverse=True),key=lambda x:nums.count(x))
sort-array-by-increasing-frequency
PYTHON 1-LINER 🤞
ganesh_5I4
0
7
sort array by increasing frequency
1,636
0.687
Easy
23,742
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2774034/Python-1-line-solution.-But-can-we-use-python-built-in-functions
class Solution(object): def frequencySort(self, nums): """ :type nums: List[int] :rtype: List[int] """ return sorted(nums, key=lambda x:(nums.count(x), -x))
sort-array-by-increasing-frequency
Python 1 line solution. But can we use python built-in functions???
csgogogo9527
0
6
sort array by increasing frequency
1,636
0.687
Easy
23,743
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2767841/Python-easy-code-solution-for-beginners.
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: nums.sort() value = [] ans = [] num = nums[::-1] c = Counter(num) for i in c: value.append(c[i]) value.sort() for i in value: for key, value in c.items(): if(i == value): for j in range(i): ans.append(key) c.pop(key) break return ans
sort-array-by-increasing-frequency
Python easy code solution for beginners.
anshu71
0
19
sort array by increasing frequency
1,636
0.687
Easy
23,744
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2746649/O(nlogn)-time-or-O(n)-space
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: d = {} for i in nums: d[i]=d.get(i, 0)+1 nums.sort(key = lambda x:(d[x], -x)) return nums
sort-array-by-increasing-frequency
O(nlogn) time | O(n) space
wakadoodle
0
11
sort array by increasing frequency
1,636
0.687
Easy
23,745
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2674704/Easy-Python-Solution-Using-Dictionary
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: dic={} for i in nums: if i not in dic: dic[i]=1 else: dic[i]+=1 arr=nums arr=sorted(arr,key=lambda x:(dic[x],-x)) return arr
sort-array-by-increasing-frequency
Easy Python Solution Using Dictionary
ankitr8055
0
9
sort array by increasing frequency
1,636
0.687
Easy
23,746
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2454721/python3-using-dictionary-with-set-faster-than-84
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: ans=[] from collections import Counter counts=Counter(nums) for v in sorted(set(counts.values())): temp_k=[] for k in counts.keys(): if counts[k]==v: temp_k.append(k) temp_k=sorted(temp_k,reverse=True) for k in temp_k: ans+=[k]*v return ans
sort-array-by-increasing-frequency
[python3] using dictionary with set, faster than 84%
hhlinwork
0
74
sort array by increasing frequency
1,636
0.687
Easy
23,747
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/2379861/Sort-Array-by-Increasing-Frequency
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: x = {} for i in nums: if i in x : x[i]+=1 else: x[i]=1 def swap(i,j): nums[i],nums[j]= nums[j],nums[i] for i in range(len(nums)): for j in range(i+1,len(nums)): if x[nums[i]]>x[nums[j]]: swap(i,j) elif x[nums[i]]==x[nums[j]]and nums[i]<nums[j]: swap(i,j) return nums
sort-array-by-increasing-frequency
Sort Array by Increasing Frequency
dhananjayaduttmishra
0
79
sort array by increasing frequency
1,636
0.687
Easy
23,748
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1862050/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: res = {} result = [] for i in sorted(set(nums)): res[i] = nums.count(i) print(res) for i in (reversed(sorted(res, reverse = True, key = res.get))): for _ in range(nums.count(i)): result.append(i) return result
sort-array-by-increasing-frequency
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
261
sort array by increasing frequency
1,636
0.687
Easy
23,749
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1818670/2-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-98
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: return list(chain(*[[idx]*val for idx,val in sorted(Counter(nums).items(),key=lambda x:(x[1],-x[0]))]))
sort-array-by-increasing-frequency
2-Lines Python Solution || 70% Faster || Memory less than 98%
Taha-C
0
191
sort array by increasing frequency
1,636
0.687
Easy
23,750
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1591936/Python-3-Counter-solution
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: c = collections.Counter(nums) return sorted(nums, key=lambda num: (c[num], -num))
sort-array-by-increasing-frequency
Python 3 Counter solution
dereky4
0
664
sort array by increasing frequency
1,636
0.687
Easy
23,751
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1571984/python-ordereddict-custom-sort
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: dic={} for i in nums: dic[i]=dic.get(i,0)+1 ord_dic = OrderedDict(sorted(dic.items(), key=lambda t: t[0],reverse=True)) _ord = OrderedDict(sorted(ord_dic.items(),key=lambda t: t[1])) idx=0 for k,v in _ord.items(): while v>0: nums[idx]=k idx=idx+1 v=v-1 return nums```
sort-array-by-increasing-frequency
python ordereddict custom sort
rashmirashmitha32
0
241
sort array by increasing frequency
1,636
0.687
Easy
23,752
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1555503/Python3-Solution-with-using-sorting
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: c = collections.Counter(nums) return sorted(nums, key=lambda val: (c[val], -val))
sort-array-by-increasing-frequency
[Python3] Solution with using sorting
maosipov11
0
191
sort array by increasing frequency
1,636
0.687
Easy
23,753
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1542633/Python-solution-48-ms-90-better-runtime-and-95-better-memory-usage
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: num_count = defaultdict(int) for num in nums: num_count[num] += 1 count_nums = defaultdict(set) for num, count in num_count.items(): count_nums[count].add(num) output = [] for count in sorted(count_nums.keys()): values = count_nums[count] for value in sorted(values, reverse=True): output += [value] * count return output ```
sort-array-by-increasing-frequency
Python solution 48 ms 90% better runtime and 95% better memory usage
akshaykumar19002
0
336
sort array by increasing frequency
1,636
0.687
Easy
23,754
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1537740/Python-Easy-Solution
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: nums.sort() c = collections.Counter(nums).most_common(len(nums)) res = [] while c: l = c[-1][1] n = c[-1][0] for i in range(l): res.append(n) else: c.pop() else: return res
sort-array-by-increasing-frequency
Python Easy Solution
aaffriya
0
352
sort array by increasing frequency
1,636
0.687
Easy
23,755
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1053368/Faster-then-85-of-Solution-and-less-than-58.42-memory-usage
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: #nums = [-1,1,-6,4,5,-6,1,4,1] dict2 = self.dict1(nums) keys = list(self.dict1(nums).keys()) revers = {} for i in range(0,len(keys)): if dict2[keys[i]] not in revers : revers[dict2[keys[i]]] = [keys[i]] else: revers[dict2[keys[i]]].extend([keys[i]]) serve = list(sorted(list(revers.keys()),reverse=False)) temper = [] for i in range(0,len(serve)): something = revers[serve[i]] if len(something)==1: temper.extend(something*serve[i]) else: temper.extend(sorted(something*serve[i],reverse =True) ) return temper def dict1(self,nums): new = {} for i in range(0,len(nums)): if nums[i] not in new: new[nums[i]] = 1 else: new[nums[i]] += 1 return new
sort-array-by-increasing-frequency
Faster then 85% of Solution and less than 58.42% memory usage
xevb
0
122
sort array by increasing frequency
1,636
0.687
Easy
23,756
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1051038/Python3-simple-solution-using-dictionary
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: nums = sorted(nums,reverse = True) d = {} x = [] for i in nums: d[i] = d.get(i,0) + 1 d = {i:j for i,j in sorted(d.items(),key=lambda x: x[1])} for i,j in d.items(): x += [i]*j return x
sort-array-by-increasing-frequency
Python3 simple solution using dictionary
EklavyaJoshi
0
134
sort array by increasing frequency
1,636
0.687
Easy
23,757
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1036375/python3-using-OrderedDict
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: d = collections.OrderedDict() nums.sort(reverse=True) for el in nums: if el in d: d[el] += 1 else: d[el] = 1 rez = [] i = 0 dist = len(d) while i < dist: num = min(d, key=d.get) arr = [num] * d[num] rez += arr del d[num] i += 1 return rez
sort-array-by-increasing-frequency
python3 using OrderedDict
dmo2412
0
194
sort array by increasing frequency
1,636
0.687
Easy
23,758
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/1026766/Python3-sorting-O(NlogN)
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: freq = {} for x in nums: freq[x] = 1 + freq.get(x, 0) return sorted(nums, key=lambda x: (freq[x], -x))
sort-array-by-increasing-frequency
[Python3] sorting O(NlogN)
ye15
0
120
sort array by increasing frequency
1,636
0.687
Easy
23,759
https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/965286/Faster-than-98-Python3
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: counter = [(x[0], len(list(x[1]))) for x in groupby(sorted(nums))] sorted_new_array = sorted(counter, key=lambda x: (x[1], -x[0])) nums = [] for i in sorted_new_array: nums += ([i[0]] * i[1]) return nums
sort-array-by-increasing-frequency
Faster than 98% Python3
WiseLin
-1
599
sort array by increasing frequency
1,636
0.687
Easy
23,760
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2806260/Python-or-Easy-Peasy-Code-or-O(n)
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: l = [] for i in points: l.append(i[0]) a = 0 l.sort() for i in range(len(l)-1): if l[i+1] - l[i] > a: a = l[i+1] - l[i] return a
widest-vertical-area-between-two-points-containing-no-points
Python | Easy Peasy Code | O(n)
bhuvneshwar906
0
2
widest vertical area between two points containing no points
1,637
0.842
Medium
23,761
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2789278/Python-1-line-code
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: return max([t - s for s, t in zip(sorted([r[0] for r in points]), sorted([r[0] for r in points])[1:])])
widest-vertical-area-between-two-points-containing-no-points
Python 1 line code
kumar_anand05
0
4
widest vertical area between two points containing no points
1,637
0.842
Medium
23,762
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2778374/Python-easy-O(nlogn)-time-solution
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: points.sort(key = lambda x:x[0]) res = 0 for i in range(len(points)-1): res = max(res, points[i+1][0] - points[i][0]) return res
widest-vertical-area-between-two-points-containing-no-points
Python easy O(nlogn) time solution
byuns9334
0
2
widest vertical area between two points containing no points
1,637
0.842
Medium
23,763
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2698327/Python3-Simple-Solution
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: res = 0 points.sort(key = lambda x: x[0]) prev = points[0][0] for x, y in points[1:]: res = max(res, x - prev) prev = x return res
widest-vertical-area-between-two-points-containing-no-points
Python3 Simple Solution
mediocre-coder
0
3
widest vertical area between two points containing no points
1,637
0.842
Medium
23,764
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2673727/Python3-few-line-solution-memory-beats%3A-91.64
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: xs = sorted({x[0] for x in points}) if len(xs) == 1: return 0 else: return max(xs[i+1]-xs[i] for i in range(0,len(xs)-1))
widest-vertical-area-between-two-points-containing-no-points
Python3 few line solution - memory beats: 91.64%
sipi09
0
5
widest vertical area between two points containing no points
1,637
0.842
Medium
23,765
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2614520/Python-solution-with-sorting-oror-N(logN)-Time-complexity
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: # Sorting points on x co-ordinate points.sort(key = lambda x: x[0]) max_dist = 0 # Get the max value by comparing consecutive values for i in range(1, len(points)): max_dist = max(max_dist, points[i][0] - points[i-1][0]) return max_dist
widest-vertical-area-between-two-points-containing-no-points
Python solution with sorting || N(logN) Time complexity
vanshika_2507
0
9
widest vertical area between two points containing no points
1,637
0.842
Medium
23,766
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2586554/Python3-or-Step-by-Step-or-O(1)-Space-in-2-lines
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: points.sort(key=lambda a: a[0]) return max((v2[0] - v1[0] for v1, v2 in zip(points, islice(points,1,None))))
widest-vertical-area-between-two-points-containing-no-points
Python3 | Step-by-Step | O(1) Space in 2 lines
dimitars
0
12
widest vertical area between two points containing no points
1,637
0.842
Medium
23,767
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2586554/Python3-or-Step-by-Step-or-O(1)-Space-in-2-lines
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: # Note: # This problem is solved by finding the largest # difference between each consecutive point # in the X axis. # 1. The list is sorted using the first element # of each row as a key. This will ensure that # the points are ordered based on their placement # on the X axis. points.sort(key=lambda a: a[0]) # 2. An islice is created to give us all elements # except the first one in the points list. points_offset = islice(points,1,None) # 3. zip is used to pair points offset by 1. # zip's size is based on the shorter iterable # so it can't loop out of bounds points_offset_pairs = zip(points, points_offset) # 4. A generator which returns the difference # between X of each offset point is made points_offset_difference = (v2[0] - v1[0] for v1, v2 in points_offset_pairs) # 5. The maximum yielded value is returned return max(points_offset_difference)
widest-vertical-area-between-two-points-containing-no-points
Python3 | Step-by-Step | O(1) Space in 2 lines
dimitars
0
12
widest vertical area between two points containing no points
1,637
0.842
Medium
23,768
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2407274/Python3-Solution-with-using-sorting
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: points.sort(key=lambda x: x[0]) res = 0 for i in range(len(points) - 1): res = max(res, points[i + 1][0] - points[i][0]) return res
widest-vertical-area-between-two-points-containing-no-points
[Python3] Solution with using sorting
maosipov11
0
12
widest vertical area between two points containing no points
1,637
0.842
Medium
23,769
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2385059/Python3-or-Sort-Only-Using-X-Coords
class Solution: #T.C = O(n + n + n) -> O(n) #S.C = O(n + n) -> O(n) def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: #Approach: Disregard y coordinates! #Record x coordinates of every point in points! #Sort the x coordinates! For every pair of adjacent x coordinate values, it represents #a valid vertical area! Compute abs diff of x2 and x1! Maximize such value over all #possible pairings! distinct_x_coords = set() for point in points: x, y = point distinct_x_coords.add(x) a = [] for x in distinct_x_coords: a.append(x) a.sort() ans = 0 for i in range(0, len(a)-1, 1): if(abs(a[i+1] - a[i]) > ans): ans = abs(a[i+1] - a[i]) return ans
widest-vertical-area-between-two-points-containing-no-points
Python3 | Sort Only Using X Coords
JOON1234
0
4
widest vertical area between two points containing no points
1,637
0.842
Medium
23,770
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2120855/python-sort-using-lambda
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: points.sort(key = lambda x : x[0]) ans = [] for i in range(len(points)-1): val = abs(points[i][0] - points[i+1][0]) ans.append(val) return max(ans) ```
widest-vertical-area-between-two-points-containing-no-points
python sort using lambda
somendrashekhar2199
0
16
widest vertical area between two points containing no points
1,637
0.842
Medium
23,771
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/1573651/python-solution-or-faster-than-94
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: L,max = [],0 for i in range(len(points)): L.append(points[i][0]) L = list(set(L)) L.sort() for i in range(len(L)-1): if L[i+1] - L[i] > max : max = L[i+1] - L[i] return max
widest-vertical-area-between-two-points-containing-no-points
python solution | faster than 94%
anandanshul001
0
71
widest vertical area between two points containing no points
1,637
0.842
Medium
23,772
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/1573651/python-solution-or-faster-than-94
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: points.sort() idx = max_width = 0 while idx < (len(points)-1): jdx = idx + 1 if points[jdx][0] - points[idx][0] > max_width : max_width = points[jdx][0] - points[idx][0] idx += 1 else: idx += 1 return max_width
widest-vertical-area-between-two-points-containing-no-points
python solution | faster than 94%
anandanshul001
0
71
widest vertical area between two points containing no points
1,637
0.842
Medium
23,773
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/1101479/Python3-1-dim-problem
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: vals = sorted(x for x, _ in points) return max(vals[i] - vals[i-1] for i in range(1, len(vals)))
widest-vertical-area-between-two-points-containing-no-points
[Python3] 1-dim problem
ye15
0
71
widest vertical area between two points containing no points
1,637
0.842
Medium
23,774
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/1101479/Python3-1-dim-problem
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: points.sort(key=lambda x: x[0]) ans = 0 for i in range(1, len(points)): ans = max(ans, points[i][0] - points[i-1][0]) return ans
widest-vertical-area-between-two-points-containing-no-points
[Python3] 1-dim problem
ye15
0
71
widest vertical area between two points containing no points
1,637
0.842
Medium
23,775
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/1008850/python3-easy-example
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: sort_point = sorted(points, key=lambda x: x[0]) return max([abs(sort_point[i][0] - sort_point[i+1][0]) for i in range(len(sort_point) - 1)])
widest-vertical-area-between-two-points-containing-no-points
python3 easy example
MartenMink
0
58
widest vertical area between two points containing no points
1,637
0.842
Medium
23,776
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/984967/Python3-%3A-faster-than-98.54-of-Python3-online-submissions
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: y = sorted([i for i,j in points]) m = 0 temp = 0 for i in range(1,len(y)): temp = y[i] - y[i-1] m = max(temp,m) return m
widest-vertical-area-between-two-points-containing-no-points
Python3 : faster than 98.54% of Python3 online submissions
abhijeetmallick29
0
93
widest vertical area between two points containing no points
1,637
0.842
Medium
23,777
https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/919487/explanation-The-simplest-Python-without-Y
class Solution: def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int: last = None mx = None for i in sorted(points): i = i[0] if last is not None and (mx is None or i - last > mx): mx = i - last last = i return mx
widest-vertical-area-between-two-points-containing-no-points
[explanation] The simplest Python without Y
c0ntender
0
72
widest vertical area between two points containing no points
1,637
0.842
Medium
23,778
https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/1101671/Python3-top-down-and-bottom-up-dp
class Solution: def countSubstrings(self, s: str, t: str) -> int: m, n = len(s), len(t) @cache def fn(i, j, k): """Return number of substrings ending at s[i] and t[j] with k=0/1 difference.""" if i < 0 or j < 0: return 0 if s[i] == t[j]: return fn(i-1, j-1, k) + (k==0) else: return 0 if k == 0 else 1 + fn(i-1, j-1, 0) return sum(fn(i, j, 1) for i in range(m) for j in range(n))
count-substrings-that-differ-by-one-character
[Python3] top-down & bottom-up dp
ye15
5
303
count substrings that differ by one character
1,638
0.714
Medium
23,779
https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/1101671/Python3-top-down-and-bottom-up-dp
class Solution: def countSubstrings(self, s: str, t: str) -> int: m, n = len(s), len(t) dp0 = [[0]*(n+1) for _ in range(m+1)] # 0-mismatch dp1 = [[0]*(n+1) for _ in range(m+1)] # 1-mismatch ans = 0 for i in range(m): for j in range(n): if s[i] == t[j]: dp0[i+1][j+1] = 1 + dp0[i][j] dp1[i+1][j+1] = dp1[i][j] else: dp0[i+1][j+1] = 0 dp1[i+1][j+1] = 1 + dp0[i][j] ans += dp1[i+1][j+1] return ans
count-substrings-that-differ-by-one-character
[Python3] top-down & bottom-up dp
ye15
5
303
count substrings that differ by one character
1,638
0.714
Medium
23,780
https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/1186959/Python3-simple-solution
class Solution: def countSubstrings(self, s: str, t: str) -> int: count = 0 for i in range(len(s)): for j in range(len(t)): x,y = i,j d = 0 while x < len(s) and y < len(t): if s[x] != t[y]: d += 1 if d == 1: count += 1 if d == 2: break x += 1 y += 1 return count
count-substrings-that-differ-by-one-character
Python3 simple solution
EklavyaJoshi
1
235
count substrings that differ by one character
1,638
0.714
Medium
23,781
https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/2839579/Python-(Simple-DP)
class Solution: def countSubstrings(self, s, t): n, m = len(s), len(t) match = [[0 for _ in range(m+1)] for _ in range(n+1)] matchone = [[0 for _ in range(m+1)] for _ in range(n+1)] for i in range(1,n+1): for j in range(1,m+1): if s[i-1] == t[j-1]: match[i][j] = 1 + match[i-1][j-1] matchone[i][j] = matchone[i-1][j-1] else: match[i][j] = 0 matchone[i][j] = 1 + match[i-1][j-1] return sum([sum(i) for i in matchone])
count-substrings-that-differ-by-one-character
Python (Simple DP)
rnotappl
0
2
count substrings that differ by one character
1,638
0.714
Medium
23,782
https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/1498318/Python3-or-O(MN*max(MN))
class Solution: def countSubstrings(self, s: str, t: str) -> int: ans=0 for i in range(len(s)): for j in range(len(t)): x=i y=j d=0 while x<len(s) and y<len(t): if s[x]!=t[y]: d+=1 if d==1: ans+=1 if d==2: break x+=1 y+=1 return ans
count-substrings-that-differ-by-one-character
[Python3] | O(MN*max(MN))
swapnilsingh421
0
179
count substrings that differ by one character
1,638
0.714
Medium
23,783
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/1101522/Python3-top-down-dp
class Solution: def numWays(self, words: List[str], target: str) -> int: freq = [defaultdict(int) for _ in range(len(words[0]))] for word in words: for i, c in enumerate(word): freq[i][c] += 1 @cache def fn(i, k): """Return number of ways to form target[i:] w/ col k.""" if i == len(target): return 1 if k == len(words[0]): return 0 return freq[k][target[i]]*fn(i+1, k+1) + fn(i, k+1) return fn(0, 0) % 1_000_000_007
number-of-ways-to-form-a-target-string-given-a-dictionary
[Python3] top-down dp
ye15
2
169
number of ways to form a target string given a dictionary
1,639
0.429
Hard
23,784
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/2836353/Python3-Recursion-to-memoization-to-optimization-with-complete-explaination
class Solution: def numWays(self, words: List[str], target: str) -> int: MOD = 10**9+7 n,m = len(target),len(words[0]) def dfs(i,j): if j == n: return 1 if i == m: return 0 if n-j > m-i: return 0 res = 0 for word in words: for k in range(i,m): if word[k] == target[j]: res += dfs(k+1,j+1) return res return dfs(0,0)%MOD
number-of-ways-to-form-a-target-string-given-a-dictionary
[Python3] Recursion to memoization to optimization with complete explaination
shriyansnaik
0
7
number of ways to form a target string given a dictionary
1,639
0.429
Hard
23,785
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/2836353/Python3-Recursion-to-memoization-to-optimization-with-complete-explaination
class Solution: def numWays(self, words: List[str], target: str) -> int: MOD = 10**9+7 n,m = len(target),len(words[0]) dp = {} def dfs(i,j): if j == n: return 1 if i == m: return 0 if n-j > m-i: return 0 if (i,j) in dp: return dp[(i,j)] res = 0 for word in words: for k in range(i,m): if word[k] == target[j]: res += dfs(k+1,j+1) dp[(i,j)] = res return dp[(i,j)] return dfs(0,0)%MOD
number-of-ways-to-form-a-target-string-given-a-dictionary
[Python3] Recursion to memoization to optimization with complete explaination
shriyansnaik
0
7
number of ways to form a target string given a dictionary
1,639
0.429
Hard
23,786
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/2836353/Python3-Recursion-to-memoization-to-optimization-with-complete-explaination
class Solution: def numWays(self, words: List[str], target: str) -> int: MOD = 10**9+7 n,m = len(target),len(words[0]) frequency = defaultdict(int) for word in words: for i,ch in enumerate(word): frequency[(ch,i)]+=1 dp = {} def dfs(i,j): if j == n: return 1 if i == m: return 0 if n-j > m-i: return 0 if (i,j) in dp: return dp[(i,j)] take,not_take = 0,0 not_take = dfs(i+1,j)%MOD if frequency[(target[j],i)] > 0: take = dfs(i+1,j+1)*frequency[(target[j],i)]%MOD dp[(i,j)] = (take+not_take)%MOD return dp[(i,j)] return dfs(0,0)%MOD
number-of-ways-to-form-a-target-string-given-a-dictionary
[Python3] Recursion to memoization to optimization with complete explaination
shriyansnaik
0
7
number of ways to form a target string given a dictionary
1,639
0.429
Hard
23,787
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/2353648/python-3-or-top-down-1-D-dp-or-O(mn)O(n)
class Solution: def numWays(self, words: List[str], target: str) -> int: m, n = len(target), len(words[0]) wordChars = [] for j in range(n): wordChars.append(collections.Counter(word[j] for word in words)) prev = [1] * (n + 1) for i in range(m - 1, -1, -1): cur = [0] * (n + 1) for j in range(n - 1, -1, -1): cur[j] = wordChars[j][target[i]] * prev[j + 1] + cur[j + 1] prev = cur return cur[0] % (10 ** 9 + 7)
number-of-ways-to-form-a-target-string-given-a-dictionary
python 3 | top down 1-D dp | O(mn)/O(n)
dereky4
0
416
number of ways to form a target string given a dictionary
1,639
0.429
Hard
23,788
https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/925002/bottom-up-top-down-dynamic-programming.-explained
class Solution: def numWays(self, words: List[str], target: str) -> int: @lru_cache(None) # dfs(i, j) is number of ways to construct taget[:i+1] using chars with index at most j in the word in the words dictionary. def dfs(i, j): if i < 0: return 1 if j < 0: return 0 # ans = dfs(i, j-1) if chars_count[j][target[i]] > 0: ans += dfs(i-1, j-1)*chars_count[j][target[i]] ans %= 10**9+7 return ans m, n = len(target), len(words[0]) chars_count = [Counter([word[idx] for word in words]) for idx in range(n)] return dfs(m-1, n-1)
number-of-ways-to-form-a-target-string-given-a-dictionary
bottom up/ top down dynamic programming. explained
ytb_algorithm
0
201
number of ways to form a target string given a dictionary
1,639
0.429
Hard
23,789
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/918382/Python3-2-line-O(N)
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: mp = {x[0]: x for x in pieces} i = 0 while i < len(arr): if (x := arr[i]) not in mp or mp[x] != arr[i:i+len(mp[x])]: return False i += len(mp[x]) return True
check-array-formation-through-concatenation
[Python3] 2-line O(N)
ye15
9
705
check array formation through concatenation
1,640
0.561
Easy
23,790
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/918382/Python3-2-line-O(N)
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: mp = {x[0]: x for x in pieces} return sum((mp.get(x, []) for x in arr), []) == arr
check-array-formation-through-concatenation
[Python3] 2-line O(N)
ye15
9
705
check array formation through concatenation
1,640
0.561
Easy
23,791
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/996914/Python-Simple-O(n)-solution-based-on-the-hints
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: for i, piece in enumerate(pieces): for j,num in enumerate(piece): try: pieces[i][j] = arr.index(num) except: return False pieces.sort() return [i for i in range(len(arr))] == [x for piece in pieces for x in piece] ## or use list(chain(*[piece for piece in pieces]))
check-array-formation-through-concatenation
[Python] Simple O(n) solution based on the hints
KevinZzz666
4
342
check array formation through concatenation
1,640
0.561
Easy
23,792
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/1237002/Python3-Intuitive-solution-by-hash-map
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: dic = {} for piece in pieces: dic[piece[0]] = piece idx = 0 while idx < len(arr): key = arr[idx] if key in dic: if arr[idx: idx + len(dic[key])] == dic[key]: idx += len(dic[key]) else: return False else: return False return True
check-array-formation-through-concatenation
Python3 Intuitive solution by hash map
georgeqz
2
138
check array formation through concatenation
1,640
0.561
Easy
23,793
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/1095488/Python3-simple-solution-by-two-approaches
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: s = ''.join(map(str, arr)) for i in pieces: if ''.join(map(str, i)) not in s or not i[0] in arr: return False return True
check-array-formation-through-concatenation
Python3 simple solution by two approaches
EklavyaJoshi
2
75
check array formation through concatenation
1,640
0.561
Easy
23,794
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/1095488/Python3-simple-solution-by-two-approaches
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: for i in pieces: if i[0] not in arr: return False pieces.sort(key=lambda a:arr.index(a[0])) res = [] for i in pieces: res += i return True if res == arr else False
check-array-formation-through-concatenation
Python3 simple solution by two approaches
EklavyaJoshi
2
75
check array formation through concatenation
1,640
0.561
Easy
23,795
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/2523031/C%2B%2BPython-Solution
class Solution: def canFormArray(self, arr, pieces): d = {x[0]: x for x in pieces} return list(chain(*[d.get(num, []) for num in arr])) == arr
check-array-formation-through-concatenation
C++/Python Solution
arpit3043
1
68
check array formation through concatenation
1,640
0.561
Easy
23,796
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/1515782/Python-the-most-optimal-solution%3A-O(n)-time-O(n)-space-with-hashmap
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: res = [] n = len(arr) indexes = {} for i in range(len(pieces)): indexes[pieces[i][0]] = i idx = 0 while idx < n: if arr[idx] not in indexes: return False item = pieces[indexes[arr[idx]]] for j in range(len(item)): if arr[idx+j] != item[j]: return False else: res.append(item[j]) idx += len(item) return True
check-array-formation-through-concatenation
Python the most optimal solution: O(n) time, O(n) space with hashmap
byuns9334
1
112
check array formation through concatenation
1,640
0.561
Easy
23,797
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/1135159/Python-Faster-than-99
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: p = {val[0]: val for val in pieces} i = 0 while i < len(arr): if arr[i] in p: for val in p[arr[i]]: if i == len(arr) or arr[i] != val: return False i += 1 else: return False return True
check-array-formation-through-concatenation
[Python] Faster than 99%
FooMan
1
168
check array formation through concatenation
1,640
0.561
Easy
23,798
https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/1019541/python3-solution-without-converting-into-string
class Solution: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: j,i=0,0 l=[] while i<len(arr) and j<len(pieces): if arr[i] in pieces[j]: for k in range(len(pieces[j])): l.append(pieces[j][k]) i=i+1 j=0 else: j=j+1 return l==arr ```
check-array-formation-through-concatenation
python3 solution without converting into string
_SID_
1
98
check array formation through concatenation
1,640
0.561
Easy
23,799