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/different-ways-to-add-parentheses/discuss/2819117/Python-Medium | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
if expression.isdigit():
return [int(expression)]
res = []
for i in range(len(expression)):
if expression[i] in "+-*":
left = self.diffWaysToCompute(expression[:i])
right = self.diffWaysToCompute(expression[i + 1:])
res += [eval(str(j) + expression[i] + str(k)) for j in left for k in right]
return res | different-ways-to-add-parentheses | Python Medium | lucasschnee | 0 | 7 | different ways to add parentheses | 241 | 0.633 | Medium | 4,600 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2766287/divide-and-conquer | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
res = []
for i in range(len(expression)):
if expression[i] in '+-*':
left = self.diffWaysToCompute(expression[:i])
right = self.diffWaysToCompute(expression[i+1:])
for l in left:
for r in right:
if expression[i]=='+':
res.append(l+r)
elif expression[i]=='-':
res.append(l-r)
elif expression[i]=='*':
res.append(l*r)
if not res:
return [int(expression)]
return res | different-ways-to-add-parentheses | divide and conquer | yhu415 | 0 | 7 | different ways to add parentheses | 241 | 0.633 | Medium | 4,601 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2727538/Python-memorization | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
@cache
def helper(x, y):
if "+" not in expression[x: y+1] and "-" not in expression[x: y+1] and "*" not in expression[x: y+1]:
return [int(expression[x: y+1])]
res = list()
i = x
while i < y + 1:
j = i
while j < y + 1 and expression[j] not in {"+", "-", "*"}:
j += 1
if j < y + 1:
left = helper(x, j - 1)
right = helper(j + 1, y)
for l in left:
for r in right:
if expression[j] == "+":
res.append(l + r)
elif expression[j] == "-":
res.append(l - r)
else:
res.append(l * r)
i = j + 1
return res
return helper(0, len(expression) - 1) | different-ways-to-add-parentheses | Python, memorization | yiming999 | 0 | 8 | different ways to add parentheses | 241 | 0.633 | Medium | 4,602 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2726465/Recursive-Solution | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
if expression.isnumeric():
return [int(expression)]
output = []
for i in range(len(expression)):
if expression[i] == "+" or expression[i] == "-" or expression[i] == "*":
left = self.diffWaysToCompute(expression[:i])
right = self.diffWaysToCompute(expression[i+1:])
for x in left:
for y in right:
if expression[i] == "+":
output.append(x + y)
elif expression[i] == "-":
output.append(x - y)
else:
output.append(x * y)
return output | different-ways-to-add-parentheses | Recursive Solution | anshsharma17 | 0 | 11 | different ways to add parentheses | 241 | 0.633 | Medium | 4,603 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2664532/Python-100-Faster-or-27ms-or-Recursion-%2B-Memoization-or-Easy-Understanding-or | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
dp = {}
def getVal(k, val1, val2):
if expression[k] == "*":
return int(val1) * int(val2)
elif expression[k] == "+":
return int(val1) + int(val2)
else:
return int(val1) - int(val2)
def isSymbol(i):
return expression[i] == "+" or expression[i] == "*" or expression[i] == "-"
def solution(start, end):
res = []
if (start, end) in dp:
return dp[(start, end)]
if (start == end-1) and (not isSymbol(end)):
res.append(expression[start:end+1])
return res
if(start == end):
res.append(expression[start])
return res
for i in range(start, end+1):
if isSymbol(i):
l1 = solution(start, i-1)
l2 = solution(i+1, end)
for j in l1:
for k in l2:
res.append(getVal(i,j,k))
dp[(start, end)] = res
return res
return solution(0, len(expression)-1) | different-ways-to-add-parentheses | [Python] 100% Faster | 27ms | Recursion + Memoization | Easy Understanding | | yash_vish87 | 0 | 10 | different ways to add parentheses | 241 | 0.633 | Medium | 4,604 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2649691/Python-Solution-Divide-and-Conquer | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
operators = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
}
@cache
def dp(i, j):
if expression[i:j+1].isnumeric():
return [int(expression[i:j+1])]
output = []
for k in range(i, j+1):
if expression[k] in operators:
left = dp(i, k-1)
right = dp(k+1, j)
output += [operators[expression[k]](l, r) for l in left for r in right]
return output
return dp(0, len(expression)-1) | different-ways-to-add-parentheses | Python Solution - Divide and Conquer | sharma_shubham | 0 | 10 | different ways to add parentheses | 241 | 0.633 | Medium | 4,605 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2599051/Python-Divide-Conquer-with-memo | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
memo = dict()
return self.computeWithMemo(expression, memo)
def computeWithMemo(self, expression, memo):
if (expression in memo):
return memo[expression]
res = []
# for each operator in the expression, split formula to two sides
for i in range(len(expression)):
c = expression[i]
if (c == '-' or c == '*' or c == '+'):
left = self.computeWithMemo(expression[0:i], memo)
right = self.computeWithMemo(expression[i+1:], memo)
# add all combinations from the two sides
for a in left:
for b in right:
if (c == '+'):
res.append(a+b)
elif (c == '-'):
res.append(a-b)
elif (c == '*'):
res.append(a*b)
# edge case: stop when there's no operator in the expression
if (len(res) == 0):
res.append(int(expression))
memo[expression] = res
return res | different-ways-to-add-parentheses | Python Divide Conquer with memo | leqinancy | 0 | 23 | different ways to add parentheses | 241 | 0.633 | Medium | 4,606 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2523759/Python-Recursive-DP | class Solution(object):
def diffWaysToCompute(self, expression):
cache = {}
def solve(exp):
if exp in cache:
return cache[exp]
if len(exp)==1 and exp.isnumeric() or len(exp)==2 and exp.isnumeric:
return [int(exp)]
operators = {'*','-','+'}
ans = []
for i in range(len(exp)):
if exp[i] in operators:
# break and solve in two parts
res1 = solve(exp[:i])
res2 = solve(exp[i+1:])
for a in res1:
for b in res2:
if exp[i] == '+':
ans.append(a+b)
elif exp[i] == '-':
ans.append(a-b)
elif exp[i] == '*':
ans.append(a*b)
cache[exp] = ans
return cache[exp]
return solve(expression) | different-ways-to-add-parentheses | Python Recursive DP | Abhi_009 | 0 | 125 | different ways to add parentheses | 241 | 0.633 | Medium | 4,607 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2477074/Python-Solution-or-Clean-Code-or-Recursive-or-Divide-and-Conquer | class Solution:
def calculate(self,l,op,r):
if op == "+":
return l + r
if op == "-":
return l - r
if op == "*":
return l * r
def diffWaysToCompute(self, expression: str) -> List[int]:
result = []
for i in range(0,len(expression)):
char = expression[i]
if char in ["+","-","*"]:
leftItems = self.diffWaysToCompute(expression[:i])
rightItems = self.diffWaysToCompute(expression[i+1:])
for l in leftItems:
for r in rightItems:
result.append(self.calculate(l,char,r))
# 1 integer only case
if not result:
result.append(int(expression))
return result | different-ways-to-add-parentheses | Python Solution | Clean Code | Recursive | Divide and Conquer | Gautam_ProMax | 0 | 48 | different ways to add parentheses | 241 | 0.633 | Medium | 4,608 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2426662/Python3or-Simple-Solution-Using-Top-Down-Recursion-With-Memoization | class Solution(object):
def diffWaysToCompute(self, expression):
result = []
def helper(s, memo):
result = []
#another base case for memoization!
if(s in memo):
return memo[s]
#base case: single digit characters!
if(s.isdigit()):
return [int(s)]
#otherwise, we need to first store all operator symbols in some arr!
symbols = ['+', '-', '*']
#iterate through each and every char in expression
for i in range(len(s)):
cur = s[i]
if(cur in symbols):
#if current ith character is a symbol, recursively evaluate the left substring of #index
#i and get all left candidates. Do the same for right substring recursively!
#Pair up all left and right candidates and apply the corresponding operator!
#Store each output in the answer array!
left, right = helper(s[:i], memo), helper(s[i+1:], memo)
#pair up!
for l in left:
for r in right:
#check operator's type!
if(s[i] == '+'):
result.append(l + r)
elif(s[i] == '-'):
result.append(l - r)
else:
result.append(l * r)
#take a memo before returning since string s is first time solved!
memo[s] = result
return result
ans = helper(expression, {})
return ans | different-ways-to-add-parentheses | Python3| Simple Solution Using Top-Down Recursion With Memoization | JOON1234 | 0 | 41 | different ways to add parentheses | 241 | 0.633 | Medium | 4,609 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2421898/Python3-or-Divide-and-Conqueor | class Solution:
s={"-","+","*"}
hmap={}
def diffWaysToCompute(self, expression: str) -> List[int]:
if expression in self.hmap:
return self.hmap[expression]
res=[]
for ind,i in enumerate(expression):
if i in self.s:
array_1=self.diffWaysToCompute(expression[:ind])
array_2=self.diffWaysToCompute(expression[ind+1:])
for num_1 in array_1:
for num_2 in array_2:
if i=='+':
res.append(int(num_1)+int(num_2))
elif i=='-':
res.append(int(num_1)-int(num_2))
elif i=='*':
res.append(int(num_1)*int(num_2))
if len(res)==0:res.append(expression)
self.hmap[expression]=res
return res | different-ways-to-add-parentheses | [Python3] | Divide & Conqueor | swapnilsingh421 | 0 | 27 | different ways to add parentheses | 241 | 0.633 | Medium | 4,610 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2408896/Python-memo | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
memo = {}
def solve(e):
if e.isdigit():
return [int(e)]
if e in memo:
return memo[e]
ans= []
for i in range(len(e)):
if e[i] in ['+','-','*']:
left = solve(e[:i])
right = solve(e[i+1:])
for l in left:
for r in right:
if e[i]=='-':
ans.append(l-r)
elif e[i]=='*':
ans.append(l*r)
elif e[i]=='+':
ans.append(l+r)
memo[e] = ans
return ans
return solve(expression) | different-ways-to-add-parentheses | Python memo | Brillianttyagi | 0 | 45 | different ways to add parentheses | 241 | 0.633 | Medium | 4,611 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2222929/Python3-Clean-code-recursion-%2B-memoization-(MCM) | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
def evaluate(left_ops, right_ops, sign):
ans = []
for i in range(len(left_ops)):
for j in range(len(right_ops)):
if sign == "*":
loc_ans = left_ops[i] * right_ops[j]
elif sign == "-":
loc_ans = left_ops[i] - right_ops[j]
else:
loc_ans = left_ops[i] + right_ops[j]
ans.append(loc_ans)
return ans
def dp(exp, start, end, memo):
if start == end:
return [int(exp[start])]
if start + 1 == end and exp[start].isdigit() and exp[end].isdigit():
return [int(exp[start:end + 1])]
if (start, end) in memo:
return memo[(start, end)]
ans = []
for i in range(start, end + 1):
if exp[i] in "+-*":
left_ans = dp(exp, start, i - 1, memo)
right_ans = dp(exp, i + 1, end, memo)
eval_ans = evaluate(left_ans, right_ans, exp[i])
ans += eval_ans
memo[(start, end)] = ans
return ans
return dp(expression, 0, len(expression) - 1, {}) | different-ways-to-add-parentheses | Python3 - Clean code, recursion + memoization (MCM) | myvanillaexistence | 0 | 101 | different ways to add parentheses | 241 | 0.633 | Medium | 4,612 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/2001064/Beautiful-solution-to-a-beautiful-problem | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
def operations(x,y,op):
if op=='+':
return int(x)+int(y)
if op=='-':
return int(x)-int(y)
if op=='*':
return int(x)*int(y)
def evaluate(exp):
res=[]
for i in range(len(exp)):
if exp[i]=='+' or exp[i]=='-' or exp[i]=='*':
left=evaluate(exp[:i])
right=evaluate(exp[i+1:])
for l in left:
for r in right:
res.append(operations(l,r,exp[i]))
if not res:
res.append(exp)
return res
return evaluate(expression) | different-ways-to-add-parentheses | Beautiful solution to a beautiful problem | pbhuvaneshwar | 0 | 286 | different ways to add parentheses | 241 | 0.633 | Medium | 4,613 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1530295/Python3-easy-implemented-by-own-(excluded-libraries)-90-faster | class Solution:
def cal(self, a, b, op):
if op == "*":
return a*b
if op == "+":
return a + b
return a - b
# @lru_cache(None)
def rec(self, i, j):
z = self.s
memo = self.cache
key = (i, j)
if key in memo:
return memo[key]
res = []
for a in range(i, j+1):
if z[a] in self.ops:
left = self.rec(i, a-1)
right = self.rec(a+1, j)
for l in left:
for r in right:
res.append(self.cal(l, r, z[a]))
if not res:
return [int(z[i:j+1])]
memo[key] = res
return res
def diffWaysToCompute(self, expression: str) -> List[int]:
n = len(expression)
self.ops = {"*", "+", "-"}
self.s = expression
self.cache = {}
return self.rec(0, n-1) | different-ways-to-add-parentheses | Python3 easy implemented by own (excluded libraries) 90% faster | ashish_chiks | 0 | 159 | different ways to add parentheses | 241 | 0.633 | Medium | 4,614 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1155748/Python-divide-and-conquer-%2B-memory-92 | class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
if len(expression) < 2:
return [int(expression)]
ans = []
m = {}
op = {
'*': lambda x, y: x * y,
'-': lambda x, y: x - y,
'+': lambda x, y: x + y,
}
def divideandconquer(s):
if s in m:
return m[s]
left, right, res = [], [], []
for i in range(len(s)):
if s[i] in op:
s1 = s[0:i]
s2 = s[i + 1:]
left = divideandconquer(s1)
right = divideandconquer(s2)
for l in m[s1]:
for r in m[s2]:
res.append(op[s[i]](l,r))
if not res:
res.append(int(s))
m[s] = res
return res
ans = divideandconquer(expression)
return ans | different-ways-to-add-parentheses | Python divide and conquer + memory 92% | ScoutBoi | 0 | 449 | different ways to add parentheses | 241 | 0.633 | Medium | 4,615 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/1043479/Combinations-with-parenthesis | class Solution:
def funcHelper(self, base, combinations):
if len(base) == 1:
combinations.add(base[0])
for i in range(1, len(base), 2):
sub = '('+''.join(base[i-1:i+2])+')'
self.funcHelper(base[:i-1]+[sub]+base[i+2:], combinations)
def diffWaysToCompute(self, input: str) -> List[int]:
operator_positions = [
i for i,c in enumerate(input)
if c in "*+-"]
base = []
prev = 0
for p in operator_positions:
base.append(input[prev:p])
base.append(input[p])
prev = p+1
base.append(input[prev:])
combinations = set()
self.funcHelper(base, combinations)
return [eval(c) for c in combinations] | different-ways-to-add-parentheses | Combinations with parenthesis | paolomoriello | 0 | 387 | different ways to add parentheses | 241 | 0.633 | Medium | 4,616 |
https://leetcode.com/problems/different-ways-to-add-parentheses/discuss/374378/Simon's-Note-Python3-itertools.product | class Solution:
def diffWaysToCompute(self, input: str) -> List[int]:
ops={
'+':lambda x,y:x+y,
'-':lambda x,y:x-y,
'*':lambda x,y:x*y
}
def ways(s):
ans=[]
for i in range(len(s)):
if s[i] in '+-*':
ans+=[ops[s[i]](l,r) for l,r in itertools.product(ways(s[0:i]),ways(s[i+1:]))]
if not ans:
ans.append(int(s))
return ans
return ways(input) | different-ways-to-add-parentheses | [🎈Simon's Note🎈] Python3 itertools.product | SunTX | 0 | 98 | different ways to add parentheses | 241 | 0.633 | Medium | 4,617 |
https://leetcode.com/problems/valid-anagram/discuss/433680/Python-3-O(n)-Faster-than-98.39-Memory-usage-less-than-100 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
tracker = collections.defaultdict(int)
for x in s: tracker[x] += 1
for x in t: tracker[x] -= 1
return all(x == 0 for x in tracker.values()) | valid-anagram | Python 3 - O(n) - Faster than 98.39%, Memory usage less than 100% | mmbhatk | 69 | 18,500 | valid anagram | 242 | 0.628 | Easy | 4,618 |
https://leetcode.com/problems/valid-anagram/discuss/2500985/Very-Easy-oror-100-oror-Fully-Explained-oror-C%2B%2B-Java-Python-JavaScript-Python3 | class Solution(object):
def isAnagram(self, s, t):
# In case of different length of thpse two strings...
if len(s) != len(t):
return False
for idx in set(s):
# Compare s.count(l) and t.count(l) for every index i from 0 to 26...
# If they are different, return false...
if s.count(idx) != t.count(idx):
return False
return True # Otherwise, return true... | valid-anagram | Very Easy || 100% || Fully Explained || C++, Java, Python, JavaScript, Python3 | PratikSen07 | 31 | 2,800 | valid anagram | 242 | 0.628 | Easy | 4,619 |
https://leetcode.com/problems/valid-anagram/discuss/2440351/Python-Easy-Top-99.4-Runtime | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
flag = True
if len(s) != len(t):
flag = False
else:
letters = "abcdefghijklmnopqrstuvwxyz"
for letter in letters:
if s.count(letter) != t.count(letter):
flag = False
break
return flag | valid-anagram | Python Easy Top 99.4% Runtime | drblessing | 28 | 2,400 | valid anagram | 242 | 0.628 | Easy | 4,620 |
https://leetcode.com/problems/valid-anagram/discuss/1587655/Faster-than-99-Python-3-(With-Video) | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
for char in set(s):
if s.count(char) != t.count(char):
return False
return True | valid-anagram | Faster than 99% - Python 3 (With Video) | hudsonh | 16 | 1,000 | valid anagram | 242 | 0.628 | Easy | 4,621 |
https://leetcode.com/problems/valid-anagram/discuss/1058987/Simple-and-easy-hash-map-python-solution-or-O(N) | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
d = {}
for i in s:
if i in d: d[i] += 1
else: d[i] = 1
for i in t:
if i in d: d[i] -= 1
else: return False
for k, v in d.items():
if v != 0: return False
return True | valid-anagram | Simple and easy hash-map python solution | O(N) | vanigupta20024 | 11 | 1,300 | valid anagram | 242 | 0.628 | Easy | 4,622 |
https://leetcode.com/problems/valid-anagram/discuss/1061765/Python-one-liner | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t) | valid-anagram | Python one-liner | lokeshsenthilkumar | 8 | 1,100 | valid anagram | 242 | 0.628 | Easy | 4,623 |
https://leetcode.com/problems/valid-anagram/discuss/382792/Python-solutions | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
frequencies = [0]*26
count = 0
for letter in s:
index = ord(letter) - ord('a')
frequencies[index] += 1
count += 1
for letter in t:
index = ord(letter) - ord('a')
if frequencies[index] == 0:
return False
frequencies[index] -= 1
count -= 1
return count == 0 | valid-anagram | Python solutions | amchoukir | 5 | 703 | valid anagram | 242 | 0.628 | Easy | 4,624 |
https://leetcode.com/problems/valid-anagram/discuss/382792/Python-solutions | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t) | valid-anagram | Python solutions | amchoukir | 5 | 703 | valid anagram | 242 | 0.628 | Easy | 4,625 |
https://leetcode.com/problems/valid-anagram/discuss/2616013/SIMPLE-PYTHON3-SOLUTION-one-line-easy-understandable | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return collections.Counter(s)==collections.Counter(t) | valid-anagram | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ one line easy understandable | rajukommula | 4 | 336 | valid anagram | 242 | 0.628 | Easy | 4,626 |
https://leetcode.com/problems/valid-anagram/discuss/2093368/Python3-Easy-Solution-Using-Dictionary-O(N)-Time | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
dicS = {chr(i) : 0 for i in range(97, 123)} # creating dictionary key as 'a' to 'z' and value as frequency of characters in s
for i in s:
dicS[i] += 1 # increasing the count of current character i
dicT = {chr(i) : 0 for i in range(97, 123)} # creating dictionary key as 'a' to 'z' and value as frequency of characters in t
for i in t:
dicT[i] += 1 # increasing the count of current character i
return dicS == dicT # frequency of characters in s equal to frequency of characters in t
# Time: O(N) ; as traversing only once
# Space: O(N) ; for creating the dictionaries | valid-anagram | [Python3] Easy Solution Using Dictionary O(N) Time | samirpaul1 | 4 | 353 | valid anagram | 242 | 0.628 | Easy | 4,627 |
https://leetcode.com/problems/valid-anagram/discuss/1555254/Python-one-pass-simple-O(n)-solution-without-sorting | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)!=len(t):return False
d=dict.fromkeys(s,0)
for ss,tt in zip(s,t):
if tt not in d: break
d[ss] += 1
d[tt] -= 1
else:
return not any(d.values())
return False | valid-anagram | Python one pass simple O(n) solution without sorting | cyrille-k | 4 | 490 | valid anagram | 242 | 0.628 | Easy | 4,628 |
https://leetcode.com/problems/valid-anagram/discuss/2719812/One-line-Solution-with-faster-than-88.05-Runtime | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t) | valid-anagram | One line Solution with faster than 88.05% Runtime | yomnazali | 3 | 59 | valid anagram | 242 | 0.628 | Easy | 4,629 |
https://leetcode.com/problems/valid-anagram/discuss/2546176/3-different-Python-solutions | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
res = {}
for i in s:
if i not in res:
res[i] = 1
else:
res[i] += 1
for i in t:
if i not in res:
return False
else:
res[i] -= 1
return set(res.values()) == set([0]) | valid-anagram | 📌 3 different Python solutions | croatoan | 3 | 184 | valid anagram | 242 | 0.628 | Easy | 4,630 |
https://leetcode.com/problems/valid-anagram/discuss/2546176/3-different-Python-solutions | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
res1 = {}
res2 = {}
for i in s:
if i not in res1:
res1[i] = 1
else:
res1[i] += 1
for i in t:
if i not in res2:
res2[i] = 1
else:
res2[i] += 1
return res1 == res2 | valid-anagram | 📌 3 different Python solutions | croatoan | 3 | 184 | valid anagram | 242 | 0.628 | Easy | 4,631 |
https://leetcode.com/problems/valid-anagram/discuss/2546176/3-different-Python-solutions | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return collections.Counter(s) == collections.Counter(t) | valid-anagram | 📌 3 different Python solutions | croatoan | 3 | 184 | valid anagram | 242 | 0.628 | Easy | 4,632 |
https://leetcode.com/problems/valid-anagram/discuss/2355633/Easy-python3 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
countS, countT = {}, {}
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0)
countT[t[i]] = 1 + countT.get(t[i], 0)
for c in countS:
if countS[c] != countT.get(c, 0):
return False
return True | valid-anagram | Easy python3 | __Simamina__ | 3 | 104 | valid anagram | 242 | 0.628 | Easy | 4,633 |
https://leetcode.com/problems/valid-anagram/discuss/2008602/Runtime%3A-32-ms-faster-than-99.65-of-Python3 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
for each in set(s):
if s.count(each) != t.count(each):
return False
else:
return True | valid-anagram | Runtime: 32 ms, faster than 99.65% of Python3 | kpkrishnapal | 3 | 248 | valid anagram | 242 | 0.628 | Easy | 4,634 |
https://leetcode.com/problems/valid-anagram/discuss/1571836/Python3-One-Liner-Solution | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t) | valid-anagram | Python3 One Liner Solution | risabhmishra19 | 3 | 178 | valid anagram | 242 | 0.628 | Easy | 4,635 |
https://leetcode.com/problems/valid-anagram/discuss/1060447/Python.-faster-than-95.20.-one-liner-O(n)-Cool-Simple-and-clear-solution. | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t) | valid-anagram | Python. faster than 95.20%. one-liner, O(n), Cool, Simple & clear solution. | m-d-f | 3 | 403 | valid anagram | 242 | 0.628 | Easy | 4,636 |
https://leetcode.com/problems/valid-anagram/discuss/2343969/Python-Simple-Faster-than-90.55-Solution-51ms-oror-Documented | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# if lengths of strings are not equal or
# if all letters are NOT common to both strings, return false
if len(s) != len(t) or set(s) != set(t):
return False
# create frequency table for s and t with 0 initially
dictS = dict.fromkeys(set(s), 0)
dictT = dictS.copy()
for i in range(len(s)):
dictS[s[i]] = dictS[s[i]] + 1
dictT[t[i]] = dictT[t[i]] + 1
# return true if both tables are equal
return dictS == dictT | valid-anagram | [Python] Simple Faster than 90.55% Solution - 51ms || Documented | Buntynara | 2 | 68 | valid anagram | 242 | 0.628 | Easy | 4,637 |
https://leetcode.com/problems/valid-anagram/discuss/2158799/Python-One-Liner | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
#Counter() => returns the count of each element in the container
return Counter(s)==Counter(t) | valid-anagram | Python One Liner | pruthashouche | 2 | 196 | valid anagram | 242 | 0.628 | Easy | 4,638 |
https://leetcode.com/problems/valid-anagram/discuss/2153329/EASY-SOLUTION-USING-PYTHON | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s = sorted(list(s))
t = sorted(list(t))
if s == t:
return True
return False | valid-anagram | EASY SOLUTION USING PYTHON | rohansardar | 2 | 158 | valid anagram | 242 | 0.628 | Easy | 4,639 |
https://leetcode.com/problems/valid-anagram/discuss/1813901/Python-Easiest-Solution-oror-HashMap-oror-Optimized | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
hashS, hashT = {}, {}
if len(s) != len(t) or len(set(s)) != len(set(t)) :
return False
for i in range(len(s)):
hashS[s[i]] = 1 + hashS.get(s[i], 0)
hashT[t[i]] = 1 + hashT.get(t[i], 0)
# Way - 1 to confirm if both the hashmap are equal.
for j in hashS:
if hashS[j] != hashT.get(j, 0):
return False
return True
# Way - 2 to confirm if both the hashmap are equal.
if hashS == hashT:
return True
return False | valid-anagram | Python Easiest Solution || HashMap || Optimized | rlakshay14 | 2 | 205 | valid anagram | 242 | 0.628 | Easy | 4,640 |
https://leetcode.com/problems/valid-anagram/discuss/1640863/Python-Beginner-Friendly-code-with-easy-Explanation | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# Frequency count of characters (string S)
dic_s = collections.Counter(s)
# We will store frequency count of (String t) here
dic_t = {}
length = 0
for i in range (len(t)):
if t[i] in dic_s:
char = t[i]
# Getting freequency from 't'
dic_t[char] = dic_t.get(char, 0) + 1
# if char freq matches we will update the length
if dic_s[char] == dic_t[char]:
length += dic_t[char]
if length == len(s) == len(t):
return True
else: False | valid-anagram | [Python] Beginner Friendly code with easy Explanation | stormbreaker_x | 2 | 109 | valid anagram | 242 | 0.628 | Easy | 4,641 |
https://leetcode.com/problems/valid-anagram/discuss/1585425/Pythonor-2-ways-Counter(O(n)-time-complexity)-and-sorted-function(O(nlogn)-Time-complexity)) | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
count_s = collections.Counter(s)
count_t = collections.Counter(t)
return count_s == count_t | valid-anagram | Python| 2 ways - Counter(O(n)- time complexity) and sorted function(O(nlogn)- Time complexity)) | lunarcrab | 2 | 189 | valid anagram | 242 | 0.628 | Easy | 4,642 |
https://leetcode.com/problems/valid-anagram/discuss/1585425/Pythonor-2-ways-Counter(O(n)-time-complexity)-and-sorted-function(O(nlogn)-Time-complexity)) | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t) | valid-anagram | Python| 2 ways - Counter(O(n)- time complexity) and sorted function(O(nlogn)- Time complexity)) | lunarcrab | 2 | 189 | valid anagram | 242 | 0.628 | Easy | 4,643 |
https://leetcode.com/problems/valid-anagram/discuss/1569382/Fully-Explained-Python-Solution-With-Proper-Comments | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
#Create a dictionary which will store the frequency of each of character
d={}
#iterate over all the characters in the string 's'
for element in s:
if element in d:
#increse the frequency count by 1 if it is already there in the dictionary 'd'
d[element]+=1
else:
#initiate that element frequency by 1 in the 'd' if it is not there previously.
d[element]=1
#iterate over all the characters in the string 't'
for element in t:
if element in d:
#decrease the frequency count by 1 so as to check the same frequency count of each character
d[element]-=1
else:
#if the element is not there in the dictionary that means that particular element is not there in the string 's' which tends the result to False
return False
for key,value in d.items():
if value!=0:
#Return False if the any of element value is not 0 after cancelling their each occurence from both side 's' and 't'
return False
return True | valid-anagram | Fully Explained Python Solution With Proper Comments | AdityaTrivedi88 | 2 | 154 | valid anagram | 242 | 0.628 | Easy | 4,644 |
https://leetcode.com/problems/valid-anagram/discuss/1484824/Easy-Implementation-Python-99 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s = {char:s.count(char) for char in set(s)}
t = {char:t.count(char) for char in set(t)}
return s == t | valid-anagram | Easy Implementation, Python 99% | AshwinBalaji52 | 2 | 305 | valid anagram | 242 | 0.628 | Easy | 4,645 |
https://leetcode.com/problems/valid-anagram/discuss/961903/Python-Simple-Solution | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
c1=collections.Counter(s)
c2=collections.Counter(t)
return c1==c2 | valid-anagram | Python Simple Solution | lokeshsenthilkumar | 2 | 325 | valid anagram | 242 | 0.628 | Easy | 4,646 |
https://leetcode.com/problems/valid-anagram/discuss/961903/Python-Simple-Solution | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s)==sorted(t) | valid-anagram | Python Simple Solution | lokeshsenthilkumar | 2 | 325 | valid anagram | 242 | 0.628 | Easy | 4,647 |
https://leetcode.com/problems/valid-anagram/discuss/255473/Easy-Code-for-Valid-Anagram | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if sorted(list(t))==sorted(list(s)):
return True
else:
return False | valid-anagram | Easy Code for Valid Anagram | lalithbharadwaj | 2 | 396 | valid anagram | 242 | 0.628 | Easy | 4,648 |
https://leetcode.com/problems/valid-anagram/discuss/2613974/Python-HashMap-oror-Sorted-oror-Counter-Solutions | class Solution: # Time: O(n) and Space: O(n)
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t): # when the lengths are different then there is no way it can ever be an Anagram
return False
countS, countT = {}, {} # character's are key: occurences are values
for i in range(len(s)):
countS[s[i]] = 1 + countS.get(s[i], 0) # get previous occurences, if it's first time get 0
countT[t[i]] = 1 + countT.get(t[i], 0) # countT[t[0]=n] = 1 + countT.get(t[0]=n = Null, 0)=0 = 1
for j in countS:
if countS[j] != countT.get(j, 0): # if the number of occurences of char j is not same in both the hashmaps then it is not valid
return False
return True # when the for loop ends means every key's and value are same | valid-anagram | Python [ HashMap || Sorted || Counter ] Solutions | DanishKhanbx | 1 | 163 | valid anagram | 242 | 0.628 | Easy | 4,649 |
https://leetcode.com/problems/valid-anagram/discuss/2613974/Python-HashMap-oror-Sorted-oror-Counter-Solutions | class Solution: # Time: O(nlogn) and Space: O(1)
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t) | valid-anagram | Python [ HashMap || Sorted || Counter ] Solutions | DanishKhanbx | 1 | 163 | valid anagram | 242 | 0.628 | Easy | 4,650 |
https://leetcode.com/problems/valid-anagram/discuss/2613974/Python-HashMap-oror-Sorted-oror-Counter-Solutions | class Solution: # Time: O(n) and Space: O(n)
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t) | valid-anagram | Python [ HashMap || Sorted || Counter ] Solutions | DanishKhanbx | 1 | 163 | valid anagram | 242 | 0.628 | Easy | 4,651 |
https://leetcode.com/problems/valid-anagram/discuss/2489386/python3-1-line-solution | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s)==sorted(t) | valid-anagram | python3 1 line solution | kyoko0810 | 1 | 38 | valid anagram | 242 | 0.628 | Easy | 4,652 |
https://leetcode.com/problems/valid-anagram/discuss/2444263/or-python3-or-ONE-LINE-or | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(t)==sorted(s) | valid-anagram | ✅ | python3 | ONE LINE | 🔥💪 | sahelriaz | 1 | 50 | valid anagram | 242 | 0.628 | Easy | 4,653 |
https://leetcode.com/problems/valid-anagram/discuss/2428946/Python-Solution-using-Collections | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if(len(s)!=len(t)):
return False
count = collections.Counter(s)
for ind,ch in enumerate(t):
if count[ch]==0 or ch not in count.keys():
return False
else:
count[ch]-=1
return True | valid-anagram | Python Solution using Collections | vishuvishnu1717 | 1 | 35 | valid anagram | 242 | 0.628 | Easy | 4,654 |
https://leetcode.com/problems/valid-anagram/discuss/2426051/Python3-One-liner-no-collections-or-imports | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t) | valid-anagram | [Python3] One liner, no collections or imports | connorthecrowe | 1 | 115 | valid anagram | 242 | 0.628 | Easy | 4,655 |
https://leetcode.com/problems/valid-anagram/discuss/2345717/Success-Details-Runtime%3A-42-ms-faster-than-97.46-of-Python3-online-submissions-for-Valid-Anagram | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
for c in 'abcdefghijklmnopqrstuvwxyz':
if s.count(c) != t.count(c): return False
return True | valid-anagram | Success Details Runtime: 42 ms, faster than 97.46% of Python3 online submissions for Valid Anagram | vimla_kushwaha | 1 | 19 | valid anagram | 242 | 0.628 | Easy | 4,656 |
https://leetcode.com/problems/valid-anagram/discuss/2344764/CPP-oror-JAVA-oror-KOTLIN-oror-PYTHON-oror-EASY-oror-EXPLAINED | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
c = [0]*26
for l in s:
c[ord(l)-ord('a')]+=1
for l in t:
c[ord(l)-ord('a')]-=1
for i in c:
if i!=0:
return False
return True | valid-anagram | CPP || JAVA || KOTLIN || PYTHON || EASY ✅|| EXPLAINED 🤗 | ken1000minus7 | 1 | 32 | valid anagram | 242 | 0.628 | Easy | 4,657 |
https://leetcode.com/problems/valid-anagram/discuss/2333971/Super-easy-one-line-solution-oror-Python-oror-Sorted | class Solution(object):
def isAnagram(self, s,t):
return sorted(s) == sorted(t) | valid-anagram | Super easy one line solution || Python || Sorted | kqi8_ | 1 | 71 | valid anagram | 242 | 0.628 | Easy | 4,658 |
https://leetcode.com/problems/valid-anagram/discuss/2135163/Python-in-built-counter-95.6-faster-93.2-less-memory | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s)==Counter(t)
# c1 = Counter(s)
# c2 = Counter(t)
# if c1 == c2:
# return True
# return False | valid-anagram | Python in-built counter 95.6% faster 93.2% less memory | notxkaran | 1 | 80 | valid anagram | 242 | 0.628 | Easy | 4,659 |
https://leetcode.com/problems/valid-anagram/discuss/2030770/Easiest-and-Fastest-Python-3-Solution | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if sorted(s) == sorted(t):
return True
else:
return False | valid-anagram | Easiest and Fastest Python 3 Solution | tanmay120 | 1 | 72 | valid anagram | 242 | 0.628 | Easy | 4,660 |
https://leetcode.com/problems/valid-anagram/discuss/2002510/Python-easy-to-read-and-understand-or-hashtable | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
d = collections.defaultdict(int)
for ch in s:
d[ch] = d.get(ch, 0) + 1
#print(d.items())
for ch in t:
if ch not in d:
return False
else:
if d[ch] == 0:
return False
else:
d[ch] -= 1
for key in d:
if d[key] > 0:
return False
return True | valid-anagram | Python easy to read and understand | hashtable | sanial2001 | 1 | 101 | valid anagram | 242 | 0.628 | Easy | 4,661 |
https://leetcode.com/problems/valid-anagram/discuss/1988612/Python3-Dictionary-solution-with-comments | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
# create empty dict
my_dict = dict()
# for each char in s, keep a count of the number of occurances
for char in s:
if char in my_dict:
my_dict[char] += 1
else:
my_dict[char] = 1
# subtract count for every char in t
for char in t:
if char in my_dict:
my_dict[char] -= 1
# new char dectected means not an anagram
else:
return False
# Check that every value in dict is 0
for value in my_dict.values():
if value != 0:
return False
return True | valid-anagram | [Python3] Dictionary solution with comments | keithlai124 | 1 | 66 | valid anagram | 242 | 0.628 | Easy | 4,662 |
https://leetcode.com/problems/valid-anagram/discuss/1976779/Python-runtime-33.07-memory-68.58 | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
d = dict()
for c in s:
if c not in d.keys():
d[c] = 1
else:
d[c] += 1
for c in t:
if c not in d.keys():
return False
else:
d[c] -= 1
for i in d.values():
if i != 0:
return False
return True | valid-anagram | Python, runtime 33.07%, memory 68.58% | tsai00150 | 1 | 50 | valid anagram | 242 | 0.628 | Easy | 4,663 |
https://leetcode.com/problems/valid-anagram/discuss/1958588/Python3-Easy-to-understand-94.01-97.46 | class Solution:
def isAnagram(self,s,t):
for i in set(s)|set(t):
if s.count(i) != t.count(i):
return False
return True | valid-anagram | Python3 Easy to understand 94.01% 97.46% | zhuyuliang0817 | 1 | 78 | valid anagram | 242 | 0.628 | Easy | 4,664 |
https://leetcode.com/problems/valid-anagram/discuss/1919264/One-Liner-oror-1-line-Code-oror-Python-3-oror-Python | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s)==Counter(t) | valid-anagram | One Liner || 1 line Code || Python 3 || Python | nileshporwal | 1 | 156 | valid anagram | 242 | 0.628 | Easy | 4,665 |
https://leetcode.com/problems/valid-anagram/discuss/1793473/Python-Simple-Python-Solution-With-Two-Approach-oror-94-Faster | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s)==len(t):
l=list(dict.fromkeys(t))
a=0
for i in l:
if s.count(i)==t.count(i):
a=a+1
if a==len(l):
return True
else:
return False
else:
return False | valid-anagram | [ Python ] ✅✅ Simple Python Solution With Two Approach || 94 % Faster 🔥🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 1 | 90 | valid anagram | 242 | 0.628 | Easy | 4,666 |
https://leetcode.com/problems/valid-anagram/discuss/1793473/Python-Simple-Python-Solution-With-Two-Approach-oror-94-Faster | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
frequency_s = {}
frequency_t = {}
for i in s:
if i not in frequency_s:
frequency_s[i] = 1
else:
frequency_s[i] = frequency_s[i] + 1
for j in t:
if j not in frequency_t:
frequency_t[j] = 1
else:
frequency_t[j] = frequency_t[j] + 1
if frequency_s == frequency_t:
return True
else:
return False | valid-anagram | [ Python ] ✅✅ Simple Python Solution With Two Approach || 94 % Faster 🔥🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 1 | 90 | valid anagram | 242 | 0.628 | Easy | 4,667 |
https://leetcode.com/problems/valid-anagram/discuss/1741210/Fastest-Python-Solution-beats-98.88-or-frequency-counter-or-collections | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
sCol=collections.Counter(s)
tCol=collections.Counter(t)
return sCol==tCol | valid-anagram | Fastest Python Solution beats 98.88% | frequency counter | collections | nerdytech | 1 | 112 | valid anagram | 242 | 0.628 | Easy | 4,668 |
https://leetcode.com/problems/valid-anagram/discuss/1738441/Easiest-Python-Solution-Using-Dictionary | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
#Create a dictionary which will store the frequency of each of character
d={}
#iterate over all the characters in the string 's'
for element in s:
if element in d:
#increse the frequency count by 1 if it is already there in the dictionary 'd'
d[element]+=1
else:
#initiate that element frequency by 1 in the 'd' if it is not there previously.
d[element]=1
#iterate over all the characters in the string 't'
for element in t:h
if element in d:
#decrease the frequency count by 1 so as to check the same frequency count of each character
d[element]-=1
else:
#if the element is not there in the dictionary that means that particular element is not there in the string 's' which tends the result to False
return False
for key,value in d.items():
if value!=0:
#Return False if the any of element value is not 0 after cancelling their each occurence from both side 's' and 't'
return False
return True`` | valid-anagram | 📍Easiest Python Solution Using Dictionary | AdityaTrivedi88 | 1 | 104 | valid anagram | 242 | 0.628 | Easy | 4,669 |
https://leetcode.com/problems/valid-anagram/discuss/1566559/Python-Easy-Solution-or-O(N)-Time | class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
res = [0]*26
for i in range(len(s)):
res[ord(s[i])-ord('a')] += 1
res[ord(t[i])-ord('a')] -= 1
for num in res:
if num != 0:
return False
return True | valid-anagram | Python Easy Solution | O(N) Time | leet_satyam | 1 | 147 | valid anagram | 242 | 0.628 | Easy | 4,670 |
https://leetcode.com/problems/valid-anagram/discuss/1300279/PythonorOne-linerorCounters | class Solution:
def isAnagram(self, s, t):
return Counter(s) == Counter(t) | valid-anagram | Python|One-liner|Counters | atharva_shirode | 1 | 144 | valid anagram | 242 | 0.628 | Easy | 4,671 |
https://leetcode.com/problems/binary-tree-paths/discuss/484118/Python-3-(beats-~100)-(nine-lines)-(DFS) | class Solution:
def binaryTreePaths(self, R: TreeNode) -> List[str]:
A, P = [], []
def dfs(N):
if N == None: return
P.append(N.val)
if (N.left,N.right) == (None,None): A.append('->'.join(map(str,P)))
else: dfs(N.left), dfs(N.right)
P.pop()
dfs(R)
return A
- Junaid Mansuri
- Chicago, IL | binary-tree-paths | Python 3 (beats ~100%) (nine lines) (DFS) | junaidmansuri | 7 | 1,100 | binary tree paths | 257 | 0.607 | Easy | 4,672 |
https://leetcode.com/problems/binary-tree-paths/discuss/1602321/Time-O(n*h)-beats-99.43-or-Space-O(h)-beats-99.39-or-Python-or-Simple-Explanation | class Solution:
def _dfs(self, root: Optional[TreeNode], cur, res) -> None:
# Base Case
if not root:
return
# Append node to path
cur.append(str(root.val))
# If root is a leaf, append path to result
if not root.left and not root.right:
res.append('->'.join(cur))
# Recursive Step
self._dfs(root.left, cur, res)
self._dfs(root.right, cur, res)
# Backtracking / Post-processing / pop node from path
cur.pop()
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
self._dfs(root, [], res)
return res | binary-tree-paths | Time O(n*h) beats 99.43% | Space O(h) beats 99.39 % | Python | Simple Explanation | PatrickOweijane | 6 | 251 | binary tree paths | 257 | 0.607 | Easy | 4,673 |
https://leetcode.com/problems/binary-tree-paths/discuss/2523403/Python-solutions-using-DFS-and-BFS | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root: return None
res = []
def paths(root, path):
if not any([root.left, root.right]):
res.append(path)
paths(root.left, path + '->' + str(root.left.val)) if root.left else None
paths(root.right, path + '->' + str(root.right.val)) if root.right else None
paths(root, str(root.val))
return res | binary-tree-paths | Python solutions using DFS and BFS | Sivle | 2 | 166 | binary tree paths | 257 | 0.607 | Easy | 4,674 |
https://leetcode.com/problems/binary-tree-paths/discuss/2523403/Python-solutions-using-DFS-and-BFS | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root: return None
q=[(root, str(root.val))]
res = []
while q:
node, path_upto_node = q.pop()
if not any([node.left, node.right]):
res.append(path_upto_node)
else:
q.append((node.left, path_upto_node + '->' + str(node.left.val))) if node.left else None
q.append((node.right, path_upto_node + '->' + str(node.right.val))) if node.right else None
return res | binary-tree-paths | Python solutions using DFS and BFS | Sivle | 2 | 166 | binary tree paths | 257 | 0.607 | Easy | 4,675 |
https://leetcode.com/problems/binary-tree-paths/discuss/1981927/Simple-Python-Recursive-Solution-using-Preorder-Traversal-with-Explanation | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
ans=[] # resultant list containing all paths.
def preorder(root,s):
if not root.left and not root.right: # If leaf node occurs then path ends here so append the string in 'ans'.
ans.append(s+str(root.val))
return
s+=str(root.val) # concatenate value of root in the path
if root.left: # If there is any node in left to traverse
preorder(root.left,s+"->")
if root.right: # If there is any node in right to traverse
preorder(root.right,s+"->")
return
preorder(root,"") # main calling of preOrder with empty string
return ans | binary-tree-paths | Simple Python Recursive Solution using Preorder Traversal with Explanation | HimanshuGupta_p1 | 2 | 95 | binary tree paths | 257 | 0.607 | Easy | 4,676 |
https://leetcode.com/problems/binary-tree-paths/discuss/1927251/Easy-Python-Recursive-Faster-Solution | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
s=""
def traversal(root,s,res):
if root:
s+=str(root.val)+"->"
if root.left==None and root.right==None:
res.append(s[:-2])
traversal(root.right,s,res)
traversal(root.left,s,res)
traversal(root,s,res)
return res | binary-tree-paths | Easy Python Recursive Faster Solution | harshitb93 | 2 | 151 | binary tree paths | 257 | 0.607 | Easy | 4,677 |
https://leetcode.com/problems/binary-tree-paths/discuss/1082155/WEEB-DOES-PYTHON-SUPER-FAST-BFS-(97-RUNTIME)-ITERATIVE-APPROACH-I-LOVE-ANIME | class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
if not root:
return []
queue = deque([(root, str(root.val))])
answers = []
while queue:
curNode, curPath = queue.popleft()
if not curNode.left and not curNode.right:
answers+= [curPath] # if list(curPath) it would give ["1","-",">","3","1","-",">","2","-",">","5"]
if curNode.left:
queue.append((curNode.left, curPath + "->" + str(curNode.left.val)))
if curNode.right:
queue.append((curNode.right, curPath + "->" + str(curNode.right.val)))
return answers | binary-tree-paths | WEEB DOES PYTHON SUPER FAST BFS (97% RUNTIME) ITERATIVE APPROACH I LOVE ANIME | Skywalker5423 | 2 | 133 | binary tree paths | 257 | 0.607 | Easy | 4,678 |
https://leetcode.com/problems/binary-tree-paths/discuss/2201438/Python-Recursive-Depth-First-Search-(DFS)-preorder-traversal | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
results = []
def binary_tree_paths(root, current_path: str):
if not root:
return
if not current_path:
current_path = str(root.val)
else:
current_path = f"{current_path}->{root.val}"
if not root.left and not root.right:
results.append(current_path)
return
binary_tree_paths(root.left, current_path)
binary_tree_paths(root.right, current_path)
binary_tree_paths(root, "")
return results | binary-tree-paths | [Python] Recursive Depth First Search (DFS), preorder traversal | julenn | 1 | 44 | binary tree paths | 257 | 0.607 | Easy | 4,679 |
https://leetcode.com/problems/binary-tree-paths/discuss/2840036/python-oror-simple-solution-oror-recursive-dfs | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
# if empty tree
if not root:
return []
ans = [] # answer
def dfs(node: Optional[TreeNode], path: str) -> None:
# add val to path
path += str(node.val)
# leaf node
if (not node.left) and (not node.right):
ans.append(path)
return
# left child exists
if node.left:
dfs(node.left, path + "->")
# right child exists
if node.right:
dfs(node.right, path + "->")
dfs(root, "")
return ans | binary-tree-paths | python || simple solution || recursive dfs | wduf | 0 | 1 | binary tree paths | 257 | 0.607 | Easy | 4,680 |
https://leetcode.com/problems/binary-tree-paths/discuss/2808333/Easy-Simply-Explained-Python-Solution-using-Inorder-traversal | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
output = []
def rootToLeaf(root,path):
if root.left == None and root.right == None:
output.append(path)
return
if root.left:
rootToLeaf(root.left,f'{path}->{root.left.val}')
if root.right:
rootToLeaf(root.right,f'{path}->{root.right.val}')
rootToLeaf(root,f'{root.val}')
return output | binary-tree-paths | Easy Simply Explained Python Solution using Inorder traversal | utkarshjain | 0 | 2 | binary tree paths | 257 | 0.607 | Easy | 4,681 |
https://leetcode.com/problems/binary-tree-paths/discuss/2703055/C%2B%2B-and-Python-Solution-based-on-PreOrder-Traversal | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
def preorder(root,l):
if root:
if (root.left==None and root.right==None):
res.append(l+[root.val])
else:
preorder(root.left,l+[root.val])
preorder(root.right,l+[root.val])
preorder(root,[])
return [('->'.join([str(k) for k in i]))for i in res] | binary-tree-paths | C++ and Python Solution based on PreOrder Traversal | chandu71202 | 0 | 7 | binary tree paths | 257 | 0.607 | Easy | 4,682 |
https://leetcode.com/problems/binary-tree-paths/discuss/2647280/O(n)-TC-oror-O(logn)-SC-ororBacktracking-oror-DFS-solution | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def dfs(root, path, res):
if not root.left and not root.right:
res.append(('->'.join([str(char) for char in path]) + '->' if path else "" ) + str(root.val))
return
if root.left:
dfs(root.left, path + [root.val], res)
if root.right:
dfs(root.right, path + [root.val], res)
res = []
dfs(root, [], res)
return res | binary-tree-paths | O(n) TC || O(logn) SC ||Backtracking || DFS solution | namanxk | 0 | 31 | binary tree paths | 257 | 0.607 | Easy | 4,683 |
https://leetcode.com/problems/binary-tree-paths/discuss/2643099/Kind-of-easy-to-understand-ig | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
left = self.binaryTreePaths(root.left)
right = self.binaryTreePaths(root.right)
path = [str(root.val) + "->"+i for i in left]
path += [str(root.val) + "->"+i for i in right]
return path | binary-tree-paths | Kind of easy to understand ig | utkarshukla1 | 0 | 13 | binary tree paths | 257 | 0.607 | Easy | 4,684 |
https://leetcode.com/problems/binary-tree-paths/discuss/2617532/Python3-or-Recursive-Solution | class Solution:
def __init__(self):
self.ans = []
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if root:
path = str(root.val)
self.search(root, path)
return self.ans
def search(self, root, path):
if not root.left and not root.right:
self.ans.append(path)
else:
if root.left:
path_l = path + '->' + str(root.left.val)
self.search(root.left, path_l)
if root.right:
path_r = path + '->' + str(root.right.val)
self.search(root.right, path_r) | binary-tree-paths | Python3 | Recursive Solution | joshua_mur | 0 | 15 | binary tree paths | 257 | 0.607 | Easy | 4,685 |
https://leetcode.com/problems/binary-tree-paths/discuss/2602892/DFS-python | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root :
return []
ans = []
def dfs(node, path):
if not node :
return
nonlocal ans
# add leaf node
if not node.left and not node.right :
path.append(str(node.val))
ans.append(path)
dfs(node.left, path + [str(node.val)])
dfs(node.right, path + [str(node.val)])
dfs(root, [])
res = ["->".join(x) for x in ans]
return res | binary-tree-paths | DFS python | kunal768 | 0 | 38 | binary tree paths | 257 | 0.607 | Easy | 4,686 |
https://leetcode.com/problems/binary-tree-paths/discuss/2576465/Python3-Stack-and-Map-Function | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
stack = [(root, [])]
paths = []
while stack:
node, path = stack.pop()
if not node:
continue
updated_path = list(path)
updated_path.append(node.val)
if not node.left and not node.right:
paths.append(updated_path)
stack.append((node.left, updated_path))
stack.append((node.right, updated_path))
return list(map(self.pathBuilder, paths))
def pathBuilder(self, path):
res = ''
for idx in range(len(path)):
if idx == 0:
res += f'{path[idx]}'
else:
res += f'->{path[idx]}'
return res | binary-tree-paths | Python3 Stack & Map Function | Mbarberry | 0 | 12 | binary tree paths | 257 | 0.607 | Easy | 4,687 |
https://leetcode.com/problems/binary-tree-paths/discuss/2490686/python3or-preorder-traversal-or-recursion | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
ans = []
an = ""
def preorder(root,an):
if root == None:
return
if(not root.left and not root.right):
an += str(root.val)
ans.append(an)
an += str(root.val) + "->"
preorder(root.left,an)
preorder(root.right,an)
preorder(root,an)
return ans | binary-tree-paths | python3| preorder traversal | recursion | rohannayar8 | 0 | 17 | binary tree paths | 257 | 0.607 | Easy | 4,688 |
https://leetcode.com/problems/binary-tree-paths/discuss/2488342/python-dfs-solution-very-understand | class Solution:
def solve(self , root , res , s ):
if(not root): return
if(not root.left and not root.right):
s += str(root.val)
res.append(s)
s += str(root.val) + "->"
self.solve(root.left , res , s)
self.solve(root.right , res , s)
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
s = ""
self.solve(root , res , s)
return res | binary-tree-paths | python dfs solution very understand | rajitkumarchauhan99 | 0 | 44 | binary tree paths | 257 | 0.607 | Easy | 4,689 |
https://leetcode.com/problems/binary-tree-paths/discuss/2444608/Python%3A-Easy-to-understand-solution | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
values = []
result = []
def path(root, values):
if root.left is None and root.right is None:
res = ''
for i in values:
res += ''.join(f'{i}->')
res += ''.join(str(root.val))
result.append(res)
if root.left is not None:
v = values.copy()
v.append(root.val)
path(root.left, v)
if root.right is not None:
v = values.copy()
v.append(root.val)
path(root.right, v)
path(root, values)
return result | binary-tree-paths | Python: Easy to understand solution | AliAlievMos | 0 | 63 | binary tree paths | 257 | 0.607 | Easy | 4,690 |
https://leetcode.com/problems/binary-tree-paths/discuss/2434736/Python3-Solution-with-using-dfs | class Solution:
def builder(self, node, cur_path, res):
if not node:
return
if not node.left and not node.right:
res.append('->'.join(cur_path + [str(node.val)]))
return
self.builder(node.left, cur_path + [str(node.val)], res)
self.builder(node.right, cur_path + [str(node.val)], res)
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
self.builder(root, [], res)
return res | binary-tree-paths | [Python3] Solution with using dfs | maosipov11 | 0 | 22 | binary tree paths | 257 | 0.607 | Easy | 4,691 |
https://leetcode.com/problems/binary-tree-paths/discuss/2414497/Python-94.32-faster-simple-helper-function-recursive | class Solution(object):
def binaryTreePaths(self, root):
ans = []
def helper(root, path):
if root.left == root.right == None:
ans.append(path+str(root.val))
return
if root.left:
helper(root.left, path+str(root.val)+'->')
if root.right:
helper(root.right, path+str(root.val)+'->')
helper(root, '')
return ans | binary-tree-paths | Python] 94.32% faster, simple helper function recursive | SteveShin_ | 0 | 42 | binary tree paths | 257 | 0.607 | Easy | 4,692 |
https://leetcode.com/problems/binary-tree-paths/discuss/2000321/Python-Clean-and-Simple!-Recursive-DFS | class Solution:
def binaryTreePaths(self, root):
self.paths = []
self.dfs(root)
return self.paths
def dfs(self, node, path=""):
path += str(node.val)
if node.left: self.dfs(node.left, path + "->")
if node.right: self.dfs(node.right, path + "->")
if not node.left and not node.right: self.paths.append(path) | binary-tree-paths | Python - Clean and Simple! Recursive DFS | domthedeveloper | 0 | 131 | binary tree paths | 257 | 0.607 | Easy | 4,693 |
https://leetcode.com/problems/binary-tree-paths/discuss/1922794/Python-Recursive-Solution-Faster-Than-84.39-Easy-To-Understand | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
v = []
def dfs(tree, s):
if not tree:
return
if tree.left is None and tree.right is None:
s += str(tree.val)
v.append(s)
s += str(tree.val) + '->'
dfs(tree.left, s)
dfs(tree.right, s)
dfs(root, "")
return v | binary-tree-paths | Python Recursive Solution, Faster Than 84.39%, Easy To Understand | Hejita | 0 | 59 | binary tree paths | 257 | 0.607 | Easy | 4,694 |
https://leetcode.com/problems/binary-tree-paths/discuss/1671761/Python-Recursion-Simple | class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
self.ans = []
def recurse(node, s):
if node is None:
return True
s += str(node.val)
left = recurse(node.left, s + "->")
right = recurse(node.right, s + "->")
if left and right:
self.ans.append(s)
recurse(root, '')
return self.ans | binary-tree-paths | Python Recursion Simple | mclovin286 | 0 | 152 | binary tree paths | 257 | 0.607 | Easy | 4,695 |
https://leetcode.com/problems/add-digits/discuss/2368005/Very-Easy-100-(Fully-Explained)(Java-C%2B%2B-Python-JS-C-Python3) | class Solution(object):
def addDigits(self, num):
while num > 9:
num = num % 10 + num // 10
return num | add-digits | Very Easy 100% (Fully Explained)(Java, C++, Python, JS, C, Python3) | PratikSen07 | 13 | 484 | add digits | 258 | 0.635 | Easy | 4,696 |
https://leetcode.com/problems/add-digits/discuss/2368005/Very-Easy-100-(Fully-Explained)(Java-C%2B%2B-Python-JS-C-Python3) | class Solution:
def addDigits(self, num: int) -> int:
while num > 9:
num = num % 10 + num // 10
return num | add-digits | Very Easy 100% (Fully Explained)(Java, C++, Python, JS, C, Python3) | PratikSen07 | 13 | 484 | add digits | 258 | 0.635 | Easy | 4,697 |
https://leetcode.com/problems/add-digits/discuss/1754357/Python3-Easiest-solution-its-a-Maths-trick. | class Solution:
def addDigits(self, num: int) -> int:
if num%9==0 and num!=0:
return 9
return num%9 | add-digits | Python3 Easiest solution, its a Maths trick. | manurag478 | 8 | 281 | add digits | 258 | 0.635 | Easy | 4,698 |
https://leetcode.com/problems/add-digits/discuss/948670/Python-one-liner | class Solution:
def addDigits(self, num: int) -> int:
if num%9==0 and num!=0:
return 9
else:
return num%9 | add-digits | Python one-liner | lokeshsenthilkumar | 7 | 546 | add digits | 258 | 0.635 | Easy | 4,699 |
Subsets and Splits