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/plates-between-candles/discuss/1605103/Python3-Easy-and-Simple-to-understand-Solution-Good-example-(O(N%2BQ))
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: # accumulated sum of '*' accumulated = [] accumulated.append(int(s[0] == '|')) for char in s[1:]: # ex. "* * | * * | * * * | " val = accumulated[-1] + (char == '*') # [1, 2, 2, 3, 4, 4, 5, 6, 7, 7] accumulated.append(val) # nearest '|' position from right (i) near_i = [0] * len(s) k = 0 for i in range(len(s)): # ex. "* * | * * | * * * |" while s[i] == '|' and k <= i: # [2, 2, 2, 5, 5, 5, 9, 9, 9, 9] near_i[k] = i # i > k += 1 # nearest '|' position from left (j) near_j = [0] * len(s) k = len(s) - 1 for j in reversed(range(len(s))): # ex. "* * | * * | * * * |" while s[j] == '|' and k >= j: # [0, 0, 2, 2, 2, 5, 5, 5, 5, 9] near_j[k] = j # < j k -= 1 result = [] for i, j in queries: if abs(j - i) <= 1: # base case: i+1 < j-1 because of the word 'between' val = 0 else: ni, nj = near_i[i], near_j[j] val = accumulated[nj] - accumulated[ni] cnt = max(0, val) # base case: count >= 0 because no negative count exists result.append(cnt) return result
plates-between-candles
[Python3] Easy & Simple-to-understand Solution, Good example (O(N+Q))
Otto_Kwon
1
164
plates between candles
2,055
0.444
Medium
28,500
https://leetcode.com/problems/plates-between-candles/discuss/2699048/Python-O(N-%2B-MlogN)-O(N)
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: mapping, plates = OrderedDict(), 0 candles = [] for i in range(len(s)): if s[i] == "*": plates += 1 else: mapping[i] = plates candles.append(i) res = [] for l, r in queries: lower = bisect_left(candles, l) upper = bisect_right(candles, r) - 1 if upper <= lower: res.append(0) continue diff = mapping[candles[upper]] - mapping[candles[lower]] res.append(diff) return res
plates-between-candles
Python - O(N + MlogN), O(N)
Teecha13
0
23
plates between candles
2,055
0.444
Medium
28,501
https://leetcode.com/problems/plates-between-candles/discuss/1554464/Python-3-or-Prefix-Sum-Math-O(N)-or-Explanation
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: cur, left, n = 0, -1, len(s) right = n pre_sum = [0] * n # pre_sum[i]: number of candles before `i` (including `i`) left_idx = [-1] * n # left_idx[i]: index of the closest candle on the left side of `i` right_idx = [-1] * n # right_idx[i]: index of the closest candle on the right side of `i` for i, c in enumerate(s): # calculate above 3 lists if c == '|': left = i cur += 1 left_idx[i] = left pre_sum[i] = cur c_right = s[n-1-i] if c_right == '|': right = n-1-i right_idx[n-1-i] = right ans = [] for x, y in queries: if left_idx[y] - right_idx[x] < 0: # case when there are no plates between candles val = 0 else: # total number of plates+candles between the most right candle and the most left candle x <= right_idx[x] <= left_idx[y] < y val = (left_idx[y] - right_idx[x]) - \ (pre_sum[left_idx[y]] - pre_sum[right_idx[x]]) # total number of candles in the same range ans.append(val) # total - candles = plates return ans
plates-between-candles
Python 3 | Prefix Sum, Math, O(N) | Explanation
idontknoooo
0
192
plates between candles
2,055
0.444
Medium
28,502
https://leetcode.com/problems/plates-between-candles/discuss/1554464/Python-3-or-Prefix-Sum-Math-O(N)-or-Explanation
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: n = len(s) prev = -1 left_idx = [-1] * n for i, c in enumerate(s): if c == '|': prev = i left_idx[i] = prev prev = n right_idx = [-1] * n for i in range(n-1, -1, -1): c = s[i] if c == '|': prev = i right_idx[i] = prev cur = 0 pre_sum = [0] * n for i, c in enumerate(s): if c == '|': cur += 1 pre_sum[i] = cur ans = [] for x, y in queries: if left_idx[y] - right_idx[x] < 0: val = 0 else: val = left_idx[y] - right_idx[x] + 1 - (pre_sum[left_idx[y]] - pre_sum[right_idx[x]] + 1) ans.append(val) return ans
plates-between-candles
Python 3 | Prefix Sum, Math, O(N) | Explanation
idontknoooo
0
192
plates between candles
2,055
0.444
Medium
28,503
https://leetcode.com/problems/plates-between-candles/discuss/1554464/Python-3-or-Prefix-Sum-Math-O(N)-or-Explanation
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: cur, left, n = 0, -1, len(s) right = n pre_sum = [0] * n left_idx = [-1] * n right_idx = [-1] * n for i, c in enumerate(s): if c == '|': left = i cur += 1 left_idx[i] = left pre_sum[i] = cur c_right = s[n-1-i] if c_right == '|': right = n-1-i right_idx[n-1-i] = right return [0 if left_idx[y] - right_idx[x] < 0 else left_idx[y] - right_idx[x] - (pre_sum[left_idx[y]] - pre_sum[right_idx[x]]) for x, y in queries]
plates-between-candles
Python 3 | Prefix Sum, Math, O(N) | Explanation
idontknoooo
0
192
plates between candles
2,055
0.444
Medium
28,504
https://leetcode.com/problems/plates-between-candles/discuss/1549047/Python3-O(N%2BQ)
class Solution: def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]: pref=[0] #prefix sum array for calculating * for x in s: if x=='*': pref.append(pref[-1]+1) else: pref.append(pref[-1]) ans=[] #array for finding the next | nex=[0]*len(s) stack=[] for x in range(len(s)-1,-1,-1): if not stack: nex[x]=inf elif s[x]=='|': nex[x]=x else: nex[x]=stack[-1] if s[x]=='|': stack.append(x) #array for finding the previous | prev=[0]*len(s) for x in range(len(s)): if not stack: prev[x]=-inf elif s[x]=='|': prev[x]=x else: prev[x]=stack[-1] if s[x]=='|': stack.append(x) for x in queries: #if | from both ends coincide or cross if nex[x[0]]>=prev[x[1]]: ans.append(0) else: #find the next | and the previous | and calculate the * in between ans.append(pref[prev[x[1]]]-pref[nex[x[0]]]) return ans
plates-between-candles
Python3 O(N+Q)
abhinav_201
0
80
plates between candles
2,055
0.444
Medium
28,505
https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/discuss/2331905/Python3-or-DFS-with-backtracking-or-Clean-code-with-comments
class Solution: BOARD_SIZE = 8 def diag(self, r, c): # Return all diagonal indices except (r, c) # Diagonal indices has the same r - c inv = r - c result = [] for ri in range(self.BOARD_SIZE): ci = ri - inv if 0 <= ci < self.BOARD_SIZE and ri != r: result.append((ri, ci)) return result def reverseDiag(self, r, c): # Return all reverse diagonal indices except (r, c) # Reverse diagonal indices has the same r + c inv = r + c result = [] for ri in range(self.BOARD_SIZE): ci = inv - ri if 0 <= ci < self.BOARD_SIZE and ri != r: result.append((ri, ci)) return result def generatePossiblePositions(self, piece, start): # Generate list of possible positions for every figure rs, cs = start[0] - 1, start[1] - 1 # Start position result = [(rs, cs)] # Straight if piece == "rook" or piece == "queen": result.extend([(r, cs) for r in range(self.BOARD_SIZE) if r != rs]) result.extend([(rs, c) for c in range(self.BOARD_SIZE) if c != cs]) # Diagonal if piece == "bishop" or piece == "queen": result.extend(self.diag(rs, cs)) result.extend(self.reverseDiag(rs, cs)) return result def collide(self, start1, end1, start2, end2): # Check if two figures will collide # Collision occures if: # - two figures have the same end points # - one figure stands on the way of second one # # For this purpose let's model each step of two pieces # and compare their positions at every time step. def steps(start, end): # Total steps that should be done return abs(end - start) def step(start, end): # Step direction -1, 0, 1 if steps(start, end) == 0: return 0 return (end - start) / steps(start, end) (rstart1, cstart1), (rend1, cend1) = start1, end1 (rstart2, cstart2), (rend2, cend2) = start2, end2 # Find step direction for each piece rstep1, cstep1 = step(rstart1, rend1), step(cstart1, cend1) rstep2, cstep2 = step(rstart2, rend2), step(cstart2, cend2) # Find maximum number of steps for each piece max_step1 = max(steps(rstart1, rend1), steps(cstart1, cend1)) max_step2 = max(steps(rstart2, rend2), steps(cstart2, cend2)) # Move pieces step by step and compare their positions for step_i in range(max(max_step1, max_step2) + 1): step_i1 = min(step_i, max_step1) r1 = rstart1 + step_i1 * rstep1 c1 = cstart1 + step_i1 * cstep1 step_i2 = min(step_i, max_step2) r2 = rstart2 + step_i2 * rstep2 c2 = cstart2 + step_i2 * cstep2 # If positions are the same then collision occures if r1 == r2 and c1 == c2: return True return False def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int: if len(pieces) == 0: return 0 n = len(pieces) # Make zero-indexed start_positions = [[r - 1, c - 1] for r, c in positions] # All possible positions possible_positions = [ self.generatePossiblePositions(piece, start) for piece, start in zip(pieces, positions) ] # Let's use DFS with backtracking # For that we will keep set of already occupied coordinates # and current positions of pieces occupied = set() current_positions = [None] * n # None means that we didn't placed the piece def collision(start, end): # Helper to check if moving from start to end position will collide with someone for start2, end2 in zip(start_positions, current_positions): if end2 is not None and self.collide(start, end, start2, end2): return True return False def dfs(piece_i=0): # All pieces are placed if piece_i == n: return 1 result = 0 for position in possible_positions[piece_i]: # If position already occupied of collides with other pieces then skip it if position in occupied or collision(start_positions[piece_i], position): continue # Occupy the position occupied.add(position) current_positions[piece_i] = position # Run DFS for next piece result += dfs(piece_i + 1) # Release the position occupied.remove(position) current_positions[piece_i] = None return result return dfs()
number-of-valid-move-combinations-on-chessboard
Python3 | DFS with backtracking | Clean code with comments
snorkin
1
58
number of valid move combinations on chessboard
2,056
0.59
Hard
28,506
https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/discuss/1557870/Python3-traversal
class Solution: def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int: n = len(pieces) mp = {"bishop": ((-1, -1), (-1, 1), (1, -1), (1, 1)), "queen" : ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)), "rook" : ((-1, 0), (0, -1), (0, 1), (1, 0))} dirs = [[]] # directions for piece in pieces: dirs = [x+[xx] for x in dirs for xx in mp[piece]] positions = tuple(map(tuple, positions)) def fn(*args): """Return possible moves along given direction.""" stack = [((1<<n)-1, positions)] while stack: mask, pos = stack.pop() ans.add(pos) m = mask while m: p = [] for i in range(n): if m &amp; (1 << i): p.append((pos[i][0] + args[i][0], pos[i][1] + args[i][1])) if not (1 <= p[i][0] <= 8 and 1 <= p[i][1] <= 8): break else: p.append(pos[i]) else: cand = tuple(p) if len(set(cand)) == len(cand) and m: stack.append((m, cand)) m = mask &amp; (m-1) ans = set() for d in dirs: fn(*d) return len(ans)
number-of-valid-move-combinations-on-chessboard
[Python3] traversal
ye15
0
335
number of valid move combinations on chessboard
2,056
0.59
Hard
28,507
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1549993/Python3-1-line
class Solution: def smallestEqual(self, nums: List[int]) -> int: return next((i for i, x in enumerate(nums) if i%10 == x), -1)
smallest-index-with-equal-value
[Python3] 1-line
ye15
10
646
smallest index with equal value
2,057
0.712
Easy
28,508
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1558084/Python-1-line-99-speed-95-memory-usage
class Solution(object): def smallestEqual(self, nums, i=0): return -1 if i == len(nums) else ( i if i%10 == nums[i] else self.smallestEqual(nums, i+1) )
smallest-index-with-equal-value
Python 1 line - 99% speed 95% memory usage
SmittyWerbenjagermanjensen
5
340
smallest index with equal value
2,057
0.712
Easy
28,509
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2640991/Python-O(N)
class Solution: def smallestEqual(self, nums: List[int]) -> int: n=len(nums) for i in range(n): if i%10==nums[i]: return i return -1
smallest-index-with-equal-value
Python O(N)
Sneh713
1
50
smallest index with equal value
2,057
0.712
Easy
28,510
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2840410/Just-1-line-code-in-Python3
class Solution: def smallestEqual(self, nums: List[int]) -> int: return min([k[0] for k in list(enumerate (nums)) if k[0]%10 == k[1]], default=-1)
smallest-index-with-equal-value
Just 1 line code in Python3
DNST
0
1
smallest index with equal value
2,057
0.712
Easy
28,511
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2825297/Fast-Simple-Python-Solution-Beats-99.9
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(0, len(nums)): if i % 10 == nums[i]: return i return -1
smallest-index-with-equal-value
Fast, Simple Python Solution - Beats 99.9%
PranavBhatt
0
2
smallest index with equal value
2,057
0.712
Easy
28,512
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2805456/Python3-list-comprehension
class Solution: def smallestEqual(self, nums): idxs = [idx for idx, ele in enumerate(nums) if idx % 10 == ele] return -1 if not idxs else min(idxs)
smallest-index-with-equal-value
Python3-list comprehension
alamwasim29
0
4
smallest index with equal value
2,057
0.712
Easy
28,513
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2780464/Easy-Python-Solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): if i % 10 == nums[i]: return i return -1
smallest-index-with-equal-value
Easy Python Solution
danishs
0
3
smallest index with equal value
2,057
0.712
Easy
28,514
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2672248/v
class Solution: def smallestEqual(self, nums: List[int]) -> int: n=len(nums) for i in range(n): if i%10==nums[i]: return i return -1
smallest-index-with-equal-value
v
adityabakshi45
0
2
smallest index with equal value
2,057
0.712
Easy
28,515
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2670790/Easy-and-optimal-faster
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(0,len(nums)): if(nums[i]==i %10): return i return -1
smallest-index-with-equal-value
Easy and optimal faster
Raghunath_Reddy
0
3
smallest index with equal value
2,057
0.712
Easy
28,516
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2560519/Easy-python-solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: result = [] for i in range(len(nums)): if i % 10 == nums[i]: result.append(i) if len(result) == 0: return -1 return min(result)
smallest-index-with-equal-value
Easy python solution
samanehghafouri
0
7
smallest index with equal value
2,057
0.712
Easy
28,517
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2536018/Simple-python-solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if i % 10 == nums[i]: return i else: return -1
smallest-index-with-equal-value
Simple python solution
aruj900
0
20
smallest index with equal value
2,057
0.712
Easy
28,518
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2520388/Python-solution-or-99-Faster-or-O(n)-complexity
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(0,len(nums)): if i%10==nums[i]: return i break return -1
smallest-index-with-equal-value
Python solution | 99% Faster | O(n) complexity
KavitaPatel966
0
15
smallest index with equal value
2,057
0.712
Easy
28,519
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2180507/Python-Solution-Easy-To-Understand
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if i%10==nums[i]: return i return -1
smallest-index-with-equal-value
Python Solution- Easy To Understand✅
T1n1_B0x1
0
27
smallest index with equal value
2,057
0.712
Easy
28,520
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2091949/Python-Simple-Solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for idx, val in enumerate(nums): if idx % 10 == val: return idx return -1
smallest-index-with-equal-value
Python Simple Solution
Nk0311
0
54
smallest index with equal value
2,057
0.712
Easy
28,521
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1972392/Simple-solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: nums = [i for i, n in enumerate(nums) if i % 10 == n] return min(nums) if nums else -1
smallest-index-with-equal-value
Simple solution
andrewnerdimo
0
30
smallest index with equal value
2,057
0.712
Easy
28,522
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1934730/easy-python-code
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if i%10 == nums[i]: return i return -1
smallest-index-with-equal-value
easy python code
dakash682
0
18
smallest index with equal value
2,057
0.712
Easy
28,523
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1886752/Python-dollarolution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i,j in enumerate(nums): if i%10 == j: return i return -1
smallest-index-with-equal-value
Python $olution
AakRay
0
28
smallest index with equal value
2,057
0.712
Easy
28,524
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1858061/Python-easy-straightforward-solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if i % 10 == nums[i]: return i return -1
smallest-index-with-equal-value
Python easy straightforward solution
alishak1999
0
26
smallest index with equal value
2,057
0.712
Easy
28,525
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1830480/1-line-solution-in-Python-3
class Solution: def smallestEqual(self, nums: List[int]) -> int: return min((i for i, n in enumerate(nums) if i % 10 == n), default=-1)
smallest-index-with-equal-value
1-line solution in Python 3
mousun224
0
35
smallest index with equal value
2,057
0.712
Easy
28,526
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1810607/Python-O(n)-Solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: # Use the enumerate() function # to look at both index and its associated value at once for index, num in enumerate(nums): # We can just return as soon as we see a match if index % 10 == num: return index # Otherwise, if no match found at all, return -1 return -1
smallest-index-with-equal-value
Python O(n) Solution
White_Frost1984
0
20
smallest index with equal value
2,057
0.712
Easy
28,527
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1721097/Python3-accepted-solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if(i%10 == nums[i]): return i return -1
smallest-index-with-equal-value
Python3 accepted solution
sreeleetcode19
0
46
smallest index with equal value
2,057
0.712
Easy
28,528
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1589587/Python3-Brute-Force-Solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if i % 10 == nums[i]: return i else: return -1
smallest-index-with-equal-value
[Python3] Brute Force Solution
terrencetang
0
53
smallest index with equal value
2,057
0.712
Easy
28,529
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1549966/Python-solution
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i in range(len(nums)): if i %10 == nums[i]: return i return -1
smallest-index-with-equal-value
Python solution
abkc1221
0
54
smallest index with equal value
2,057
0.712
Easy
28,530
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2003813/Python-Solution-%2B-One-Liner!
class Solution: def smallestEqual(self, nums): for i,n in enumerate(nums): if i % 10 == n: return i return -1
smallest-index-with-equal-value
Python - Solution + One Liner!
domthedeveloper
-1
38
smallest index with equal value
2,057
0.712
Easy
28,531
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/2003813/Python-Solution-%2B-One-Liner!
class Solution: def smallestEqual(self, nums): return min((i for i,n in enumerate(nums) if i%10 == n), default=-1)
smallest-index-with-equal-value
Python - Solution + One Liner!
domthedeveloper
-1
38
smallest index with equal value
2,057
0.712
Easy
28,532
https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1550918/Python
class Solution: def smallestEqual(self, nums: List[int]) -> int: for i, n in enumerate(nums): if n == i % 10: return i return -1
smallest-index-with-equal-value
Python
blue_sky5
-1
42
smallest index with equal value
2,057
0.712
Easy
28,533
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1551353/Python-O(1)-memory-O(n)-time-beats-100.00
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: min_res = math.inf min_point = max_point = last_point = None prev_val = head.val head = head.next i = 1 while head.next: if ((head.next.val < head.val and prev_val < head.val) or (head.next.val > head.val and prev_val > head.val)): if min_point is None: min_point = i else: max_point = i if last_point: min_res = min(min_res, i - last_point) last_point = i prev_val = head.val i += 1 head = head.next if min_res == math.inf: min_res = -1 max_res = max_point - min_point if max_point else -1 return [min_res, max_res]
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python O(1) memory, O(n) time beats 100.00%
dereky4
1
125
find the minimum and maximum number of nodes between critical points
2,058
0.57
Medium
28,534
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/2246179/not-easy-to-understand-but-easy-solution-(90-faster)
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: arr,dist=[],[] diff=10 ** 5 index=0 while head: arr.append(head.val) head=head.next for i in range(1,len(arr)-1): if (arr[i-1] > arr[i] and arr[i+1] >arr[i]) or (arr[i-1] < arr[i] and arr[i]> arr[i+1]): dist.append(i) if index>=1: diff=min(diff,dist[index]-dist[index-1]) index+=1 if not dist or len(dist)==1:return [-1,-1] else: return [diff,dist[-1]-dist[0]]
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
not easy to understand, but easy solution (90% faster)
alenov
0
15
find the minimum and maximum number of nodes between critical points
2,058
0.57
Medium
28,535
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1552796/One-pass-100-speed
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: i = prev_val = first_critical_idx = prev_critical_idx = critical_idx = 0 min_diff = inf found_two_critical = False while head: if i == 0: prev_val = head.val elif head.next: new_critical = False if head.val < head.next.val: if head.val < prev_val: critical_idx = i new_critical = True elif head.val > head.next.val: if head.val > prev_val: critical_idx = i new_critical = True if new_critical: if not first_critical_idx: first_critical_idx = prev_critical_idx = critical_idx else: min_diff = min(min_diff, critical_idx - prev_critical_idx) prev_critical_idx = critical_idx found_two_critical = True prev_val = head.val head = head.next i += 1 return ([min_diff, critical_idx - first_critical_idx] if found_two_critical else [-1, -1])
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
One pass, 100% speed
EvgenySH
0
45
find the minimum and maximum number of nodes between critical points
2,058
0.57
Medium
28,536
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1551192/Python3-one-pass-O(1)-space
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: prev = head.val node = head.next dmin = inf first = i = last = 0 while node and node.next: i += 1 if prev < node.val > node.next.val or prev > node.val < node.next.val: if last : dmin = min(dmin, i - last) last = i # last critical point if not first: first = i # first critical point prev = node.val node = node.next return [dmin, last - first] if dmin < inf else [-1, -1]
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
[Python3] one-pass O(1) space
ye15
0
43
find the minimum and maximum number of nodes between critical points
2,058
0.57
Medium
28,537
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1550791/Python-3-(Self-Explanatory)
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: if not head: return [-1, -1] prev, curr = head, head.next idx = 1 res = [] while curr and curr.next: if self.is_critical(prev.val, curr.val, curr.next.val): res.append(idx) prev = curr curr = curr.next idx += 1 if len(res) <= 1: return [-1, -1] min_ = min(res[i] - res[i-1] for i in range(1, len(res))) max_ = res[-1] - res[0] return [min_, max_] def is_critical(self, prev, curr, nxt): return (prev > curr < nxt) or (prev < curr > nxt)
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python 3 (Self-Explanatory)
1nnOcent
0
21
find the minimum and maximum number of nodes between critical points
2,058
0.57
Medium
28,538
https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1561343/PythonSolution-beats-97-Find-Minimum-and-Max-No.-of-Nodes
class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: ''' 5->3->1->2->5->1->2 C C. C c = [2,4,5] ''' if head.next.next is None: return [-1,-1] def calc(head): prev = head temp = head.next while temp: next_node = temp.next if next_node is not None: if prev.val > temp.val < next_node.val or prev.val < temp.val > next_node.val: break prev,temp = temp,next_node else: break max_dis = 0 min_dis = pow(10,5)+1 count = 0 mi_count = pow(10,5)+1 while temp: next_node = temp.next if next_node is not None: if prev.val > temp.val < next_node.val or prev.val < temp.val > next_node.val: max_dis = count min_dis = min(min_dis,mi_count) mi_count = 0 count += 1 mi_count += 1 prev,temp = temp,next_node else: break if max_dis != 0 and min_dis != pow(10,5)+1: return [min_dis,max_dis] return [-1,-1] return calc(head)
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
[Python]Solution beats 97% - Find Minimum and Max No. of Nodes
SaSha59
-1
50
find the minimum and maximum number of nodes between critical points
2,058
0.57
Medium
28,539
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550007/Python3-bfs
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: ans = 0 seen = {start} queue = deque([start]) while queue: for _ in range(len(queue)): val = queue.popleft() if val == goal: return ans if 0 <= val <= 1000: for x in nums: for op in (add, sub, xor): if op(val, x) not in seen: seen.add(op(val, x)) queue.append(op(val, x)) ans += 1 return -1
minimum-operations-to-convert-number
[Python3] bfs
ye15
17
1,200
minimum operations to convert number
2,059
0.473
Medium
28,540
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550007/Python3-bfs
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: ans = 0 queue = deque([start]) visited = [False]*1001 while queue: for _ in range(len(queue)): val = queue.popleft() if val == goal: return ans if 0 <= val <= 1000 and not visited[val]: visited[val] = True for x in nums: for xx in (val+x, val-x, val^x): queue.append(xx) ans += 1 return -1
minimum-operations-to-convert-number
[Python3] bfs
ye15
17
1,200
minimum operations to convert number
2,059
0.473
Medium
28,541
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1551110/BFS-Approach-oror-Well-coded-oror-Easy-to-understand
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: if start==goal: return 0 q = [(start,0)] seen = {start} while q: n,s = q.pop(0) for num in nums: for cand in [n+num,n-num,n^num]: if cand==goal: return s+1 if 0<=cand<=1000 and cand not in seen: seen.add(cand) q.append((cand,s+1)) return -1
minimum-operations-to-convert-number
📌📌 BFS Approach || Well-coded || Easy-to-understand 🐍
abhi9Rai
5
198
minimum operations to convert number
2,059
0.473
Medium
28,542
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1549955/py3-Simple-BFS
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: seen = set() que = deque([(start, 0)]) while que: item, cnt = que.popleft() if item == goal: return cnt if item in seen: continue if item >= 0 and item <= 1000: for n in nums: que.append((item + n, cnt + 1)) que.append((item - n, cnt + 1)) que.append((item ^ n, cnt + 1)) seen.add(item) return -1
minimum-operations-to-convert-number
[py3] Simple BFS
mtx2d
3
196
minimum operations to convert number
2,059
0.473
Medium
28,543
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/2211975/python-3-or-bfs-or-O(n)O(1)
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: q = collections.deque([(start, 0)]) visited = {start} while q: x, count = q.popleft() count += 1 for num in nums: for newX in (x + num, x - num, x ^ num): if newX == goal: return count if newX < 0 or 1000 < newX or newX in visited: continue visited.add(newX) q.append((newX, count)) return -1
minimum-operations-to-convert-number
python 3 | bfs | O(n)/O(1)
dereky4
2
83
minimum operations to convert number
2,059
0.473
Medium
28,544
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1707143/Using-sets-for-new-numbers-84-speed
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: seen, level, ops = {start}, {start}, 0 while level: new_level = set() ops += 1 for x in level: for n in nums: for new_x in [x + n, x - n, x ^ n]: if new_x == goal: return ops elif 0 <= new_x <= 1000 and new_x not in seen: new_level.add(new_x) level = new_level seen.update(level) return -1
minimum-operations-to-convert-number
Using sets for new numbers, 84% speed
EvgenySH
0
63
minimum operations to convert number
2,059
0.473
Medium
28,545
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1551203/Python3-BFS-100
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: n = len(nums) que = [start] steps = 0 visited = set() while que: # print(que) nxt = [] for x in que: if x == goal: return steps if x in visited or x < 0 or x > 1000: continue visited.add(x) for i in range(n): nxt.append(x + nums[i]) nxt.append(x - nums[i]) nxt.append(x ^ nums[i]) steps += 1 que = nxt return -1
minimum-operations-to-convert-number
[Python3] BFS 100%
oliver33697
0
43
minimum operations to convert number
2,059
0.473
Medium
28,546
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1551106/Python-3-Two-head-BFS
class Solution: def minimumOperations(self, nums: List[int], start: int, target: int) -> int: n = len(nums) vis = defaultdict(lambda: float('inf'), {start: 0}) vis2 = defaultdict(lambda: float('inf'), {target: 0}) q = deque([(0, start, 0), (0, target, 1)]) nums = set(nums) while q: steps, cur, typ = q.popleft() if typ == 0: for x in nums: for ops in '+-^': if ops == '+': new = cur + x elif ops == '-': new = cur - x else: new = cur ^ x # new = eval(f"{cur}{ops}{x}") if new in vis2: return steps + 1 + vis2[new] if new > 1000 or new < 0: continue if vis[new] > steps + 1: vis[new] = steps + 1 q.append((steps + 1, new, typ)) else: for x in nums: for ops in '+-^': if ops == '+': new = cur + x elif ops == '-': new = cur - x else: new = cur ^ x # new = eval(f"{cur}{ops}{x}") if new in vis: return steps + 1 + vis[new] if new > 1000 or new < 0: continue if vis2[new] > steps + 1: vis2[new] = steps + 1 q.append((steps + 1, new, typ)) return -1
minimum-operations-to-convert-number
[Python 3] Two head BFS
chestnut890123
0
29
minimum operations to convert number
2,059
0.473
Medium
28,547
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550084/Python-Efficient-%22BFS%22-Using-Set
class Solution: def f(self, nums = [2,4,12], o = 2): r = set() for n in nums: r.update([o+n, o-n, o^n]) return r def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: seen = set() todo = set([start]) d = 1 while True: r = set() for n in todo: r.update(self.f(nums=nums, o=n)) if goal in r: return d r = set(e for e in r if e >= 0 and e <= 1000) todo = r - seen if len(todo) == 0: return -1 seen.update(r) d += 1
minimum-operations-to-convert-number
[Python] Efficient "BFS" Using Set
datafireball
0
36
minimum operations to convert number
2,059
0.473
Medium
28,548
https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550059/Python-Simple-BFS-solution
class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: nums.sort() q = collections.deque([(start, 0)]) visited = set() while q: for _ in range(len(q)): x, step = q.popleft() if x == goal: return step if x < 0 or x > 1000: continue if x in visited: continue visited.add(x) for num in nums: q.append((x+num, step+1)) q.append((x-num, step+1)) q.append((x^num, step+1)) return -1
minimum-operations-to-convert-number
[Python] Simple BFS solution
nightybear
0
24
minimum operations to convert number
2,059
0.473
Medium
28,549
https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/discuss/1550012/Python3-dp
class Solution: def possiblyEquals(self, s1: str, s2: str) -> bool: def gg(s): """Return possible length""" ans = [int(s)] if len(s) == 2: if s[1] != '0': ans.append(int(s[0]) + int(s[1])) return ans elif len(s) == 3: if s[1] != '0': ans.append(int(s[:1]) + int(s[1:])) if s[2] != '0': ans.append(int(s[:2]) + int(s[2:])) if s[1] != '0' and s[2] != '0': ans.append(int(s[0]) + int(s[1]) + int(s[2])) return ans @cache def fn(i, j, diff): """Return True if s1[i:] matches s2[j:] with given differences.""" if i == len(s1) and j == len(s2): return diff == 0 if i < len(s1) and s1[i].isdigit(): ii = i while ii < len(s1) and s1[ii].isdigit(): ii += 1 for x in gg(s1[i:ii]): if fn(ii, j, diff-x): return True elif j < len(s2) and s2[j].isdigit(): jj = j while jj < len(s2) and s2[jj].isdigit(): jj += 1 for x in gg(s2[j:jj]): if fn(i, jj, diff+x): return True elif diff == 0: if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False return fn(i+1, j+1, 0) elif diff > 0: if i == len(s1): return False return fn(i+1, j, diff-1) else: if j == len(s2): return False return fn(i, j+1, diff+1) return fn(0, 0, 0)
check-if-an-original-string-exists-given-two-encoded-strings
[Python3] dp
ye15
82
6,200
check if an original string exists given two encoded strings
2,060
0.407
Hard
28,550
https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/discuss/1550012/Python3-dp
class Solution: def possiblyEquals(self, s1: str, s2: str) -> bool: def gg(s): """Return possible length.""" ans = {int(s)} for i in range(1, len(s)): ans |= {x+y for x in gg(s[:i]) for y in gg(s[i:])} return ans @cache def fn(i, j, diff): """Return True if s1[i:] matches s2[j:] with given differences.""" if i == len(s1) and j == len(s2): return diff == 0 if i < len(s1) and s1[i].isdigit(): ii = i while ii < len(s1) and s1[ii].isdigit(): ii += 1 for x in gg(s1[i:ii]): if fn(ii, j, diff-x): return True elif j < len(s2) and s2[j].isdigit(): jj = j while jj < len(s2) and s2[jj].isdigit(): jj += 1 for x in gg(s2[j:jj]): if fn(i, jj, diff+x): return True elif diff == 0: if i < len(s1) and j < len(s2) and s1[i] == s2[j]: return fn(i+1, j+1, 0) elif diff > 0: if i < len(s1): return fn(i+1, j, diff-1) else: if j < len(s2): return fn(i, j+1, diff+1) return False return fn(0, 0, 0)
check-if-an-original-string-exists-given-two-encoded-strings
[Python3] dp
ye15
82
6,200
check if an original string exists given two encoded strings
2,060
0.407
Hard
28,551
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563707/Python3-sliding-window-O(N)
class Solution: def countVowelSubstrings(self, word: str) -> int: ans = 0 freq = defaultdict(int) for i, x in enumerate(word): if x in "aeiou": if not i or word[i-1] not in "aeiou": jj = j = i # set anchor freq.clear() freq[x] += 1 while len(freq) == 5 and all(freq.values()): freq[word[j]] -= 1 j += 1 ans += j - jj return ans
count-vowel-substrings-of-a-string
[Python3] sliding window O(N)
ye15
16
1,900
count vowel substrings of a string
2,062
0.659
Easy
28,552
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1594931/Python.-Time%3A-one-pass-O(N)-space%3A-O(1).-Not-a-sliding-window.
class Solution: def countVowelSubstrings(self, word: str) -> int: vowels = ('a', 'e', 'i', 'o', 'u') result = 0 start = 0 vowel_idx = {} for idx, c in enumerate(word): if c in vowels: if not vowel_idx: start = idx vowel_idx[c] = idx if len(vowel_idx) == 5: result += min(vowel_idx.values()) - start + 1 elif vowel_idx: vowel_idx = {} return result
count-vowel-substrings-of-a-string
Python. Time: one pass O(N), space: O(1). Not a sliding window.
blue_sky5
12
654
count vowel substrings of a string
2,062
0.659
Easy
28,553
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563978/Python3-One-line-Solution
class Solution: def countVowelSubstrings(self, word: str) -> int: return sum(set(word[i:j+1]) == set('aeiou') for i in range(len(word)) for j in range(i+1, len(word)))
count-vowel-substrings-of-a-string
[Python3] One-line Solution
leefycode
8
871
count vowel substrings of a string
2,062
0.659
Easy
28,554
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1574341/python-straightforward-solution
class Solution: def countVowelSubstrings(self, word: str) -> int: count = 0 current = set() for i in range(len(word)): if word[i] in 'aeiou': current.add(word[i]) for j in range(i+1, len(word)): if word[j] in 'aeiou': current.add(word[j]) else: break if len(current) == 5: count += 1 current = set() return count
count-vowel-substrings-of-a-string
python straightforward solution
mqueue
6
718
count vowel substrings of a string
2,062
0.659
Easy
28,555
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1564159/Python3-Sliding-Window-O(N)-with-explanations
class Solution: def countVowelSubstrings(self, word: str) -> int: result = 0 vowels = 'aeiou' # dictionary to record counts of each char mp = defaultdict(lambda: 0) for i, char in enumerate(word): # if the current letter is a vowel if char in vowels: mp[char] += 1 # if the previous letter is not a vowel, set the current point to a left point and a pivot if i == 0 or word[i-1] not in vowels: left = pivot = i # if all five vowels are founded, # try to calculate how many substrings that contain all five vowels using sliding window # window range is between the left point and the current i point # move the pivot to the right-side one by one, check if [pivot, i] contains all five vowels while len(mp) == 5 and all(mp.values()): mp[word[pivot]] -= 1 pivot += 1 result += (pivot - left) else: mp.clear() left = pivot = i+1 return result
count-vowel-substrings-of-a-string
[Python3] Sliding Window O(N) with explanations
idzhanghao
4
360
count vowel substrings of a string
2,062
0.659
Easy
28,556
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/2670441/Python
class Solution: def countVowelSubstrings(self, word: str) -> int: fin=0 for i in range(len(word)): res = set() for j in range(i,len(word)): if word[j] in 'aeiou': res.add(word[j]) if len(res)>=5: fin+=1 else: break return fin
count-vowel-substrings-of-a-string
Python
naveenraiit
1
97
count vowel substrings of a string
2,062
0.659
Easy
28,557
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1626076/Easy-python3-solution-using-counter
class Solution: def countVowelSubstrings(self, word: str) -> int: n=len(word) vowels="aeiou" from collections import Counter res=0 for i in range(n): for j in range(i+4,n): counter=Counter(word[i:j+1]) if all(counter[key]>=1 for key in vowels) and len(counter)==5: res+=1 return res
count-vowel-substrings-of-a-string
Easy python3 solution using counter
Karna61814
1
211
count vowel substrings of a string
2,062
0.659
Easy
28,558
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/2843354/Python3-using-Set
class Solution: def countVowelSubstrings(self, word: str) -> int: if len(word) < 5: return 0 result = 0 for i in range (len(word)-4): r = i + 5 while r <= len(word): if "".join(sorted(set(word[i:r]))) == "aeiou": result += 1 r += 1 return result
count-vowel-substrings-of-a-string
Python3 using Set
DNST
0
2
count vowel substrings of a string
2,062
0.659
Easy
28,559
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/2775965/Simple-approach-using-counter-%3A-)
class Solution: def countVowelSubstrings(self, word: str) -> int: # creating a list of vowels v = list('aeiou') # counter for vowels counter = { i: 0 for i in v } count = 0 # Outer loop runs 0 to n for i in range(len(word)): # checking either the current index doesn't exceed 5, cuz as condition says all vowels should be present, then it should > 5. if i + 5 > len(word): break # reseting the counter everytime dic = dict.copy(counter) # inner loop which runs from i to n for j in range(i, len(word)): # checking either the character is a vowel if word[j] in v: # if yes, incrementing the counter dic[word[j]] += 1 else: # if not, break the loop and reset counter dic = dict.copy(counter) break # fetching all values of hashmap val = dic.values() # if there is no zero in values of hashmap and sum of values exceed 5, for sure all vowels has been found if list(val).count(0) == 0 and sum(val) >= 5: count += 1 return count
count-vowel-substrings-of-a-string
Simple approach using counter : )
aadarshvelu
0
4
count vowel substrings of a string
2,062
0.659
Easy
28,560
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1798228/1-Line-Python-Solution-oror-30-Faster-oror-Memory-less-than-99
class Solution: def countVowelSubstrings(self, word: str) -> int: return sum(set(word[i:j]) == set('aeiou') for i in range(len(word)-4) for j in range(i+5,len(word)+1))
count-vowel-substrings-of-a-string
1-Line Python Solution || 30% Faster || Memory less than 99%
Taha-C
0
267
count vowel substrings of a string
2,062
0.659
Easy
28,561
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563878/Sliding-window-with-subset-check
class Solution: vowels = frozenset(["a", "e", "i", "o", "u"]) def countVowelSubstrings(self, word: str) -> int: n = len(word) counter = 0 for i in range(n - 4): end = i + 4 check = word[i:end+1] current = set(check) only_vowels = current.issubset(self.vowels) while only_vowels and end < n: if word[end] in self.vowels: current.add(word[end]) if current == self.vowels: counter += 1 end += 1 else: only_vowels = False return counter
count-vowel-substrings-of-a-string
Sliding window with subset check
0hh98h55f
0
86
count vowel substrings of a string
2,062
0.659
Easy
28,562
https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563777/Just-another-beginner's-Python3-solution
class Solution: def countVowels(self, word: str) -> int: vowels = ["a", "e", "i", "o", "u"] res = [] vowels_cop = set(vowels.copy()) for j in range(len(word)): if word[j] not in vowels: continue string = "" for i in range(j, len(word)): flag = False if word[i] in vowels: string += str(i) vowels_cop.discard(word[i]) if not vowels_cop: res.append(string) flag = True if not flag: string = "" vowels_cop = set(vowels.copy()) string = "" vowels_cop = set(vowels.copy()) print(len(set(res)))
count-vowel-substrings-of-a-string
Just another beginner's Python3 solution
WoodlandXander
0
229
count vowel substrings of a string
2,062
0.659
Easy
28,563
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564075/Detailed-explanation-of-why-(len-pos)-*-(pos-%2B-1)-works
class Solution: def countVowels(self, word: str) -> int: count = 0 sz = len(word) for pos in range(sz): if word[pos] in 'aeiou': count += (sz - pos) * (pos + 1) return count
vowels-of-all-substrings
Detailed explanation of why (len - pos) * (pos + 1) works
bitmasker
77
2,000
vowels of all substrings
2,063
0.551
Medium
28,564
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1563701/(i-%2B-1)-*-(sz-i)
class Solution: def countVowels(self, word: str) -> int: return sum((i + 1) * (len(word) - i) for i, ch in enumerate(word) if ch in 'aeiou')
vowels-of-all-substrings
(i + 1) * (sz - i)
votrubac
34
2,800
vowels of all substrings
2,063
0.551
Medium
28,565
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564031/Fastest-Python-Solution-or-108ms
class Solution: def countVowels(self, word: str) -> int: c, l = 0, len(word) d = {'a':1, 'e':1,'i':1,'o':1,'u':1} for i in range(l): if word[i] in d: c += (l-i)*(i+1) return c
vowels-of-all-substrings
Fastest Python Solution | 108ms
the_sky_high
5
270
vowels of all substrings
2,063
0.551
Medium
28,566
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1794416/Python-oror-Simple-Math-and-Combinatorics
class Solution: def countVowels(self, word: str) -> int: vows = set("aeiou") l = len(word) s = 0 for i in range(l): if word[i] in vows: s += (i + 1) * (l - i) return s
vowels-of-all-substrings
Python || Simple Math and Combinatorics
cherrysri1997
1
80
vowels of all substrings
2,063
0.551
Medium
28,567
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564858/Python-3-two-prefix-sums
class Solution: def countVowels(self, word: str) -> int: n = len(word) # mark vowel # 'aba' vowels = [1, 0, 1] vowels = list(map(lambda x: int(x in 'aeiou'), word)) # add vowel count in each substring # acc = [0, 1, 1, 2] acc = list(accumulate(vowels, initial=0)) # add up vowel count # acc2 = [0, 1, 2, 4] acc2 = list(accumulate(acc)) ans = 0 for i in range(n+1): # add up accumulative vowel count in substring start from index i ans += acc2[-1] - acc2[i] # subtract previous vowel counts from current substrings if i > 0: ans -= (acc[i-1]) * (len(acc2) - i) return ans
vowels-of-all-substrings
[Python 3] two prefix sums
chestnut890123
1
68
vowels of all substrings
2,063
0.551
Medium
28,568
https://leetcode.com/problems/vowels-of-all-substrings/discuss/2773836/Python3-or-O(n)-Solution
class Solution: def countVowels(self, word: str) -> int: counter = 0 ans = 0;n = len(word) for i in range(len(word)): if(word[i] in ["a","e","i","o","u"]): counter+=1 ans+=(i+1)*counter-(n-i-1)*counter return ans
vowels-of-all-substrings
Python3 | O(n) Solution
ty2134029
0
5
vowels of all substrings
2,063
0.551
Medium
28,569
https://leetcode.com/problems/vowels-of-all-substrings/discuss/2257479/python-3-or-simple-O(n)-time-O(1)-space-solution
class Solution: def countVowels(self, word: str) -> int: count = vowelIndexSum = 0 vowels = {'a', 'e', 'i', 'o', 'u'} for i, c in enumerate(word, start=1): if c in vowels: vowelIndexSum += i count += vowelIndexSum return count
vowels-of-all-substrings
python 3 | simple O(n) time, O(1) space solution
dereky4
0
143
vowels of all substrings
2,063
0.551
Medium
28,570
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1565085/Simple-formula-100-speed
class Solution: vowels = set("aeiou") def countVowels(self, word: str) -> int: len_word = len(word) return sum((i + 1) * (len_word - i) for i, c in enumerate(word) if c in Solution.vowels)
vowels-of-all-substrings
Simple formula, 100% speed
EvgenySH
0
60
vowels of all substrings
2,063
0.551
Medium
28,571
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564177/Python3-one-line-solution
class Solution: def countVowels(self, word: str) -> int: return sum((i+1)*(len(word)-i) for i, val in enumerate(word) if val in 'aeiou')
vowels-of-all-substrings
[Python3] one line solution
idzhanghao
0
34
vowels of all substrings
2,063
0.551
Medium
28,572
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564123/Python-Solution-Easy
class Solution: def countVowels(self, word: str) -> int: count = 0 vowel = ['a','e','i','o','u'] n = len(word) for i,x in enumerate(word): if x in vowel: count += (n-i)*(i+1) return count
vowels-of-all-substrings
[Python] Solution -Easy
SaSha59
0
50
vowels of all substrings
2,063
0.551
Medium
28,573
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1563876/Clean-and-Concise-oror-Well-Explained-oror-Easy-Approach
class Solution: def countVowels(self, word: str) -> int: vowel = "aeiou" n, res = len(word), 0 for i,c in enumerate(word): if c in vowel: res+=(n-i)*(i+1) return res
vowels-of-all-substrings
📌📌 Clean & Concise || Well-Explained || Easy Approach 🐍
abhi9Rai
0
40
vowels of all substrings
2,063
0.551
Medium
28,574
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1563837/Python3-greedy-1-line-O(N)
class Solution: def countVowels(self, word: str) -> int: return sum((i+1)*(len(word)-i) for i, x in enumerate(word) if x in "aeiou")
vowels-of-all-substrings
[Python3] greedy 1-line O(N)
ye15
0
61
vowels of all substrings
2,063
0.551
Medium
28,575
https://leetcode.com/problems/vowels-of-all-substrings/discuss/1626199/Easy-python3-solution-using-prefix-sum
class Solution: def countVowels(self, word: str) -> int: vowels="aeiou" n=len(word) prefix=[0] for s in word: prefix.append(prefix[-1]+ (s in vowels)) prefix.pop(0) total=sum(prefix) diff=0 res=total for i in range(1,n): diff+=prefix[i-1] res+=total-(n-i)*prefix[i-1]-diff return res
vowels-of-all-substrings
Easy python3 solution using prefix sum
Karna61814
-1
99
vowels of all substrings
2,063
0.551
Medium
28,576
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1563731/Python3-binary-search
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: lo, hi = 1, max(quantities) while lo < hi: mid = lo + hi >> 1 if sum(ceil(qty/mid) for qty in quantities) <= n: hi = mid else: lo = mid + 1 return lo
minimized-maximum-of-products-distributed-to-any-store
[Python3] binary search
ye15
9
296
minimized maximum of products distributed to any store
2,064
0.5
Medium
28,577
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1563991/Python-Binary-Search-with-explain
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: l, r = 1, max(quantities) while l <= r: mid = (l+r)//2 # count the number of stores needed if the max distribution is mid # one store can has max one product only and we need to distribute all the quantities cnt = 0 for x in quantities: # if 0<=x<=mid, cnt = 1, if mid<x<=2mid, cnt = 2 cnt += (x+mid-1)//mid # if with max distribution is mid, but number of stores needed is larger than actual stores n, then will need to increase the distribution, else we can further lower down the distribution. if cnt > n: l = mid + 1 else: r = mid - 1 return l
minimized-maximum-of-products-distributed-to-any-store
[Python] Binary Search with explain
nightybear
2
133
minimized maximum of products distributed to any store
2,064
0.5
Medium
28,578
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1563800/Heap-oror-Well-Explained-oror-Visualizable
class Solution: def minimizedMaximum(self, n, A): heap = [] for q in A: heapq.heappush(heap,(-q,1)) n-=1 while n>0: quantity,num_shops = heapq.heappop(heap) total = (-1)*quantity*num_shops num_shops+=1 n-=1 heapq.heappush(heap,(-1*(total/num_shops),num_shops)) return math.ceil(-heap[0][0]) **Thanks and Upvote if You like the Idea !! 🤞**
minimized-maximum-of-products-distributed-to-any-store
📌📌 Heap || Well-Explained || Visualizable 🐍
abhi9Rai
2
168
minimized maximum of products distributed to any store
2,064
0.5
Medium
28,579
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/2808229/Python-Readable-solution-using-the-bisect-library
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: search_range = range(1, max(quantities)) return bisect.bisect_left(search_range, 1, key=lambda x: self.canDistribute(n, quantities, x)) + 1 def canDistribute(self, n: int, quantities: List[int], k: int) -> bool: quantities_gt_k = [q for q in quantities if q > k] num_qs_lt_k = len(quantities) - len(quantities_gt_k) extra_shops = sum(math.ceil(q / k) for q in quantities_gt_k) min_num_shops = num_qs_lt_k + extra_shops return n >= min_num_shops
minimized-maximum-of-products-distributed-to-any-store
[Python] Readable solution using the bisect library
lefteris12
0
3
minimized maximum of products distributed to any store
2,064
0.5
Medium
28,580
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1564122/Python-binary-search
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: l, h = math.ceil(sum(quantities)/n), max(quantities) getCount = lambda x: sum(math.ceil(quantities[i]/x) for i in range(len(quantities))) while l < h: mid = l + (h - l)//2 # if getting a low count than number of shops reduce the distribution if getCount(mid) <= n: h = mid else: l = mid + 1 return l
minimized-maximum-of-products-distributed-to-any-store
Python binary search
abkc1221
0
47
minimized maximum of products distributed to any store
2,064
0.5
Medium
28,581
https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1580955/Binary-search-96-speed
class Solution: def minimizedMaximum(self, n: int, quantities: List[int]) -> int: left, right = 1, max(quantities) while left < right: middle = (left + right) // 2 if sum(ceil(q / middle) for q in quantities) > n: left = middle + 1 else: right = middle return right
minimized-maximum-of-products-distributed-to-any-store
Binary search, 96% speed
EvgenySH
-1
101
minimized maximum of products distributed to any store
2,064
0.5
Medium
28,582
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1564102/Python-DFS-and-BFS-solution
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: ans = 0 graph = collections.defaultdict(dict) for u, v, t in edges: graph[u][v] = t graph[v][u] = t def dfs(curr, visited, score, cost): if curr == 0: nonlocal ans ans = max(ans, score) for nxt, time in graph[curr].items(): if time <= cost: dfs(nxt, visited|set([nxt]), score+values[nxt]*(nxt not in visited), cost-time) dfs(0, set([0]), values[0], maxTime) return ans
maximum-path-quality-of-a-graph
[Python] DFS and BFS solution
nightybear
2
424
maximum path quality of a graph
2,065
0.576
Hard
28,583
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1564102/Python-DFS-and-BFS-solution
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: ans = 0 graph = collections.defaultdict(dict) for u,v,t in edges: graph[u][v] = t graph[v][u] = t # node, cost, visited, score q = collections.deque([(0, maxTime, set([0]), values[0])]) while q: curr, cost, visited, score = q.popleft() if curr == 0: ans = max(ans, score) for nxt, time in graph[curr].items(): if time > cost: continue q.append((nxt, cost-time, visited|set([nxt]), score + values[nxt]*(nxt not in visited))) return ans
maximum-path-quality-of-a-graph
[Python] DFS and BFS solution
nightybear
2
424
maximum path quality of a graph
2,065
0.576
Hard
28,584
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1563743/Python3-iterative-dfs
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: graph = [[] for _ in values] for u, v, t in edges: graph[u].append((v, t)) graph[v].append((u, t)) ans = 0 stack = [(0, values[0], 0, 1)] while stack: time, val, u, mask = stack.pop() if u == 0: ans = max(ans, val) for v, t in graph[u]: if time + t <= maxTime: if not mask &amp; 1<<v: stack.append((time+t, val+values[v], v, mask ^ 1<<v)) else: stack.append((time+t, val, v, mask)) return ans
maximum-path-quality-of-a-graph
[Python3] iterative dfs
ye15
2
210
maximum path quality of a graph
2,065
0.576
Hard
28,585
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/2812642/Python-BFS-%2B-Pruning-with-Dijktra
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: graph = defaultdict(list) for outgoing, incoming, distance in edges: graph[outgoing].append((incoming, distance)) graph[incoming].append((outgoing, distance)) # At each node, we have at most four possible moves # dp[loc][maxTime] = max(*[dp[adj][maxTime - dist(adj)] for adj in adjs], value[loc]) # as many unique nodes as possible.. # able to return to start # maximize value # compute shortest path from all nodes to 0 # dijktra distance_to_origin = defaultdict(lambda: inf) distance_to_origin[0] = 0 visited = set() to_visit = [(0, 0)] while len(to_visit) > 0: dist, cur = heappop(to_visit) if cur in visited or dist != distance_to_origin[cur]: continue for neighbor, distance in graph[cur]: if distance_to_origin[cur] + distance < distance_to_origin[neighbor]: distance_to_origin[neighbor] = distance_to_origin[cur] + distance heappush(to_visit, (distance_to_origin[neighbor], neighbor)) visited.add(cur) # start from 0, reach out (how to determine returnability?) # with the shortest path map, we can prune branches that cannot return to the start d = deque([(0, maxTime, set(), 0)]) best = values[0] while len(d) > 0: for _ in range(len(d)): cur, time, unique, val = d.popleft() if cur == 0: best = max(best, val) if distance_to_origin[cur] > time: # no way home continue for to, distance in graph[cur]: if distance > time: continue new_val = values[to] + val if to not in unique else val # Conditionally copy the unique set new_unique = set(unique) | set([to]) if to not in unique else unique d.append((to, time - distance, new_unique, new_val)) return best
maximum-path-quality-of-a-graph
Python BFS + Pruning with Dijktra
PIG208
0
5
maximum path quality of a graph
2,065
0.576
Hard
28,586
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/2206944/Python-DFS-Recursive
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: d = defaultdict(list) n = len(values) for edge in edges: d[edge[0]].append([edge[1], edge[2]]) d[edge[1]].append([edge[0], edge[2]]) visited = [0]*n ans = 0 def dfs(node, curTime, total): nonlocal ans if curTime > maxTime: return if visited[node] == 0: total+= values[node] if node == 0: if total > ans: ans = total visited[node] += 1 for vertex, time in d[node]: dfs(vertex, curTime + time, total) visited[node] -= 1 dfs(0, 0, 0) return ans
maximum-path-quality-of-a-graph
[Python] DFS Recursive
happysde
0
76
maximum path quality of a graph
2,065
0.576
Hard
28,587
https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1818481/Python-DFS-%2B-Djikstra-or-faster-than-88.89-1095ms
class Solution: def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int: graph = defaultdict(list) dist = defaultdict(int) parent = defaultdict(int) R2Bpath = defaultdict(list) for u, v, w in edges: graph[u].append( (v, w) ) graph[v].append( (u, w) ) ## calc Djik: Q[ (time, node, parent) ] Q = [ (0, 0, -1) ] while Q: time, node, par = heapq.heappop(Q) if node not in dist: dist[node] = time parent[node] = par for v, w in graph[node]: alt = time + w heapq.heappush(Q, (alt, v, node) ) ## get ancesters of each nodes for node in range(len(values)): if node in dist: curr = node while curr != -1: R2Bpath[node].append(curr) curr = parent[curr] def get_score(ancesters: List[int]) -> int: score = 0 for node in set(ancesters): score += values[node] return score self.maxScore = 0 def dfs(curr=0, cost=0, path=[0]): self.maxScore = max( self.maxScore, get_score(path+R2Bpath[curr]) ) for v, time in graph[curr]: if cost+time+dist[v] <= maxTime: dfs(v, cost+time, path+[v]) dfs() return self.maxScore
maximum-path-quality-of-a-graph
[Python] DFS + Djikstra | faster than 88.89%, 1095ms
ark10806
0
252
maximum path quality of a graph
2,065
0.576
Hard
28,588
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1576339/Python3-freq-table
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: freq = [0]*26 for x in word1: freq[ord(x)-97] += 1 for x in word2: freq[ord(x)-97] -= 1 return all(abs(x) <= 3 for x in freq)
check-whether-two-strings-are-almost-equivalent
[Python3] freq table
ye15
2
140
check whether two strings are almost equivalent
2,068
0.646
Easy
28,589
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2513742/Python-Concise-Array-Solution-No-CounterHash-Map-Beats-98
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: # make an array to track occurences for every letter of the # alphabet alphabet = [0]*26 # go through both words and count occurences # word 1 add and word 2 subtract # after this we have the differences for every letter for index in range(len(word1)): alphabet[ord(word1[index]) - 97] += 1 alphabet[ord(word2[index]) - 97] -= 1 # find min and max and check that it is less than three return min(alphabet) >= -3 and max(alphabet) <= 3
check-whether-two-strings-are-almost-equivalent
[Python] - Concise Array Solution - No Counter/Hash-Map - Beats 98%
Lucew
1
314
check whether two strings are almost equivalent
2,068
0.646
Easy
28,590
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2840266/Python-1-line%3A-Optimal-and-Clean-with-explanation-2-ways%3A-O(n)-time-and-O(1)-space
class Solution: # use two frequency counters. # O(n) time : O(26) = O(1) space def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: freq1, freq2 = Counter(word1), Counter(word2) for c,f in freq1.items(): if abs(f - freq2[c]) > 3: return False for c,f in freq2.items(): if abs(f - freq1[c]) > 3: return False return True
check-whether-two-strings-are-almost-equivalent
Python 1 line: Optimal and Clean with explanation - 2 ways: O(n) time and O(1) space
topswe
0
4
check whether two strings are almost equivalent
2,068
0.646
Easy
28,591
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2836607/Simple-python-solution-using-hashmap
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: dic1 = defaultdict(int) dic2 = defaultdict(int) for i in word1: dic1[i] += 1 for j in word2: dic2[j] += 1 for k,v in dic1.items(): if abs(v-dic2[k]) > 3: return False for k,v in dic2.items(): if abs(v-dic1[k]) > 3: return False else: return True
check-whether-two-strings-are-almost-equivalent
Simple python solution using hashmap
aruj900
0
5
check whether two strings are almost equivalent
2,068
0.646
Easy
28,592
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2829247/Python-Solution-explained-oror-HASHMAP
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: d1={} d2={} #FREQUENCIES OF WORD1 CHARACTERS for i in word1: if i in d1: d1[i]+=1 else: d1[i]=1 #FREQUENCIES OF WORD2 CHARACTERS for i in word2: if i in d2: d2[i]+=1 else: d2[i]=1 #CHECK IF EQUAL CHARACTERS OF WORD1 AND WORD2 HAVING FREQUENCY DIFFERENCE AT MOST 3 #AND IF CHARACTERS PRESENT IN d1 BUT NOT d2 ,CHECK FRQUENCY OF d1 CHARACTERS SHOULD BE AT MOST 3 #AS FREQUENCY - 0(COZ NOT PRESENT IN D2) for i in d1.keys(): if i in d2: if not(abs(d2[i]-d1[i])<=3): return False else: if not(d1[i]<=3): return False #IF CHARACTERS PRESENT IN d2 BUT NOT d1 ,CHECK FRQUENCY OF d2 CHARACTERS SHOULD BE AT MOST 3 #AS FREQUENCY - 0(COZ NOT PRESENT IN D1) for i in d2.keys(): if i not in d1: if not(d2[i]<=3): return False #REMOVED ALL FALSE CONDITIONS ABOVE, RETURN TRUE return True
check-whether-two-strings-are-almost-equivalent
Python Solution - explained || HASHMAP✔
T1n1_B0x1
0
6
check whether two strings are almost equivalent
2,068
0.646
Easy
28,593
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2705949/97-faster-easy-using-counter
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: f=list(set(word1+word2)) word1=Counter(word1) word2=Counter(word2) for i in f: k=word1[i] l=word2[i] if(abs(k-l)>3): return False return True
check-whether-two-strings-are-almost-equivalent
97% faster easy using counter
Raghunath_Reddy
0
37
check whether two strings are almost equivalent
2,068
0.646
Easy
28,594
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2674202/Frequency-%22Tug-of-War%22-Between-Two-Words-Without-a-Dictionary
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: counts = [0] * 26 for char1, char2 in zip(word1, word2): counts[ord(char1) - 97] += 1 counts[ord(char2) - 97] -= 1 return all(abs(count) <= 3 for count in counts)
check-whether-two-strings-are-almost-equivalent
Frequency "Tug of War" Between Two Words Without a Dictionary
kcstar
0
8
check whether two strings are almost equivalent
2,068
0.646
Easy
28,595
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2664075/Easy-Python-Solution-Using-Dictionary
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: dic1={} for i in word1: if i not in dic1: dic1[i]=1 else: dic1[i]+=1 dic2={} for i in word2: if i not in dic2: dic2[i]=1 else: dic2[i]+=1 for k,v in dic1.items(): if(abs(v-dic2.get(k,0)))>3: return False for k,v in dic2.items(): if(abs(v-dic1.get(k,0)))>3: return False return True
check-whether-two-strings-are-almost-equivalent
Easy Python Solution Using Dictionary
ankitr8055
0
11
check whether two strings are almost equivalent
2,068
0.646
Easy
28,596
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2646466/Python3-Just-Look-At-Each-Character-(Counter)
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: c1, c2 = Counter(word1), Counter(word2) for ch in set(word1+word2): if abs(c1[ch]-c2[ch]) > 3: return False return True
check-whether-two-strings-are-almost-equivalent
Python3 Just Look At Each Character (Counter)
godshiva
0
11
check whether two strings are almost equivalent
2,068
0.646
Easy
28,597
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2616741/Python-Simple-Python-Solution-By-Merging-Both-Word-or-92-Faster
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: merge_string = word1 + word2 for index in range(len(merge_string)): frequency_count_in_word1 = word1.count(merge_string[index]) frequency_count_in_word2 = word2.count(merge_string[index]) if abs(frequency_count_in_word1 - frequency_count_in_word2) > 3: return False return True
check-whether-two-strings-are-almost-equivalent
[ Python ] ✅✅ Simple Python Solution By Merging Both Word | 92% Faster 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
45
check whether two strings are almost equivalent
2,068
0.646
Easy
28,598
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2586448/Python-Using-two-lists-O(n)
class Solution: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: if len(word1) != len(word2): return False freq1 = [0] * 256 freq2 = [0] * 256 for char in word1: freq1[ord(char)] += 1 for char in word2: freq2[ord(char)] += 1 for i in range(len(freq1)): if abs(freq1[i] - freq2[i]) > 3: return False return True
check-whether-two-strings-are-almost-equivalent
Python - Using two lists - O(n)
aj1904
0
39
check whether two strings are almost equivalent
2,068
0.646
Easy
28,599