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/range-sum-of-bst/discuss/696795/Python3-Simple-Recursive-For-Beginners | class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
valid_vals = []
def search(root):
if root.val >= L and root.val<=R:
valid_vals.append(root.val)
if root.left:
search(root.left)
if root.right:
search(root.right)
search(root)
return sum(valid_vals) | range-sum-of-bst | Python3 Simple Recursive For Beginners | bradleydamato | 2 | 216 | range sum of bst | 938 | 0.854 | Easy | 15,200 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1926412/Python-easy-O(N)-solution | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
self.summ = 0
def dfs(root):
if not root:
return
if root.val >= low and root.val <= high:
self.summ += root.val
dfs(root.left)
dfs(root.right)
dfs(root)
return self.summ | range-sum-of-bst | Python easy O(N) solution | aashnachib17 | 1 | 177 | range sum of bst | 938 | 0.854 | Easy | 15,201 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1743200/Python-Recursion-solution-and-Iterative-solution | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
if root.val <= high and root.val >= low:
return root.val + self.rangeSumBST(root.right, low, high) + self.rangeSumBST(root.left, low, high)
else:
return self.rangeSumBST(root.right, low, high) + self.rangeSumBST(root.left, low, high) | range-sum-of-bst | Python Recursion solution and Iterative solution | sphilip1206 | 1 | 189 | range sum of bst | 938 | 0.854 | Easy | 15,202 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1743200/Python-Recursion-solution-and-Iterative-solution | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
q = deque()
q.append(root)
res = 0
while q: # q = [10]
node = q.popleft()
if node.val >= low and node.val <= high:
res += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return res | range-sum-of-bst | Python Recursion solution and Iterative solution | sphilip1206 | 1 | 189 | range sum of bst | 938 | 0.854 | Easy | 15,203 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1628001/Python-oror-Easy-Solution | class Solution:
def __init__(self):
self.sum = 0
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if root is None:
return
if root.val >= low and root.val <= high:
self.sum += root.val
self.rangeSumBST(root.left, low, high)
self.rangeSumBST(root.right, low, high)
return self.sum | range-sum-of-bst | Python || Easy Solution | naveenrathore | 1 | 52 | range sum of bst | 938 | 0.854 | Easy | 15,204 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1003420/Python3-Using-Only-Two-Variables-or-BFS | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
queue = [root]
sumi = 0
while queue:
if low <= queue[0].val <= high:
sumi += queue[0].val
if queue[0].left:
queue.append(queue[0].left)
if queue[0].right:
queue.append(queue[0].right)
queue.pop(0)
return sumi | range-sum-of-bst | [Python3] Using Only Two Variables | BFS | May-i-Code | 1 | 184 | range sum of bst | 938 | 0.854 | Easy | 15,205 |
https://leetcode.com/problems/range-sum-of-bst/discuss/942632/Python-Easy-Solutions | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if not root:
return 0
if root.val<low:
return self.rangeSumBST(root.right,low,high)
if root.val>high:
return self.rangeSumBST(root.left,low,high)
return root.val+self.rangeSumBST(root.left,low,high)+self.rangeSumBST(root.right,low,high) | range-sum-of-bst | Python Easy Solutions | lokeshsenthilkumar | 1 | 493 | range sum of bst | 938 | 0.854 | Easy | 15,206 |
https://leetcode.com/problems/range-sum-of-bst/discuss/942632/Python-Easy-Solutions | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if not root:
return 0
if root.val<low:
return self.rangeSumBST(root.right,low,high)
if root.val>high:
return self.rangeSumBST(root.left,low,high)
if root.val==low:
return root.val+self.rangeSumBST(root.right,low,high)
if root.val==high:
return root.val+self.rangeSumBST(root.left,low,high)
return root.val+self.rangeSumBST(root.left,low,high)+self.rangeSumBST(root.right,low,high) | range-sum-of-bst | Python Easy Solutions | lokeshsenthilkumar | 1 | 493 | range sum of bst | 938 | 0.854 | Easy | 15,207 |
https://leetcode.com/problems/range-sum-of-bst/discuss/485124/Python3-Iterative-DFS-and-BFS-solutions. | class Solution:
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
# Stack to keep track of nodes is key to iterative solution
stack = []
rangedSum = 0
# Check that tree is not empty (never specified edge case)
if root is None:
return 0
# Make root of tree the first node to check
stack.append(root)
# Iteratively simulate recursion by appending and popping stack until it is empty
while len(stack) > 0:
# Set up the next node to traverse
# stack.pop(0) will turn solution into BFS
root = stack.pop()
# Check if the solution is within range
if L <= root.val <= R:
# Add value to sum
rangedSum += root.val
# Set the both children to be explored, if they exist
if not root.left is None:
stack.append(root.left)
if not root.right is None:
stack.append(root.right)
# Some values within range may have parent nodes outside the desired range
else:
# Value is larger than R, but left child (and its children) may be less than R
if root.val >= L:
if not root.left is None:
stack.append(root.left)
# Value is smaller than L, but right child (and its children) may be greater than L
elif root.val <= R:
if not root.right is None:
stack.append(root.right)
# Return the sum of values within the given inclusive range
return rangedSum | range-sum-of-bst | Python3 Iterative DFS and BFS solutions. | jhacker | 1 | 397 | range sum of bst | 938 | 0.854 | Easy | 15,208 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2794969/Python3-recursive-6-liner-solution | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root: return 0
return (
(root.val if low <= root.val <= high else 0) +
Solution.rangeSumBST(self, root.left, low, high) +
Solution.rangeSumBST(self, root.right, low, high)
) | range-sum-of-bst | Python3 recursive 6 liner solution | lucabonagd | 0 | 1 | range sum of bst | 938 | 0.854 | Easy | 15,209 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2788351/Python-beats-90-(recursive-approach) | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root: return 0
lr = self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)
if root.val >= low and root.val <= high: return root.val + lr
return lr | range-sum-of-bst | Python beats 90% (recursive approach) | farruhzokirov00 | 0 | 2 | range sum of bst | 938 | 0.854 | Easy | 15,210 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2760973/Easy-preorder-python | class Solution:
def preOrder(self, root):
res = []
if root:
res.append(root.val)
res += self.preOrder(root.left)
res += self.preOrder(root.right)
return(res)
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
return sum(value for value in self.preOrder(root) if value <= high and value >= low) | range-sum-of-bst | Easy preorder python | vincentoldfriend | 0 | 2 | range sum of bst | 938 | 0.854 | Easy | 15,211 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2329433/Beats-78-Simple-Python-Solution-Recursion-DFS | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if root is None:
return 0
num = root.val if root.val >= low and root.val <= high else 0
return self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high) + num | range-sum-of-bst | Beats 78% - Simple Python Solution - Recursion / DFS | 7yler | 0 | 100 | range sum of bst | 938 | 0.854 | Easy | 15,212 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2271352/C%2B%2BPYTHON-Recursive-Solution | class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if(root == nullptr)
return 0;
if(root->val < low)
return rangeSumBST(root->right,low,high);
if(root->val > high)
return rangeSumBST(root->left,low,high);
return root->val + rangeSumBST(root->left,low,high) + rangeSumBST(root->right,low,high);
}
};
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
if root.val < low:
return self.rangeSumBST(root.right,low,high)
if root.val > high:
return self.rangeSumBST(root.left,low,high)
return root.val + self.rangeSumBST(root.right,low,high) + self.rangeSumBST(root.left,low,high) | range-sum-of-bst | [C++/PYTHON] Recursive Solution | Cyborg9303 | 0 | 54 | range sum of bst | 938 | 0.854 | Easy | 15,213 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2247926/Pythhon-Fast-Approach | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
sum1 = 0
def check(r):
sum1 = 0
if r and low<=r.val<=high:
sum1+= r.val
sum1+=check(r.left)
sum1+=check(r.right)
elif r and r.val>high:
sum1+=check(r.left)
elif r and r.val<low:
sum1+=check(r.right)
return sum1
return check(root) | range-sum-of-bst | Pythhon Fast Approach | harsh30199 | 0 | 15 | range sum of bst | 938 | 0.854 | Easy | 15,214 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2245113/Learning-how-to-solve-it-1-Liner-by-Python!! | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
a=self.rangeSumBST(root.left,low,high)
b=self.rangeSumBST(root.right,low,high)
# if root.val fit the range, return root.val + root.left's add + root.right's add
# if not, just return left child's and right child's add
if root.val>=low and root.val<=high:
return a+b+root.val
else:
return a+b | range-sum-of-bst | Learning how to solve it 1-Liner by Python!! | XRFXRF | 0 | 18 | range sum of bst | 938 | 0.854 | Easy | 15,215 |
https://leetcode.com/problems/range-sum-of-bst/discuss/2245113/Learning-how-to-solve-it-1-Liner-by-Python!! | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
return 0 if not root else self.rangeSumBST(root.left,low,high)+self.rangeSumBST(root.right,low,high)+root.val if root.val>=low and root.val<=high else self.rangeSumBST(root.left,low,high)+self.rangeSumBST(root.right,low,high) | range-sum-of-bst | Learning how to solve it 1-Liner by Python!! | XRFXRF | 0 | 18 | range sum of bst | 938 | 0.854 | Easy | 15,216 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1984140/Python-Solution-or-SubTree-Range-Checking-or-Recursive-or-Clean-Code | class Solution:
def __init__(self):
self.ans = 0
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if root is None:
return None
if root.val > high: # check in left subtree
return self.rangeSumBST(root.left,low,high)
if root.val < low: # check in right subtree
return self.rangeSumBST(root.right,low,high)
# in range
print(root.val)
self.ans += root.val
root.left = self.rangeSumBST(root.left,low,high)
root.right = self.rangeSumBST(root.right,low,high)
return self.ans | range-sum-of-bst | Python Solution | SubTree Range Checking | Recursive | Clean Code | Gautam_ProMax | 0 | 92 | range sum of bst | 938 | 0.854 | Easy | 15,217 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1825820/Python-BFS-and-DFS-solution | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
q = collections.deque([root])
ans = 0
while q:
for _ in range(len(q)):
node = q.popleft()
if node.val >= low and node.val <= high:
ans += node.val
# if node.val < low, meaning we don't have to check left anymore.
if node.left and node.val > low:
q.append(node.left)
# if node.val > high, meaning we don't have to check right anymore.
if node.right and node.val < high:
q.append(node.right)
return ans | range-sum-of-bst | Python BFS & DFS solution | johnnychang | 0 | 117 | range sum of bst | 938 | 0.854 | Easy | 15,218 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1825820/Python-BFS-and-DFS-solution | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
if root.val < low:
return self.rangeSumBST(root.right, low, high)
if root.val > high:
return self.rangeSumBST(root.left, low, high)
# if none of the conditions met, the node is within range
return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high) | range-sum-of-bst | Python BFS & DFS solution | johnnychang | 0 | 117 | range sum of bst | 938 | 0.854 | Easy | 15,219 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1646732/Easy-solution-Python | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
self.sum_=0
def inorder(root):
if root:
if root.val > low:
inorder(root.left)
if root.val >= low and root.val <= high:
self.sum_ += root.val
if root.val < high:
inorder(root.right)
inorder(root)
return self.sum_ | range-sum-of-bst | Easy solution Python | akshattrivedi9 | 0 | 40 | range sum of bst | 938 | 0.854 | Easy | 15,220 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1628251/Python3-Recursive-dfs-solution | class Solution:
def traversal(self, node, low, high):
if not node:
return 0
lv = rv = 0
if node.val > low:
lv = self.traversal(node.left, low, high)
if node.val < high:
rv = self.traversal(node.right, low, high)
return lv + rv + node.val if low <= node.val <= high else lv + rv
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
return self.traversal(root, low, high) | range-sum-of-bst | [Python3] Recursive dfs solution | maosipov11 | 0 | 17 | range sum of bst | 938 | 0.854 | Easy | 15,221 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1491070/Python-Solution-O(N)-understandable-for-beginners-like-me-!!! | class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
q=[root]
Sum=low+high
while q:
temp=q.pop(0)
if(temp.val>low and temp.val<high):
Sum+=temp.val
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
return Sum | range-sum-of-bst | Python Solution O(N) understandable for beginners like me !!! | kabiland | 0 | 179 | range sum of bst | 938 | 0.854 | Easy | 15,222 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1270298/Easy-to-Read-%2B-Intuitive-Python-Recursion-beats-96 | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
total = 0
def helper(node):
nonlocal total
if not node:
return
if node.val < low:
helper(node.right)
elif node.val > high:
helper(node.left)
else:
total += node.val
helper(node.left)
helper(node.right)
helper(root)
return total | range-sum-of-bst | Easy to Read + Intuitive Python Recursion beats 96% | Pythagoras_the_3rd | 0 | 130 | range sum of bst | 938 | 0.854 | Easy | 15,223 |
https://leetcode.com/problems/range-sum-of-bst/discuss/1172600/WEEB-DOES-PYTHON-BFS(BEATS-98.58) | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
queue, result = deque([root]), 0
while queue:
curNode = queue.popleft()
if low<=curNode.val<=high:
result+=curNode.val
if low <= curNode.val and curNode.left:
queue.append(curNode.left)
if curNode.val <= high and curNode.right:
queue.append(curNode.right)
return result | range-sum-of-bst | WEEB DOES PYTHON BFS(BEATS 98.58%) | Skywalker5423 | 0 | 221 | range sum of bst | 938 | 0.854 | Easy | 15,224 |
https://leetcode.com/problems/range-sum-of-bst/discuss/937049/Range-sum-BST-(Python-3) | class Solution:
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
cursum = 0
if root.val != None:
cursum = root.val if low <= root.val <= high else 0
if root.left and root.val >= low:
cursum += self.rangeSumBST(root.left, low, high)
if root.right and root.val <= high:
cursum += self.rangeSumBST(root.right, low, high)
return cursum | range-sum-of-bst | Range sum BST (Python 3) | smahamkl | 0 | 31 | range sum of bst | 938 | 0.854 | Easy | 15,225 |
https://leetcode.com/problems/minimum-area-rectangle/discuss/1888886/PYTHON-SOLUTION-oror-PASSED-ALL-CASES-oror-WELL-EXPLAINED-oror-EASY-SOL-oror | class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
x_axis = defaultdict(dict)
y_axis = defaultdict(dict)
d = {}
points.sort()
ans = float('inf')
for point in points:
x_axis[point[0]][point[1]] = True
y_axis[point[1]][point[0]] = True
d[(point[0],point[1])] = True
for point in points:
x1 = point[0]
y1 = point[1]
for y2 in x_axis[x1]:
if y2 == y1:continue
for x2 in y_axis[y2]:
if x2 == x1:continue
if (x2,y1) in d:
tmp = abs(x2-x1) * abs(y2-y1)
if tmp < ans : ans = tmp
return ans if ans!=float('inf') else 0 | minimum-area-rectangle | PYTHON SOLUTION || PASSED ALL CASES || WELL EXPLAINED || EASY SOL || | reaper_27 | 1 | 489 | minimum area rectangle | 939 | 0.53 | Medium | 15,226 |
https://leetcode.com/problems/minimum-area-rectangle/discuss/2169094/Python%3A-using-set | class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
xy = {}
for x, y in points:
if x not in xy:
xy[x] = set()
xy[x].add(y)
result = float('inf')
xs = list(xy.keys())
for i in range(len(xs)-1):
x1 = xs[i]
if len(xy[x1]) < 2:
continue
for j in range(i+1, len(xs)):
x2 = xs[j]
if len(xy[x2]) < 2:
continue
commonY = list(xy[x1]&xy[x2])
if len(commonY) < 2:
continue
commonY.sort()
for l in range(len(commonY)-1):
result = min(result, abs(x1-x2) * (commonY[l+1] - commonY[l]))
return result if result != float('inf') else 0 | minimum-area-rectangle | Python: using set | kailinshi1989 | 0 | 130 | minimum area rectangle | 939 | 0.53 | Medium | 15,227 |
https://leetcode.com/problems/minimum-area-rectangle/discuss/1885758/Python3-oror-need-help-ororall-test-cases-passed-but-took-too-longoror-O(n2) | class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
min_area = float('inf')
n = len(points)
#add all points in the set
points_set = set()
for pt in points:
points_set.add(tuple(pt))
for x in range(n):
for y in range(n):
#check if this 2 points are valid to make a diagonal
#X-axis = points[idx][0] Y-axis = points[idx][1]
if points[x][0] < points[y][0] and points[x][1] > points[y][1]:
#generate new pair
pt1 = (points[x][0],points[y][1])
pt2 = (points[y][0],points[x][1])
if pt1 in points_set and pt2 in points_set:
#we have the rectangle
area = (abs(points[x][0]-points[y][0])*abs(points[y][1]-points[x][1]))
min_area = min(min_area,area)
return min_area if min_area != float('inf') else 0 | minimum-area-rectangle | Python3 || need help ||all test cases passed, but took too long|| O(n^2) | s_m_d_29 | 0 | 110 | minimum area rectangle | 939 | 0.53 | Medium | 15,228 |
https://leetcode.com/problems/minimum-area-rectangle/discuss/958979/Python3-bottom-left-and-top-right-corners-O(N2) | class Solution:
def minAreaRect(self, points: List[List[int]]) -> int:
ans = inf
seen = {(x, y) for x, y in points}
for x, y in points:
for xx, yy in points:
if x != xx and y != yy and (x, yy) in seen and (xx, y) in seen:
ans = min(ans, abs((xx-x)*(yy-y)))
return ans if ans < inf else 0 | minimum-area-rectangle | [Python3] bottom-left & top-right corners O(N^2) | ye15 | 0 | 133 | minimum area rectangle | 939 | 0.53 | Medium | 15,229 |
https://leetcode.com/problems/distinct-subsequences-ii/discuss/1894186/PYTHON-SOL-oror-DP-oror-EXPLAINED-oror-FULL-APPROACH-EXPLAINED-oror-TLE-TO-OPTIMIZED-SOL-oror | class Solution:
def distinctSubseqII(self, s: str) -> int:
n = len(s)
MOD = 1000000007
dp = {}
def recursion(string,index):
ans = 1 if index > 0 else 0
used = {}
for idx in range(index,n):
if s[idx] in used:continue
used[s[idx]] = True
ans += recursion(string + s[idx] , idx + 1)
return ans
res = recursion("",0)%MOD
return res | distinct-subsequences-ii | PYTHON SOL || DP || EXPLAINED || FULL APPROACH EXPLAINED || TLE TO OPTIMIZED SOL || | reaper_27 | 0 | 102 | distinct subsequences ii | 940 | 0.443 | Hard | 15,230 |
https://leetcode.com/problems/distinct-subsequences-ii/discuss/1894186/PYTHON-SOL-oror-DP-oror-EXPLAINED-oror-FULL-APPROACH-EXPLAINED-oror-TLE-TO-OPTIMIZED-SOL-oror | class Solution:
def distinctSubseqII(self, s: str) -> int:
n = len(s)
dp = [0]*n
last = dict()
ans = 0
for i in range(n):
to_add = True
limit = -1
if s[i] in last:
to_add = False
limit = last[s[i]] - 1
tmp = 0
for j in range(i-1,limit,-1):
tmp += dp[j]
if to_add:tmp+=1
last[s[i]] = i
dp[i] = tmp
ans += dp[i]
return ans%1000000007 | distinct-subsequences-ii | PYTHON SOL || DP || EXPLAINED || FULL APPROACH EXPLAINED || TLE TO OPTIMIZED SOL || | reaper_27 | 0 | 102 | distinct subsequences ii | 940 | 0.443 | Hard | 15,231 |
https://leetcode.com/problems/distinct-subsequences-ii/discuss/1894186/PYTHON-SOL-oror-DP-oror-EXPLAINED-oror-FULL-APPROACH-EXPLAINED-oror-TLE-TO-OPTIMIZED-SOL-oror | class Solution:
def distinctSubseqII(self, s: str) -> int:
n = len(s)
dp = [0]*(n+1)
last = dict()
for i in range(n):
if s[i] in last:dp[i+1] = dp[i]*2 - dp[last[s[i]]-1]
else:dp[i+1] = dp[i]*2 + 1
last[s[i]] = i+1
return dp[-1]%1000000007 | distinct-subsequences-ii | PYTHON SOL || DP || EXPLAINED || FULL APPROACH EXPLAINED || TLE TO OPTIMIZED SOL || | reaper_27 | 0 | 102 | distinct subsequences ii | 940 | 0.443 | Hard | 15,232 |
https://leetcode.com/problems/distinct-subsequences-ii/discuss/1518644/Python3-dp | class Solution:
def distinctSubseqII(self, s: str) -> int:
freq = [0]*26
for i in reversed(range(len(s))): freq[ord(s[i])-97] = (1 + sum(freq)) % 1_000_000_007
return sum(freq) % 1_000_000_007 | distinct-subsequences-ii | [Python3] dp | ye15 | 0 | 116 | distinct subsequences ii | 940 | 0.443 | Hard | 15,233 |
https://leetcode.com/problems/valid-mountain-array/discuss/338636/Python-solution-using-Two-pointer-from-opposite-sides | class Solution:
def validMountainArray(self, A: List[int]) -> bool:
if len(A)<3:return False
l=len(A)
i,j=0,l-1
while i<j and A[i]<A[i+1]:
i+=1
while j>0 and A[j]<A[j-1]:
j-=1
if i==j and j!=l-1 and i!=0:return True
return False | valid-mountain-array | Python solution using Two pointer from opposite sides | ketan35 | 10 | 778 | valid mountain array | 941 | 0.335 | Easy | 15,234 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717948/Python-3-(250ms)-or-O(N)-and-O(1)-or-One-Pass-For-Loop-or-6-Lines-Only | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr)<=2 or max(arr)==arr[0] or max(arr)==arr[len(arr)-1]:
return False
f=True
for i in range(len(arr)-1):
if f and arr[i]>=arr[i+1]:
f=False
if not f and arr[i]<=arr[i+1]:
return False
return True | valid-mountain-array | Python 3 (250ms) | O(N) & O(1) | One Pass For Loop | 6 Lines Only | MrShobhit | 4 | 122 | valid mountain array | 941 | 0.335 | Easy | 15,235 |
https://leetcode.com/problems/valid-mountain-array/discuss/2022655/Python-or-Time%3A-O(n)-Space%3A-O(1)-or-using-max-value | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
max_num = max(arr)
# Edge cases --> if the slope of the mountain is strictly increasing/decreasing
if max_num == arr[len(arr) - 1] or max_num == arr[0]:
return False
max_found = False
for i in range(len(arr) - 1):
# We initially want the mountain to be increasing but
# once we find the max number, we want the mountain to decrease
if arr[i] == max_num:
max_found = True
if max_found and arr[i] <= arr[i + 1]:
return False
elif not max_found and arr[i] >= arr[i + 1]:
return False
return True | valid-mountain-array | Python | Time: O(n), Space: O(1) | using max value | user5622HA | 3 | 107 | valid mountain array | 941 | 0.335 | Easy | 15,236 |
https://leetcode.com/problems/valid-mountain-array/discuss/925441/Python3-beats-98.17-speed-and-100-memory | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
decreasestarted= False
#edge cases
if (len(arr)< 3): return False
if (arr[0]>arr[1]): return False
for i in range(len(arr)-1):
if (not decreasestarted):
if (arr[i]>=arr[i+1]):
decreasestarted = True
if (decreasestarted and arr[i]<=arr[i+1]):
return False
return True if decreasestarted else False | valid-mountain-array | Python3 beats 98.17% speed and 100% memory | antong95 | 2 | 264 | valid mountain array | 941 | 0.335 | Easy | 15,237 |
https://leetcode.com/problems/valid-mountain-array/discuss/1718693/Simple-python-solution-covered-all-end-cases | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
i=arr.index(max(arr))
if arr.count(max(arr))>=2:
return False
lst1=arr[:i:]
lst2=arr[i+1::]
if (sorted(lst1)!=lst1 or sorted(lst2,reverse=True)!=lst2) or (len(lst1)==0 or len(lst2)==0) :
return False
dict1=collections.Counter(lst1)
dict2=collections.Counter(lst2)
for key,val in dict1.items():
if val>=2:
return False
for key,val in dict2.items():
if val>=2:
return False
return True | valid-mountain-array | Simple python solution covered all end cases | amannarayansingh10 | 1 | 48 | valid mountain array | 941 | 0.335 | Easy | 15,238 |
https://leetcode.com/problems/valid-mountain-array/discuss/1274222/Python3-simple-%22single-pass%22-solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
i = arr.index(max(arr))
if i == 0 or i == len(arr)-1:
return False
j = 1
while j < len(arr)-1:
if (j <= i and arr[j] <= arr[j-1]) or (j >= i and arr[j] <= arr[j+1]):
return False
j += 1
return True | valid-mountain-array | Python3 simple "single-pass" solution | EklavyaJoshi | 1 | 80 | valid mountain array | 941 | 0.335 | Easy | 15,239 |
https://leetcode.com/problems/valid-mountain-array/discuss/1264425/python3-clean-and-easy-solution-TC%3AO(N) | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
top = arr.index(max(arr))
if len(arr)<3 or top == len(arr)-1 or top == 0:
return False
return all(arr[i]<arr[i+1] for i in range(top)) and all(arr[i]>arr[i+1] for i in range(top,len(arr)-1)) | valid-mountain-array | python3 clean & easy solution TC:O(N) | Rei4126 | 1 | 164 | valid mountain array | 941 | 0.335 | Easy | 15,240 |
https://leetcode.com/problems/valid-mountain-array/discuss/1176511/Python-breakpoint-set-solution-easy-to-understand-faster-than-99 | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
n = len(arr)
if n < 3 or arr[0] >= arr[1]:
# if size of arr < 3 or zeroth index has value greater than 1st index
return False
breakpoint = -1 # we need to find the breakpoint, where graph goes downards, if it exists, so initially set it to -1
for i in range(n-1):
# check whether current index has value greater than it's next index, if it is, set this as the breakpoint
if arr[i] >= arr[i+1]:
breakpoint = i
break
# We need to check the condition, where there is no breakpoint meaning graph is increasing in it's whole life
if breakpoint == -1:
return False
# run the loop after the breakpoint, and check whether there exists any index i which has value greater than i-1
# if there is, we know, graph is not strictly decreasing anymore, which is invalid
for i in range(breakpoint+1, n):
if arr[i] >= arr[i-1]:
return False
return True | valid-mountain-array | Python breakpoint set solution, easy to understand, faster than 99% | kakkarotssj | 1 | 91 | valid mountain array | 941 | 0.335 | Easy | 15,241 |
https://leetcode.com/problems/valid-mountain-array/discuss/1146314/Python-solution%3A-really-easy-to-follow-and-maintain | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# Guard clause for minimum 3 in a mountain
if len(arr) < 3:
return False
# Guard clause for no repeat neighbors
for i in range(len(arr)-1):
if arr[i] == arr[i+1]:
return False
# Index of max value
max_idx = arr.index(max(arr))
# Check if max occurs at the ends
if max_idx == 0 or max_idx == len(arr)-1:
return False
# Separate the mountain left / right
increases = arr[0:max_idx]
decreases = arr[max_idx:]
# Check increases
if increases != sorted(increases):
return False
# Check decreases
if decreases != sorted(decreases, reverse=True):
return False
return True | valid-mountain-array | Python solution: really easy to follow and maintain | OliviaW373 | 1 | 120 | valid mountain array | 941 | 0.335 | Easy | 15,242 |
https://leetcode.com/problems/valid-mountain-array/discuss/1082904/Python-one-for-loop | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3 or arr[0] >= arr[1] or arr[-2] <= arr[-1]:
return False
else:
m = x = 1
for i in range(1, len(arr) - 1):
if arr[i] < arr[i + 1] and m == 1:
m = 1
elif arr[i] > arr[i + 1]:
m = 0
else:
x = 2
return True if m == 0 and x == 1 else False | valid-mountain-array | [Python] one for loop | angelique_ | 1 | 76 | valid mountain array | 941 | 0.335 | Easy | 15,243 |
https://leetcode.com/problems/valid-mountain-array/discuss/1062435/Python-easy-solution-beats-98 | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
ind = arr.index(max(arr))
if ind==0 or ind==len(arr)-1 or len(arr)<3: return False
for i in range(ind-1):
if arr[i]>=arr[i+1]: return False
for i in range(ind,len(arr)-1):
if arr[i]<=arr[i+1]: return False
return True | valid-mountain-array | Python easy solution, beats 98% | zzj8222090 | 1 | 124 | valid mountain array | 941 | 0.335 | Easy | 15,244 |
https://leetcode.com/problems/valid-mountain-array/discuss/1050492/PythonPython3-Valid-Mountain-Array | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# using two elements to keep a memory of past ascent or descent
up = [None, None]
down = [None, None]
for idx in range(len(arr) - 1):
# return False if the adjacent elements are of same value
if arr[idx] == arr[idx+1]:
return False
# change the values when the ascent of the mountain begins
elif arr[idx] < arr[idx+1] and not up[0]:
up[0] = 1
down[0] = 0
# return False if the descent has begun and we encounter an ascent
elif arr[idx] < arr[idx+1] and down[1]:
return False
# change the values when the descent begins
elif arr[idx] > arr[idx+1] and up[0]:
down[1] = 1
up[1] = 0
# up[0], down[0] = 1, 0
# return False if we get a descent before an ascent
elif arr[idx] > arr[idx+1] and not down[1]:
return False
# first condition is when there is only increasing elements
# second condition is when there is only decreasing elements
if (up[0] == 1 and up[1] == None) or (up[0] == None and up[1] == None):
return False
else:
return True | valid-mountain-array | [Python/Python3] Valid Mountain Array | newborncoder | 1 | 213 | valid mountain array | 941 | 0.335 | Easy | 15,245 |
https://leetcode.com/problems/valid-mountain-array/discuss/890862/Python3-Solution-Beats-92 | class Solution:
def validMountainArray(self, A: List[int]) -> bool:
if len(A) < 3:
return False
if A[0] > A[1]:
return False
updown = 0
direction = 1 # if direction = 1 it is up if direction = 0 it is going down
for i in range(1,len(A)):
if A[i] == A[i-1]:
return False
if direction:
if A[i] < A[i-1]:
direction = 0
updown += 1
else:
if A[i] > A[i-1]:
return False
if updown:
return True
return False | valid-mountain-array | Python3 Solution Beats 92% | leader21 | 1 | 64 | valid mountain array | 941 | 0.335 | Easy | 15,246 |
https://leetcode.com/problems/valid-mountain-array/discuss/356330/Solution-in-Python-3-(two-lines) | class Solution:
def validMountainArray(self, A: List[int]) -> bool:
s, L = [(A[i+1]>A[i]) - (A[i+1]<A[i]) for i in range(len(A)-1)], len(A)
return (1 in s and -1 in s and 0 not in s) and (s.index(-1) + s[::-1].index(1) == L - 1)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | valid-mountain-array | Solution in Python 3 (two lines) | junaidmansuri | 1 | 517 | valid mountain array | 941 | 0.335 | Easy | 15,247 |
https://leetcode.com/problems/valid-mountain-array/discuss/2841072/Best-Python-solution-(168-ms-b.87.82) | class Solution(object):
def validMountainArray(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
len_ = len(arr) - 1
i = 0
# walk up
while i < len_ and arr[i + 1] > arr[i]:
i += 1
# peak can't be first or last index
if i == 0 or i == len_:
return False
# walk down
while i < len_ and arr[i] > arr[i + 1]:
i += 1
return i == len_ | valid-mountain-array | Best Python solution - (168 ms, b.87.82%) | Nematulloh | 0 | 4 | valid mountain array | 941 | 0.335 | Easy | 15,248 |
https://leetcode.com/problems/valid-mountain-array/discuss/2824231/An-O(n)-soln-beats-82-in-time-67-in-mem | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# array size less than '3' is not valid
if len(arr) < 3: return False
# we start with up mode
down = False
for i in range(1, len(arr)):
# if we are in up more and a downward value change
if arr[i-1] > arr[i] and not down:
if i > 1: down = True # we've hit the pick
else: return False
# never ever we expect consecutive equal values
elif arr[i-1] == arr[i]: return False
# we are in down mode and an upward value change
elif arr[i-1] < arr[i] and down: return False
# we must be at down mode by now
return down | valid-mountain-array | An O(n) soln, beats 82% in time, 67% in mem | Aritram | 0 | 2 | valid mountain array | 941 | 0.335 | Easy | 15,249 |
https://leetcode.com/problems/valid-mountain-array/discuss/2811782/PYTHON-SOLUTION-EASY-TO-UNDERSTAND | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr)<3:
return False
store=0
for i in range(len(arr)-1):
if arr[i]>=arr[i+1]:
store=i
break
if store==len(arr)-1 or store==0:
return False
for i in range(store,len(arr)-1):
if arr[i]<=arr[i+1]:
return False
return True | valid-mountain-array | PYTHON SOLUTION - EASY TO UNDERSTAND | T1n1_B0x1 | 0 | 2 | valid mountain array | 941 | 0.335 | Easy | 15,250 |
https://leetcode.com/problems/valid-mountain-array/discuss/2807720/python3-brute-force | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
inc,dec = 0,0
if len(arr) < 3:
return False
for i in range(len(arr)-1):
if arr[i] < arr[i+1] and dec == 0:
inc += 1
elif inc > 0 and arr[i] > arr[i+1]:
dec += 1
else:
return False
break
return dec != 0 | valid-mountain-array | python3 brute force | BhavyaBusireddy | 0 | 1 | valid mountain array | 941 | 0.335 | Easy | 15,251 |
https://leetcode.com/problems/valid-mountain-array/discuss/2776245/Python-solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3:
return False
start = 0
end = len(arr) - 1
while arr[start] < arr[start+1] and start < len(arr) - 2:
start += 1
while arr[end] < arr[end - 1]:
end -= 1
if start == end and start != 0 and end != 0:
return True
else:
return False | valid-mountain-array | Python solution | zhi90 | 0 | 4 | valid mountain array | 941 | 0.335 | Easy | 15,252 |
https://leetcode.com/problems/valid-mountain-array/discuss/2749907/Simple-Python-Solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr)<3:
return False
if arr.count(max(arr)) > 1:
return False
x = arr.index(max(arr))
if x == 0 or x == len(arr)-1:
return False
for i in range(1,x):
if arr[i] <= arr[i-1]:
return False
for i in range(x+1, len(arr)):
if arr[i] >= arr[i-1]:
return False
return True | valid-mountain-array | Simple Python Solution | imkprakash | 0 | 3 | valid mountain array | 941 | 0.335 | Easy | 15,253 |
https://leetcode.com/problems/valid-mountain-array/discuss/2749160/easy-approach!! | class Solution:
def validMountainArray(self, A: List[int]) -> bool:
if(len(A) < 3):
return False
i = 1
while(i<len(A) and A[i] > A[i-1]):
i += 1
if(i==1 or i == len(A)):
return False
while(i<len(A) and A[i] < A[i-1]):
i+=1
return i==len(A) | valid-mountain-array | easy approach!! | sanjeevpathak | 0 | 2 | valid mountain array | 941 | 0.335 | Easy | 15,254 |
https://leetcode.com/problems/valid-mountain-array/discuss/2667281/Python-solution-O(n)-time-O(1)-space | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
def isStrictlyInc(arr, highPt) -> int:
for i in range(0, len(arr) - 1):
if arr[i] < arr[i + 1]:
highPt = i + 1
else:
break
return highPt
def isStrictlyDec(arr, highPt) -> bool:
res = True
for i in range(highPt, len(arr)-1):
if arr[i] <= arr[i + 1]:
res = False
break
return res
highPt = isStrictlyInc(arr, -1)
if 0 <= highPt < len(arr) - 1:
return isStrictlyDec(arr, highPt)
else:
return False | valid-mountain-array | Python solution O(n) time, O(1) space | cat_woman | 0 | 3 | valid mountain array | 941 | 0.335 | Easy | 15,255 |
https://leetcode.com/problems/valid-mountain-array/discuss/2640413/Solution-for-Python | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
flag1 = -1
flag2 = -1
for i in range(len(arr) - 1):
if arr[i] >= arr[i + 1]:
flag1 = i
break
for i in range(len(arr) - 1, 0, -1):
if arr[i - 1] <= arr[i]:
flag2 = i
break
if flag1 == flag2 and flag1 != -1:
return True
return False | valid-mountain-array | Solution for Python | Anonymous84 | 0 | 5 | valid mountain array | 941 | 0.335 | Easy | 15,256 |
https://leetcode.com/problems/valid-mountain-array/discuss/2542586/Python-naive-and-beginner-approach-90%2B-(with-comment) | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# valid mountain must be > 3 in length
if len(arr) < 3:
return False
# initialize previous index and tipping point
prev = 0
tipping_point = -1
for i, n in enumerate(arr):
if i == 0:
continue
# if value is the same then it is not strictly increaseing/decreasing
# hence not a mountain
if arr[prev] == n:
return False
# if tipping point has yet to be found, search for it
if tipping_point == -1:
# tipping point exist if value start to decrease
if arr[prev] > n:
tipping_point = prev
# however if tipping point index is 0 then it never increaase
# hence it is not a mountain
if tipping_point == 0:
return False
else:
# if value is increasing again then it is not a mountain
if arr[prev] < n:
return False
prev = i
# last check if tipping point has been found
# not found means that tipping point has -1 as index
return tipping_point > 0 | valid-mountain-array | Python naive and beginner approach 90%+ (with comment) | theRealSandro | 0 | 40 | valid mountain array | 941 | 0.335 | Easy | 15,257 |
https://leetcode.com/problems/valid-mountain-array/discuss/2418920/python3-O(n)-solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
'''
1. length should >= 3
2. max height must not appear in begining or end of array
3. must not appear consecutive same height
4. must not appear any concave valley
'''
max_height = max(arr)
if len(arr) < 3 or max_height == arr[0] or max_height == arr[-1]:
return False
idx = 1
while idx < len(arr)-1:
if arr[idx-1] == arr[idx] or arr[idx] == arr[idx+1]:
return False
elif arr[idx-1] > arr[idx] and arr[idx] < arr[idx+1]:
return False
idx += 1
return True
# TC = O(n)
# SC = O(1) | valid-mountain-array | python3 O(n) solution | hwf87 | 0 | 15 | valid mountain array | 941 | 0.335 | Easy | 15,258 |
https://leetcode.com/problems/valid-mountain-array/discuss/2366660/Python-easy-O(n)-with-explanation | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
l = len(arr)
if l <3: # 1st length condition, we need minimum 3
return False
if arr[0]>=arr[1]: # 2nd if first element > second, its not stricting increasing
return False
i = 1
peak=0
while i < (l-1):
if (arr[i] > arr[i-1]) and (arr[i] > arr[i+1]): #peak condition
if peak==1: # 3rd we need only one peak
return False
peak+=1
if arr[i]==arr[i+1] or arr[i-1]==arr[i]: #4th no adjacent elements shall be equal
return False
if (peak==1) and (arr[i+1]>arr[i]): #5th if last element is more than second last, its not strictly decreasing
return False
i+=1
if peak==1: #6th we need at least 1 peak
return True
return False | valid-mountain-array | Python easy O(n) with explanation | sunakshi132 | 0 | 36 | valid mountain array | 941 | 0.335 | Easy | 15,259 |
https://leetcode.com/problems/valid-mountain-array/discuss/2325834/Easy-Simple-1-Pass-Using-For-Loop-Beats-98 | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
#SOLUTION: we use a boolean "increasing" to mark what stage of the mountain we are at. we can only go up if the bool is None (at the start) or True (we are currently increasing). We can only go down if increasing is True (when we first start going down) or False (we are currently going down). Basically, increasing != None when we are going down. Any other condition we return false
increasing = None
for i in range(len(arr) - 1):
if (increasing == None or increasing == True) and arr[i] < arr[i + 1]:
increasing = True
elif increasing != None and arr[i] > arr[i + 1]:
increasing = False
else:
return False
#CHECK JUST IN CASE len(arr) = 1 such as [2], since it should return False
return True if increasing == False else False
return True if increasing == False else False | valid-mountain-array | Easy, Simple 1 Pass Using For Loop Beats 98% | yaahallo | 0 | 46 | valid mountain array | 941 | 0.335 | Easy | 15,260 |
https://leetcode.com/problems/valid-mountain-array/discuss/2313545/Python3-Two-solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# Simulation O(N)
n = len(arr)
if n < 3:
return False
pivot = -1
for i in range(1, n):
if arr[i] == arr[i-1]:
return False
elif arr[i] < arr[i-1]:
pivot = i-1
break
if pivot in [-1, 0, n]:
return False
for i in range(pivot+1, n):
if arr[i-1] <= arr[i]:
return False
return True
#O(n) (Idea taken from Discussion)
# Two people start from both side of mountain and keep on climbing, till they reach the top.
# If they are at same top, there is only one maxima and its a valid mountain array
n = len(arr)-1
p1, p2 = 0, len(arr)-1
while p1+1 <= n and arr[p1] < arr[p1+1]:
p1 += 1
while p2 - 1 >= 0 and arr[p2] < arr[p2-1]:
p2 -= 1
return 0 < p1 == p2 < n | valid-mountain-array | [Python3] Two solution | Gp05 | 0 | 22 | valid mountain array | 941 | 0.335 | Easy | 15,261 |
https://leetcode.com/problems/valid-mountain-array/discuss/2262752/Python3-Easy-Solution-O(n) | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
n = len(arr)
point1, point2 = 0, n-1
for i in range(n-1):
if arr[i+1] == arr[i]:
return False
elif arr[i+1] < arr[i]:
point1 = i
break
for i in range(n-1, -1, -1):
if arr[i-1] == arr[i]:
return False
if arr[i-1] <= arr[i]:
point2 = i
break
if point1 == point2 and point1 !=0 and point2 != n-1:
return True | valid-mountain-array | Python3 -- Easy Solution O(n) | code_sakshu | 0 | 36 | valid mountain array | 941 | 0.335 | Easy | 15,262 |
https://leetcode.com/problems/valid-mountain-array/discuss/2013046/Python-Climb-the-Mountain-Clean-and-Simple! | class Solution:
def validMountainArray(self, nums):
n = len(nums)
climbed = peakReached = False
for i in range(1,n):
prevNum, num = nums[i-1], nums[i]
if num == prevNum: return False
elif not peakReached:
if num > prevNum: climbed = True
elif prevNum > num: peakReached = True
else:
if num > prevNum: return False
return climbed and peakReached | valid-mountain-array | Python - Climb the Mountain - Clean and Simple! | domthedeveloper | 0 | 64 | valid mountain array | 941 | 0.335 | Easy | 15,263 |
https://leetcode.com/problems/valid-mountain-array/discuss/1905115/Python-Solution-O(n) | class Solution(object):
def validMountainArray(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
# Find peak
max_val = max(arr)
# check whether peak doesn't occur on ends
if max_val == arr[0] or max_val == arr[len(arr)-1]:
return False
i = 0
# check strictly increasing from start till peak
while(arr[i] != max_val):
if arr[i] < arr[i+1]:
i += 1
else:
return False
# check if pointer reached the peak
if arr[i] == max_val:
# check strictly decreasing after peak till end
while(i < len(arr)-1):
if arr[i] > arr[i+1]:
i += 1
else:
return False
return True | valid-mountain-array | Python Solution O(n) | Mallikarjun_5685 | 0 | 58 | valid mountain array | 941 | 0.335 | Easy | 15,264 |
https://leetcode.com/problems/valid-mountain-array/discuss/1874925/daily-leetcoding | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
for i in range(1, len(arr)):
if not arr[i] > arr[i - 1]:
current = i
break
else:
return False
if current == 1: return False
for i in range(current, len(arr)):
if not arr[i] < arr[i - 1]:
return False
else:
return True | valid-mountain-array | daily leetcoding | kaixliu | 0 | 15 | valid mountain array | 941 | 0.335 | Easy | 15,265 |
https://leetcode.com/problems/valid-mountain-array/discuss/1807286/Simple-Python-Solution-oror-90-Faster-oror-90-Less-Memory | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr)<3 or arr[0]>arr[1]: return False
for i in range(len(arr)-1):
if arr[i]==arr[i+1]: return False
if arr[i]>arr[i+1]: arr=arr[i:] ; break
for j in range(len(arr)-1):
if arr[j]<=arr[j+1]: return False
return True | valid-mountain-array | Simple Python Solution || 90% Faster || 90% Less Memory | Taha-C | 0 | 85 | valid mountain array | 941 | 0.335 | Easy | 15,266 |
https://leetcode.com/problems/valid-mountain-array/discuss/1719265/Easy-python-solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr)<3:
return False
c=0
m=arr.index(max(arr))
if m==0 or m==len(arr)-1:
return False
for i in range(0,m):
if arr[i]>=arr[i+1]:
c=1
for i in range(m,len(arr)-1):
if arr[i]<=arr[i+1]:
c=1
if c==0:
return True | valid-mountain-array | Easy python solution | FaizanAhmed_ | 0 | 31 | valid mountain array | 941 | 0.335 | Easy | 15,267 |
https://leetcode.com/problems/valid-mountain-array/discuss/1719126/Python3-solution-two-pointer-approach | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) <3:
return False
s = 0
e = len(arr)-1
while(s<e):
if arr[s+1] > arr[s]:
s = s + 1
elif arr[e-1] > arr[e]:
e = e - 1
else:
return False
if s == e and s != (len(arr)-1) and e != 0:
return True
else:
return False | valid-mountain-array | Python3 solution - two pointer approach | KratikaRathore | 0 | 15 | valid mountain array | 941 | 0.335 | Easy | 15,268 |
https://leetcode.com/problems/valid-mountain-array/discuss/1718616/Valid-Mountain-array-or-python-or-explained-or | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# if length of the array is less than 3 then it cant be a valid mountain
if len(arr) < 3: return False
# if first element is greater than second element then its not a valid mountain
if arr[0] > arr[1]: return False
for i in range(len(arr)-1):
# iterate till there is point of deviation
if arr[i] < arr[i+1]:
continue
else:
# if no deviation found for second time return True 'its a valid mountain'
# else return False
for i in range(i, len(arr)-1):
if arr[i] > arr[i+1]:
continue
else:
return False
return True | valid-mountain-array | Valid Mountain array | python | explained | | shashank_k_y | 0 | 15 | valid mountain array | 941 | 0.335 | Easy | 15,269 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717806/faster-than-89.80-Valid-Mountain-Array-or-Python | class Solution:
def validMountainArray(self, arr):
m = max(arr)
if arr[0] == m:
return False
if arr[-1] == m:
return False
status = 0
for i in range(len(arr)):
if arr[i] == m:
status = 1
if status == 0:
if arr[i] < arr[i+1]:
continue
else:
return False
if status == 1:
if i + 1 != len(arr):
if arr[i] > arr[i+1]:
continue
else:
return False
return True | valid-mountain-array | faster than 89.80% Valid Mountain Array | Python | snehvora | 0 | 31 | valid mountain array | 941 | 0.335 | Easy | 15,270 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717799/Python-3-Splitting-the-array-in-two-from-the-highest-point-(196ms-15.4MB) | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
# At least three points are needed to be a mountain.
if len(arr) in [0, 1, 2]:
return False
max_idx, max_value = max(enumerate(arr), key=lambda x: x[1])
leftside = arr[:max_idx]
rightside = arr[max_idx + 1:]
# Takes care of cases where it's a hill, not a mountain.
if (not len(leftside)) or (not len(rightside)):
return False
# Takes care of cases with plateaus.
if (max_value in leftside) or (max_value in rightside):
return False
for i in range(1, len(leftside)):
if leftside[i] <= leftside[i - 1]:
return False
for i in range(1, len(rightside)):
if rightside[i] >= rightside[i - 1]:
return False
return True | valid-mountain-array | [Python 3] Splitting the array in two from the highest point (196ms, 15.4MB) | seankala | 0 | 32 | valid mountain array | 941 | 0.335 | Easy | 15,271 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717616/Python-3-EASY-Intuitive-Solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
is_decreasing = False
is_increasing = False
# length less than 3
if len(arr) < 3:
return False
for i in range(1, len(arr)):
# found downward slope, but element is larger than previous
if is_decreasing and arr[i] > arr[i-1]:
return False
# elements are equal
if arr[i] == arr[i-1]:
return False
# detect downward slope
elif arr[i] < arr[i-1]:
is_decreasing = True
# detect upward slope
elif arr[i] > arr[i-1]:
is_increasing = True
# a mountain array must have a peak and downward slope,
# but in this case, array is strictly increasing or strictly decreasing
if not is_decreasing or not is_increasing:
return False
return True | valid-mountain-array | ✅ [Python 3] EASY Intuitive Solution | JawadNoor | 0 | 22 | valid mountain array | 941 | 0.335 | Easy | 15,272 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717458/Python-Simple-Python-Solution-using-For-Loop-!!-O(N) | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
mx = max(arr)
index = arr.index(mx)
if index!=0 and index!= len(arr)-1:
s=1
for i in range(index):
if arr[i]<arr[i+1]:
s=s+1
else:
return False
for j in range(index,len(arr)-1):
if arr[j]>arr[j+1]:
s=s+1
if s==len(arr):
return True
else:
return False
else:
return False
# Time Complexity : = O(N) | valid-mountain-array | ✔✔ [ Python ] Simple Python Solution using For Loop 🔥✌👍 !! O(N) | ASHOK_KUMAR_MEGHVANSHI | 0 | 28 | valid mountain array | 941 | 0.335 | Easy | 15,273 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717380/Python-Climbing-The-Mountain-From-Both-Side-TC%3A-O(N)-SC%3A-O(1) | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
n = len(arr)
i, j = 0, n - 1
while i + 1 < n and arr[i] < arr[i + 1]:
i += 1
while j > 0 and arr[j] < arr[j - 1]:
j -= 1
return i == j and 0 < i and j < n - 1 | valid-mountain-array | ✅ Python - Climbing The Mountain From Both Side - TC: O(N), SC: O(1) | imrajeshberwal | 0 | 23 | valid mountain array | 941 | 0.335 | Easy | 15,274 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717364/Slow-but-easy-understand | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if (len(arr) < 3) or (arr[0] > arr[1]) or (arr[-1] > arr[-2]):
return 0
left = 0
right = len(arr)-1
continue_ = 1
while(continue_):
continue_ = 0
if arr[left] < arr[left+1]:
left += 1
continue_ = 1
if arr[right] < arr[right-1]:
right -= 1
continue_ = 1
if left == right:
return 1
return 0 | valid-mountain-array | Slow but easy-understand | ctw01 | 0 | 14 | valid mountain array | 941 | 0.335 | Easy | 15,275 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717301/Python-Solution-Intuitive-Based-on-Hint-on-the-Problem | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
valley_start, valley_end = 0, 0
mountain_exists, valley_exists = False, False
for i in range(len(arr) - 1):
if arr[i] < arr[i + 1]:
mountain_exists = True
else:
valley_start = i
break
for i in range(valley_start, len(arr) - 1):
if arr[i] > arr[i + 1]:
valley_exists = True
valley_end = i
else:
break
return mountain_exists and valley_exists and valley_end == len(arr)-2 | valid-mountain-array | Python Solution, Intuitive, Based on Hint on the Problem | pradeep288 | 0 | 11 | valid mountain array | 941 | 0.335 | Easy | 15,276 |
https://leetcode.com/problems/valid-mountain-array/discuss/1717162/Python-3-Solution-Linear-Time-Explained | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
if len(arr) < 3: # Base case must len >= 3
return False
isIncreasing = True
peak = -1
for i in range(1, len(arr)):
if arr[i] == arr[i -1]: # Not strictly increasing or decreasing
return False
if isIncreasing and arr[i] < arr[i - 1]: # Find peak
peak = i - 1
isIncreasing = False
if not isIncreasing and arr[i] > arr[i - 1]:
return False
return isIncreasing == False and peak != 0 | valid-mountain-array | [Python 3] Solution Linear Time Explained | gcobs0834 | 0 | 43 | valid mountain array | 941 | 0.335 | Easy | 15,277 |
https://leetcode.com/problems/valid-mountain-array/discuss/1599323/Python-3-easy-solution | class Solution:
def validMountainArray(self, arr: List[int]) -> bool:
increased = decreased = False
for i in range(1, len(arr)):
if arr[i] > arr[i-1]:
if decreased:
return False
increased = True
elif arr[i] < arr[i-1]:
if not increased:
return False
decreased = True
else:
return False
return decreased | valid-mountain-array | Python 3 easy solution | dereky4 | 0 | 120 | valid mountain array | 941 | 0.335 | Easy | 15,278 |
https://leetcode.com/problems/di-string-match/discuss/1199072/Python3-Simple-And-Readable-Solution | class Solution:
def diStringMatch(self, s: str) -> List[int]:
ans = []
a , b = 0 , len(s)
for i in s:
if(i == 'I'):
ans.append(a)
a += 1
else:
ans.append(b)
b -= 1
if(s[-1] == 'D'):
ans.append(a)
else:
ans.append(b)
return ans | di-string-match | [Python3] Simple And Readable Solution | VoidCupboard | 7 | 157 | di string match | 942 | 0.768 | Easy | 15,279 |
https://leetcode.com/problems/di-string-match/discuss/382097/Solution-in-Python-3-(beats-~100)-(one-line) | class Solution:
def diStringMatch(self, S: str) -> List[int]:
return (lambda x: [x.pop() if i == 'D' else x.popleft() for i in S]+[x[0]])(collections.deque(range(len(S)+1)))
- Junaid Mansuri
(LeetCode ID)@hotmail.com | di-string-match | Solution in Python 3 (beats ~100%) (one line) | junaidmansuri | 3 | 558 | di string match | 942 | 0.768 | Easy | 15,280 |
https://leetcode.com/problems/di-string-match/discuss/1316332/Python3-oror-Faster-than-98-oror-Twisted-two-pointer | class Solution:
def diStringMatch(self, s: str) -> List[int]:
#two pointers start = 0 and (end)n = len(s)
start = k = 0
n =len(s)
res=[None]*(n+1)
for x in s:
if x == "I":
res[k]=(start)
start+=1
else:
res[k]=(n)
n-=1
k+=1
res[k]=start
return res
#i used k for faster complexity but you can use res.append(start or n) instead | di-string-match | Python3 || Faster than 98% || Twisted two pointer | ana_2kacer | 2 | 181 | di string match | 942 | 0.768 | Easy | 15,281 |
https://leetcode.com/problems/di-string-match/discuss/1296169/Easy-Python-Solution(98.83) | class Solution:
def diStringMatch(self, s: str) -> List[int]:
l=len(s)
x=0
f=[]
for i in range(len(s)):
if(s[i]=='I'):
f.append(x)
x+=1
else:
f.append(l)
l-=1
f.append(x)
return f | di-string-match | Easy Python Solution(98.83%) | Sneh17029 | 2 | 338 | di string match | 942 | 0.768 | Easy | 15,282 |
https://leetcode.com/problems/di-string-match/discuss/2773346/Easy-to-Understand-O(n) | class Solution:
def diStringMatch(self, s: str) -> List[int]:
i, n = 0, len(s)
ans = []
for c in s:
if c == 'I':
ans.append(i)
i+=1
else:
ans.append(n)
n-=1
ans.append(i)
return ans | di-string-match | Easy to Understand O(n) | Mencibi | 1 | 58 | di string match | 942 | 0.768 | Easy | 15,283 |
https://leetcode.com/problems/di-string-match/discuss/1144914/Python-Simple-and-Easy-To-Understand-Solution-or-O(N)-Time-Complexity | class Solution:
def diStringMatch(self, s: str) -> List[int]:
perm = []
incr = 0
decr = len(s)
for i in s:
if i == 'I':
perm.append(incr)
incr += 1
if i == 'D':
perm.append(decr)
decr -= 1
perm.append(incr)
return perm | di-string-match | Python Simple & Easy To Understand Solution | O(N) Time Complexity | saurabhkhurpe | 1 | 119 | di string match | 942 | 0.768 | Easy | 15,284 |
https://leetcode.com/problems/di-string-match/discuss/302778/Python3-easy-understanding-solution | class Solution:
def diStringMatch(self, S: str) -> List[int]:
res=[]
Min=0
Max=len(S)
for i in range(len(S)):
if S[i] =="I":
res.append(Min)
Min+=1
else:
res.append(Max)
Max-=1
res.append(Min)
return res | di-string-match | Python3 easy understanding solution | JasperZhou | 1 | 117 | di string match | 942 | 0.768 | Easy | 15,285 |
https://leetcode.com/problems/di-string-match/discuss/2833667/Python-Solution | class Solution:
def diStringMatch(self, s: str) -> List[int]:
a=len(s)
b=0
l=[]
p=""
for i in s:
if(i=='D'):
l.append(a)
a-=1
p="a"
else:
l.append(b)
b+=1
p="b"
if(p=="b"):
l.append(b)
else:
l.append(a)
return l | di-string-match | Python Solution | CEOSRICHARAN | 0 | 2 | di string match | 942 | 0.768 | Easy | 15,286 |
https://leetcode.com/problems/di-string-match/discuss/2772820/Simple-Python3-Solution | class Solution:
def diStringMatch(self, S):
l, r, arr = 0, len(S), []
for s in S:
arr.append(l if s == "I" else r)
l, r = l + (s == "I"), r - (s == "D")
return arr + [l] | di-string-match | Simple Python3 Solution | dnvavinash | 0 | 1 | di string match | 942 | 0.768 | Easy | 15,287 |
https://leetcode.com/problems/di-string-match/discuss/2550568/EASY-PYTHON3-SOLUTION-0(N) | class Solution:
def diStringMatch(self, s: str) -> List[int]:
arr, low, high = [0 for _ in range(len(s) + 1)], 0, len(s)
for i in range(len(s)):
if s[i] == 'I':
arr[i] = low
low += 1
else:
arr[i] = high
high -= 1
arr[len(s)] = high
return arr | di-string-match | ✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔ 0(N) | rajukommula | 0 | 26 | di string match | 942 | 0.768 | Easy | 15,288 |
https://leetcode.com/problems/di-string-match/discuss/2473913/Python-O(n)-time-complexity-O(1)-space-complexity-with-clear-explanation-and-drawing. | class Solution:
def diStringMatch(self, s):
sLength = len(s)
diList = [] # n extra space
left, right = 0, sLength
for i in range(sLength): # O(n)
if s[i] == 'D':
diList.append(right)
right-=1
else:
diList.append(left)
left+=1
if i == len(s)-1:
if s[i] == 'D':
diList.append(right)
else:
diList.append(left)
return diList | di-string-match | Python O(n) time complexity, O(1) space complexity, with clear explanation and drawing. | OsamaRakanAlMraikhat | 0 | 36 | di string match | 942 | 0.768 | Easy | 15,289 |
https://leetcode.com/problems/di-string-match/discuss/2087089/Python3-Solution-with-using-two-pointers | class Solution:
def diStringMatch(self, s: str) -> List[int]:
left, right = 0, len(s)
res = []
for c in s:
if c == 'I':
res.append(left)
left += 1
else:
res.append(right)
right -= 1
res.append(left) # or right
return res | di-string-match | [Python3] Solution with using two-pointers | maosipov11 | 0 | 59 | di string match | 942 | 0.768 | Easy | 15,290 |
https://leetcode.com/problems/di-string-match/discuss/2077772/O(N)-basic-solution | class Solution:
def diStringMatch(self, s: str) -> List[int]:
low, high = 0, len(s)
res = []
for char in s:
if char == "I":
res.append(low)
low += 1
else:
res.append(high)
high -= 1
res.append(low)
return res | di-string-match | O(N) basic solution | andrewnerdimo | 0 | 56 | di string match | 942 | 0.768 | Easy | 15,291 |
https://leetcode.com/problems/di-string-match/discuss/2012780/Python-3-Solution-Two-Pointers | class Solution:
def diStringMatch(self, s: str) -> List[int]:
perm = list()
low, high = 0, len(s)
for i in s:
if i == "I":
perm.append(low)
low += 1
elif i == "D":
perm.append(high)
high -= 1
perm.append(low)
return perm | di-string-match | Python 3 Solution, Two Pointers | AprDev2011 | 0 | 35 | di string match | 942 | 0.768 | Easy | 15,292 |
https://leetcode.com/problems/di-string-match/discuss/1979742/python-3-oror-simple-two-pointer-solution | class Solution:
def diStringMatch(self, s: str) -> List[int]:
res = []
low, high = 0, len(s)
for c in s:
if c == 'I':
res.append(low)
low += 1
else:
res.append(high)
high -= 1
res.append(low)
return res | di-string-match | python 3 || simple two pointer solution | dereky4 | 0 | 73 | di string match | 942 | 0.768 | Easy | 15,293 |
https://leetcode.com/problems/di-string-match/discuss/1884332/Python-easy-solution-for-beginners | class Solution:
def diStringMatch(self, s: str) -> List[int]:
inc = 0
dec = len(s)
res = []
for i in s:
if i == 'I':
res.append(inc)
inc += 1
else:
res.append(dec)
dec -= 1
res.append(dec)
return res | di-string-match | Python easy solution for beginners | alishak1999 | 0 | 73 | di string match | 942 | 0.768 | Easy | 15,294 |
https://leetcode.com/problems/di-string-match/discuss/1648496/Python | class Solution:
def diStringMatch(self, s: str) -> List[int]:
ci = s.count("I")
cd = s.count("D")
lis = []
i,d = 0, cd + ci
for x in range(len(s)):
if s[x] == "I":
lis.append(i)
i += 1
elif s[x] == "D":
lis.append(d)
d -= 1
lis.append(ci)
return lis | di-string-match | Python | KratikaRathore | 0 | 58 | di string match | 942 | 0.768 | Easy | 15,295 |
https://leetcode.com/problems/di-string-match/discuss/1495005/Python-3-oror-Simple-two-pointer-with-index-of-string-and-while-loop-oror-explained-in-comments | class Solution:
def diStringMatch(self, s: str) -> List[int]:
#firstly keep i at first and j at last rqd value = len(nums) = n
# each time you find I print i and D print j+1
# use an idx pointer to move in the string
n = len(s)
i,j = 0,n
idx =0
res = []
while(i<=j):
if s[idx]=="I":
res.append(i)
i+=1
else:
res.append(j)
j-=1
if idx<n-1:
idx+=1
return res | di-string-match | Python 3 || Simple two pointer with index of string and while loop || explained in comments | ana_2kacer | 0 | 109 | di string match | 942 | 0.768 | Easy | 15,296 |
https://leetcode.com/problems/di-string-match/discuss/1494888/DI-String-Match-or-Runtime%3A-64ms-(Faster-than-70.90-of-Python3-Submissions) | class Solution:
def diStringMatch(self, s: str) -> List[int]:
temp = [0 for i in range(len(s)+1)]
minim = 0
maxim = len(s)
for i in range(len(s)):
if s[i] == 'I':
temp[i] = minim
minim += 1
else:
temp[i] = maxim
maxim -= 1
temp[-1] = maxim
return temp | di-string-match | DI String Match | Runtime: 64ms (Faster than 70.90% of Python3 Submissions) | thisisashwinraj | 0 | 44 | di string match | 942 | 0.768 | Easy | 15,297 |
https://leetcode.com/problems/di-string-match/discuss/1298344/Python-3-Topological-sort-or-O(n)-T-or-O(n)-S | class Solution:
def diStringMatch(self, s: str) -> List[int]:
graph = [[] for _ in range(len(s)+1)]
for i, ch in enumerate(s):
if ch == 'I':
graph[i].append(i+1)
else:
graph[i+1].append(i)
top_sort = []
used = [False]*len(graph)
def dfs(v):
used[v] = True
for ch in graph[v]:
if not used[ch]:
dfs(ch)
top_sort.append(v)
for v in range(len(graph)):
if not used[v]:
dfs(v)
top_sort.reverse()
result = [-1] * len(graph)
val = 0
for v in top_sort:
result[v] = val
val += 1
return result | di-string-match | Python 3 Topological sort | O(n) T | O(n) S | CiFFiRO | 0 | 63 | di string match | 942 | 0.768 | Easy | 15,298 |
https://leetcode.com/problems/di-string-match/discuss/1227284/Python-Easy-to-understand-solution | class Solution:
def diStringMatch(self, s: str) -> List[int]:
ans = []
rangelist = [i for i in range(0,len(s)+1)]
for char in s:
if char=='I':
ans.append(min(rangelist))
rangelist.remove(min(rangelist))
else:
ans.append(max(rangelist))
rangelist.remove(max(rangelist))
ans.extend(rangelist) #appending last element left int he rangelist
return ans | di-string-match | [Python] Easy-to-understand solution | arkumari2000 | 0 | 94 | di string match | 942 | 0.768 | Easy | 15,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.