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/maximum-number-of-words-found-in-sentences/discuss/1646613/Python3-O(n)-or-2-solutions-or-With-Loop-%2B-1-Liner-or-Easy-to-Understand | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
m = 0
for s in sentences:
m = max(m, len(s.split()))
return m | maximum-number-of-words-found-in-sentences | [Python3] O(n) | 2 solutions | With Loop + 1 Liner | Easy to Understand | PatrickOweijane | 1 | 135 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,200 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/1646613/Python3-O(n)-or-2-solutions-or-With-Loop-%2B-1-Liner-or-Easy-to-Understand | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max(len(sentence.split()) for sentence in sentences) | maximum-number-of-words-found-in-sentences | [Python3] O(n) | 2 solutions | With Loop + 1 Liner | Easy to Understand | PatrickOweijane | 1 | 135 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,201 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2842845/Using-python-Lambda | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
sentences.sort(key=lambda x:len(x.split(' ')))
return len(sentences[-1].split(' ')) | maximum-number-of-words-found-in-sentences | Using python Lambda | pratiklilhare | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,202 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2824585/Python-Simple-Python-Solution-Using-Slpit-Function-or-94-Faster | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
result = 0
for sentence in sentences:
length = len(sentence.split())
result = max(result, length)
return result | maximum-number-of-words-found-in-sentences | [ Python ] ✅✅ Simple Python Solution Using Slpit Function | 94% Faster🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 5 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,203 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2815468/Fast-and-Simple-Python-Solution-(One-Liner-Code) | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max([len(i.split()) for i in sentences]) | maximum-number-of-words-found-in-sentences | Fast and Simple Python Solution (One-Liner Code) | PranavBhatt | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,204 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2807705/PYTHON3-BEST | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max(i.count(" ") for i in sentences) + 1 | maximum-number-of-words-found-in-sentences | PYTHON3 BEST | Gurugubelli_Anil | 0 | 5 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,205 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2797344/Simple-Python-Solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
res=0
for sentence in sentences:
# method 1:
if res<len(sentence.split(" ")):
res=len(sentence.split(" "))
# method 2:
# res=max(res,sentence.count(" ")+1)
return res | maximum-number-of-words-found-in-sentences | Simple Python Solution | sbhupender68 | 0 | 4 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,206 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2770399/oror-Python-oror-Easy-oror | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
ans = 0
for item in sentences:
ans = max(ans, len(item.split(' ')))
return ans | maximum-number-of-words-found-in-sentences | 🔥 || Python || Easy || 🔥 | parth_panchal_10 | 0 | 4 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,207 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2762109/Easy-python-solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
new_result=0
result_2 = [item.split(' ') for item in sentences]
for i in range(len(result_2)):
new_result=max(len(result_2[i]),new_result)
return new_result | maximum-number-of-words-found-in-sentences | Easy python solution | user7798V | 0 | 2 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,208 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2752755/Simple-Python3-OneLiner-solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max([len(x.split()) for x in sentences]) | maximum-number-of-words-found-in-sentences | Simple Python3 OneLiner solution | vivekrajyaguru | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,209 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2750816/Using-Python-Split-Function-easy-to-understand | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
maxi = 0
for i in range(len(sentences)):
x = list(sentences[i].split(" "))
if len(x)>maxi:
maxi = len(x)
return maxi | maximum-number-of-words-found-in-sentences | Using Python Split Function easy to understand | anand_sagar1128 | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,210 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2745763/One-line-solution-Python | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
max = 0
for sentence in sentences:
c = len(sentence.split(" "))
if c>max:
max = c
else:
continue
return max | maximum-number-of-words-found-in-sentences | One line solution - Python | avs-abhishek123 | 0 | 3 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,211 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2745763/One-line-solution-Python | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
max_m = 0
return max([len(sentence.split(" ")) if (len(sentence.split(" "))>max_m) else max_m for sentence in sentences]) | maximum-number-of-words-found-in-sentences | One line solution - Python | avs-abhishek123 | 0 | 3 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,212 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2728628/python-easy-solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
maxx = 0
for sen in sentences:
maxx = max(maxx, len(sen.split()))
return maxx | maximum-number-of-words-found-in-sentences | python easy solution | kruzhilkin | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,213 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2721922/PYTHON-or-Easy-One-Line-Solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max(( len(i.split(' ')) for i in sentences)) | maximum-number-of-words-found-in-sentences | PYTHON | Easy One Line Solution | mariusep | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,214 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2687697/for-loop-solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
p = []
for i in sentences:
p.append(i.split())
r = []
for z in p:
r.append(len(z))
return max(r) | maximum-number-of-words-found-in-sentences | for loop solution | ft3793 | 0 | 3 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,215 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2686495/Simple-Solution-in-Python | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
ans = []
for Li in sentences:
L =len(Li.split())
ans.append(L)
return ( max( ans)) | maximum-number-of-words-found-in-sentences | Simple Solution in Python | Baboolal | 0 | 1 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,216 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2671532/Python-solution-1-line | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max(list(map(lambda x: len(x.split(" ")), sentences))) | maximum-number-of-words-found-in-sentences | Python solution 1 line | phantran197 | 0 | 2 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,217 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2652630/Simple-python-solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
maxLength = 0
for i in sentences:
maxLength = max(maxLength,len(i.split()))
return maxLength | maximum-number-of-words-found-in-sentences | Simple python solution | shubhamshinde245 | 0 | 3 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,218 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2578658/Pythonoror-list-comprehensionoror-One-line-code | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max([len(i.split()) for i in sentences]) | maximum-number-of-words-found-in-sentences | Python|| list comprehension|| One line code | shersam999 | 0 | 53 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,219 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2520328/Python-Solution | class Solution:
def mostWordsFound(self, sent: List[str]) -> int:
count=0
n=len(sent)
for i in range(n):
m=len(sent[i].split(" "))
count=max(count,m)
return count | maximum-number-of-words-found-in-sentences | Python Solution | Sneh713 | 0 | 31 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,220 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2473621/Python-3-or-List-Comprehension-or-Easy-to-Understand-(With-References) | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
l = [len(i.split(" ")) for i in sentences]
return max(l) | maximum-number-of-words-found-in-sentences | Python 3 | List Comprehension | Easy to Understand (With References) | danny42 | 0 | 20 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,221 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2395233/2114.-Maximum-Number-of-Words-Found-in-Sentences%3A-One-liner | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max([len(sentence.split()) for sentence in sentences]) | maximum-number-of-words-found-in-sentences | 2114. Maximum Number of Words Found in Sentences: One liner | rogerfvieira | 0 | 27 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,222 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2395228/Two-Python-solutions-one-has-less-lines | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
# keep a running maxwords variable to update
# iterate each sentence in sentences
# split the sentences to get each word of the sentence
# get the length of the split sentence which defines the number of words
# set maxwords between it, and the amount fo words from the sentence
# Time O(N) Space O(N)
maxwords = 0
for sentence in sentences:
words = len(sentence.split())
maxwords = max(words, maxwords)
return maxwords
class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
# Second Solution with max()
return len(max(sentences, key=lambda x: len(x.split())).split()) | maximum-number-of-words-found-in-sentences | Two Python solutions, one has less lines | andrewnerdimo | 0 | 47 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,223 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2381978/Python3-one-line-answer | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
return max([sentence.count(" ") + 1 for sentence in sentences]) | maximum-number-of-words-found-in-sentences | Python3 one line answer | tawaca | 0 | 11 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,224 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2350695/Python-Perfect-solution-here | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
ans = 0
for sentence in sentences:
word_length = len(sentence.split())
if ans < word_length:
ans = word_length
return ans | maximum-number-of-words-found-in-sentences | Python Perfect solution here | RohanRob | 0 | 51 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,225 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2300348/easy-python-solution-fast!! | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
ls=[]
for i in sentences:
ls.append(len(i.split(" ")))
return max(ls) | maximum-number-of-words-found-in-sentences | easy python solution fast!! | HeyAnirudh | 0 | 58 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,226 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2299309/Python3-Multiple-solutions... | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
# Using loop
maxv = 0
for sentence in sentences:
words = sentence.split(" ")
maxv = max(maxv, len(words))
return maxv
# Using Map
def calculate(a):
return len(a.split(" "))
return max(map(calculate, sentences))
# Using map and lambda
return max(map(lambda x: len(x.split(" ")), sentences))
# Count spaces
return max(map(lambda x: x.count(" ") + 1, sentences)) | maximum-number-of-words-found-in-sentences | [Python3] Multiple solutions... | Gp05 | 0 | 20 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,227 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2238908/Python3-solution-using-count-function | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
count = []
for sentence in sentences:
count.append(sentence.count(" ")+1)
return max(count) | maximum-number-of-words-found-in-sentences | Python3 solution using count function | psnakhwa | 0 | 23 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,228 |
https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/2102834/understandable-to-python-beginner-or-easy-or-simple-solution | class Solution:
def mostWordsFound(self, sentences: List[str]) -> int:
c=0
m=0
for i in range(len(sentences)):
c=sentences[i].count(' ')
if c+1>m:
m=c+1
return m | maximum-number-of-words-found-in-sentences | understandable to python beginner | easy | simple solution | T1n1_B0x1 | 0 | 58 | maximum number of words found in sentences | 2,114 | 0.88 | Easy | 29,229 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646903/DFS | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
graph, can_make, supplies = {recipe : [] for recipe in recipes}, {}, set(supplies)
def dfs(recipe : str) -> bool:
if recipe not in can_make:
can_make[recipe] = False
can_make[recipe] = all([dfs(ingr) for ingr in graph[recipe]])
return can_make[recipe]
for i, recipe in enumerate(recipes):
for ingr in ingredients[i]:
if ingr not in supplies:
graph[recipe].append(ingr if ingr in graph else recipe)
return [recipe for recipe in recipes if dfs(recipe)] | find-all-possible-recipes-from-given-supplies | DFS | votrubac | 62 | 7,200 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,230 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646605/Python3-topological-sort-(Kahn's-algo) | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
indeg = defaultdict(int)
graph = defaultdict(list)
for r, ing in zip(recipes, ingredients):
indeg[r] = len(ing)
for i in ing: graph[i].append(r)
ans = []
queue = deque(supplies)
recipes = set(recipes)
while queue:
x = queue.popleft()
if x in recipes: ans.append(x)
for xx in graph[x]:
indeg[xx] -= 1
if indeg[xx] == 0: queue.append(xx)
return ans | find-all-possible-recipes-from-given-supplies | [Python3] topological sort (Kahn's algo) | ye15 | 53 | 4,100 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,231 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1664405/Beginners-Friendly-oror-Well-Explained-oror-94-Faster | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
graph = defaultdict(list)
in_degree = defaultdict(int)
for r,ing in zip(recipes,ingredients):
for i in ing:
graph[i].append(r)
in_degree[r]+=1
queue = supplies[::]
res = []
while queue:
ing = queue.pop(0)
if ing in recipes:
res.append(ing)
for child in graph[ing]:
in_degree[child]-=1
if in_degree[child]==0:
queue.append(child)
return res | find-all-possible-recipes-from-given-supplies | 📌📌 Beginners Friendly || Well-Explained || 94% Faster 🐍 | abhi9Rai | 40 | 2,600 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,232 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1815471/PYTHON3-BFS-EASY-TO-UNDERSTAND | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
adj=defaultdict(list)
ind=defaultdict(int)
for i in range(len(ingredients)):
for j in range(len(ingredients[i])):
adj[ingredients[i][j]].append(recipes[i])
ind[recipes[i]]+=1
ans=[]
q=deque()
for i in range(len(supplies)):
q.append(supplies[i])
while q:
node=q.popleft()
for i in adj[node]:
ind[i]-=1
if ind[i]==0:
q.append(i)
ans.append(i)
return ans | find-all-possible-recipes-from-given-supplies | [PYTHON3] BFS -EASY TO UNDERSTAND | wauuwauu | 8 | 761 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,233 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1653594/Brute-Force-Python-3-(Accepted)-(Commented) | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
ans = [] // Store the possible recipes
dict1 = {} //Map each recipe to its ingredient
supplies = set(supplies) //Converting to set in order to store unique supplies and avoid redundant checks
for i in range(len(recipes)):
dict1[recipes[i]] = ingredients[i] //Map each recipe to its ingredient
while True: // loop until terminating criteria is reached
temp = [] //temp array to store the non-possible reciepes for a particular iteration
for i in range(len(recipes)): //Iterage the reciepe array
flag = True // Assume each recipe is possible in the start
for j in range(len(dict1[recipes[i]])): //iterate each ingredient for each reciepe
if dict1[recipes[i]][j] not in supplies: // and check if its available in supplies
flag = False //if not available then set the flag to false
temp.append(recipes[i]) //and add the not possible(maybe as of now) reciepe to temp array
break //and break
if flag: //if the reciepe is possible
ans.append(recipes[i]) //then add the reciepe to ans array
supplies.add(recipes[i]) //also add the reciepe to the supply array as it is possible
if temp == recipes: //terminating criteria for while True loop if there is no change in temp array then break
break
else:
recipes = temp // else update the reciepes array with temp
return ans //Lastly return the ans | find-all-possible-recipes-from-given-supplies | Brute Force Python 3 (Accepted) (Commented) | sdasstriver9 | 3 | 249 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,234 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2023973/Python-Topological-Sort-with-Inline-Explanation | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
# Build a graph where vertices are ingredients and recipes
# and edges are in the form of <ingredient | recipe> -> recipe
graph = defaultdict(set)
indegree = defaultdict(int)
# O(R+I) where R is number of recipes and I is the max number of supplies for any given recipe
for recipe, ingredient in zip(recipes, ingredients):
for supply in ingredient:
graph[supply].add(recipe)
indegree[recipe] += 1
# First use all supplies to cook all the possible recipes
# O(S+R+I)
for supply in supplies:
for recipe in graph[supply]:
indegree[recipe] -= 1
# these are the recipes we can cook directly from the given supplies
recipes_with_zero_in_degree = [recipe for recipe in indegree if not indegree[recipe]]
# Final answer include these as well
ans = set(recipes_with_zero_in_degree)
# now let's see what are the recipes we can cook using the already cooked recipes
# We do a DFS where at each iteration we cook a recipe
# At each step if there is a new recipe we can cook (i.e., indegree=0)
# we add it back to the stack and the final answer
# O(R)
while recipes_with_zero_in_degree:
supply = recipes_with_zero_in_degree.pop()
for recipe in graph[supply]:
indegree[recipe] -= 1
if not indegree[recipe]:
recipes_with_zero_in_degree.append(recipe)
ans.add(recipe)
return ans | find-all-possible-recipes-from-given-supplies | Python Topological Sort with Inline Explanation | ashkan-leo | 2 | 231 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,235 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646779/Python-Coloring-the-graph | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
WHITE, GRAY, BLACK = 0, 1, 2
color = defaultdict(int)
supplies = set(supplies)
recipes_s = set(recipes)
graph = defaultdict(list)
# Create the graph
for i in range(len(recipes)):
for ingredient in ingredients[i]:
# Partially color the graph
# ingredient that requires another recipe always GRAY if the recipe doesn't exist
if ingredient not in recipes_s:
color[ingredient] = GRAY
# Ingredient in supplies always BLACK
if ingredient in supplies:
color[ingredient] = BLACK
graph[recipes[i]].append(ingredient)
def dfs(node):
if color[node] != WHITE:
return color[node] == BLACK
color[node] = GRAY
for ingredient in graph[node]:
if color[ingredient] == BLACK:
continue
if color[ingredient] == GRAY or not dfs(ingredient):
return False
color[node] = BLACK
return True
return [recipe for recipe in recipes if dfs(recipe)] | find-all-possible-recipes-from-given-supplies | [Python] Coloring the graph | asbefu | 2 | 170 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,236 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646638/Python3-O(V-%2B-E)-or-Topological-Sort-or-Kahn's-algorithm-or-BFS | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
inDeg = {s: 0 for s in supplies}
outAdj = {s: [] for s in supplies}
for r in recipes:
inDeg[r] = 0
outAdj[r] = []
for pres, cur in zip(ingredients, recipes):
inDeg[cur] = len(pres)
for p in pres:
if p not in outAdj:
outAdj[p] = []
inDeg[p] = 1
outAdj[p].append(cur)
level = [i for i in inDeg if inDeg[i] == 0]
while level:
nextLevel = []
for ing in level:
for adj in outAdj[ing]:
inDeg[adj] -= 1
if inDeg[adj] == 0:
nextLevel.append(adj)
level = nextLevel
return [r for r in inDeg if inDeg[r] == 0 and r in recipes] | find-all-possible-recipes-from-given-supplies | [Python3] O(V + E) | Topological Sort | Kahn's algorithm | BFS | PatrickOweijane | 2 | 214 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,237 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2272128/DFS-with-memoization-oror-DP-oror-Python | class Solution(object):
def findAllRecipes(self, recipes, ingredients, supplies):
"""
:type recipes: List[str]
:type ingredients: List[List[str]]
:type supplies: List[str]
:rtype: List[str]
"""
supplies=set(supplies)
graph={}
can_make={}
def recur(r):
if(r in supplies):
return True
if(r not in supplies and r not in graph):
return False
if(r not in can_make):
can_make[r]=False
rs=False
for ing in graph[r]: #All ingredients for that reciepe should be possible to be made
if(recur(ing)): # True if it is either in supplies or it was a recipie which as possible to be made
rs=True
else:
rs=False
break
can_make[r]=rs
return can_make[r]
#Convert to graph
for i in range(len(recipes)):
recipe=recipes[i]
graph[recipe]=[]
for ing in ingredients[i]:
graph[recipe].append(ing)
#Check if each recipie is possible
res=[]
for rec in recipes:
if(recur(rec)):
res.append(rec)
return res | find-all-possible-recipes-from-given-supplies | DFS with memoization || DP || Python | ausdauerer | 1 | 55 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,238 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1734855/Short-python3-brute-force-solution | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
res=set()
s=set(supplies)
mydict={}
for j in range(len(recipes)):
for i in range(len(recipes)):
recipe=recipes[i]
req=ingredients[i]
if recipe not in s:
if all(val in s for val in req):
res.add(recipe)
if len(res)==len(recipes):
return list(res)
s.add(recipe)
return list(res) | find-all-possible-recipes-from-given-supplies | Short python3 brute force solution | Karna61814 | 1 | 50 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,239 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1653465/Simple-DFS-Solution-with-comments | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
indicies = {}
cache = {}
answer = []
for i in range(len(recipes)):
indicies[recipes[i]] = i
for i in range(len(supplies)):
cache[supplies[i]] = True
for recipe in recipes:
if self.canMake(recipe, indicies, cache, ingredients):
answer.append(recipe)
# print(cache)
return answer
def canMake(self, toMake, indicies, cache, ingredients):
# if we have tried making this before, we know if we can or cannot
# all supplies should be in here
if toMake in cache:
return cache[toMake]
cache[toMake] = False
# if its not something we have tried to make before, it must be a recipe or something that is not a supply or recipe
# check if it is a recipe, if not, this is neither a recipe or a supply and we can never make this
if toMake not in indicies:
return False
# at this point, its definitely a recipe
index = indicies[toMake]
# simply check if we can make each ingredient, end early if not
for ingredient in ingredients[index]:
if not self.canMake(ingredient, indicies, cache, ingredients):
return False
cache[toMake] = True
return True | find-all-possible-recipes-from-given-supplies | Simple DFS Solution with comments | jdot593 | 1 | 118 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,240 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646756/Python3-recursive-DFS | class Solution:
def dfs_visit(self, n):
if self.ins[n]:
return
while self.out[n]:
o = self.out[n].pop()
if n in self.ins[o]:
self.ins[o].remove(n)
self.dfs_visit(o)
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
out = defaultdict(list)
ins = defaultdict(set)
for i, r in enumerate(recipes):
ins[r] = set(ingredients[i])
for i, ing in enumerate(ingredients):
for k in ing:
out[k].append(recipes[i])
self.ins = ins
self.out = out
for supply in supplies:
self.dfs_visit(supply)
return [r for r in recipes if not self.ins[r]] | find-all-possible-recipes-from-given-supplies | [Python3] recursive DFS | dwschrute | 1 | 143 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,241 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2770911/DFS-%2B-Cycle-detection | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
supplies_set = set(supplies)
recipes_dict: Dict[str, List[str]] = {recipes[i]: ingredients[i] for i in range(len(recipes))} # Build a dictionary for quick access
memo: Dict[str, bool] = {sup: True for sup in supplies}
def dfs(rec: str, seen: Set[str]) -> bool:
if rec in memo:
return memo[rec]
if rec not in recipes_dict and rec not in supplies: # for ingredients that is not in supplies
return False
if rec in seen:
return False
seen.add(rec)
ans: bool = True
for ing in recipes_dict[rec]:
ans = ans and dfs(ing, seen)
if not ans:
break
memo[rec] = ans
return ans
valid_recipes: List[str] = []
for rec in recipes:
seen = set([]) # Add this to avoid cycle
if dfs(rec, seen):
valid_recipes.append(rec)
return valid_recipes | find-all-possible-recipes-from-given-supplies | DFS + Cycle detection | fengdi2020 | 0 | 10 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,242 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2512652/Efficent-Python3-BFS-Solution | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
recipeHash = collections.defaultdict(list)
supplySet = set()
for i in supplies:
supplySet.add(i)
for i in range(len(recipes)):
for j in ingredients[i]:
if j not in supplySet:
recipeHash[recipes[i]].append(j)
q = deque()
for r in recipes:
if not recipeHash[r]:
q.append(r)
res = []
while q:
for i in range(len(q)):
cur = q.popleft()
supplySet.add(cur)
res.append(cur)
for r in recipes:
if cur in recipeHash[r]:
recipeHash[r].remove(cur)
if not recipeHash[r]:
q.append(r)
return res | find-all-possible-recipes-from-given-supplies | Efficent Python3 BFS Solution | ys2674 | 0 | 42 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,243 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2488548/FULLY-EXPLAINED-Khan's-Algorithm%3A-Optimized-vs-Easy-Python-Solution | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
#SOLUTION: TOPOLOGICAL SORT USING KHANS ALGORITHM. FIRST, GIVEN THE SUPPLIES, REMOVE THEM FROM THE INGREDIENTS (this makes the runtime faster). CREATE INITIAL QUEUE, RUN KHANS ALGORITHM:
#we have a queue which holds 0 indegree nodes
#at every iteration, we pop from the queue and remove this current node from all the other node's dependencies
#if the updated node dependency is now 0, we add it to the queue
#ANOTHER SOLUTION AT BOTTOM: set the intial queue to the list of supplies (since those have indegrees of 0)
#slower, but less code
#set for faster lookup
s = set()
for sup in supplies:
s.add(sup)
adjList = {}
#new ingredients list, where it doesnt contain any supplies that are given
newIngreds = []
for arr in ingredients:
#temp array storing which supplies weren't given
toKeep = []
for sup in arr:
if sup not in s:
toKeep.append(sup)
newIngreds.append(toKeep)
queue = []
for r, i in zip(recipes, newIngreds):
adjList[r] = i
#add to initial queue
if i == []:
queue.append(r)
res = []
while queue:
visitNext = queue.pop()
res.append(visitNext)
for node in adjList:
if visitNext in adjList[node]:
adjList[node].remove(visitNext)
if adjList[node] == []:
queue.append(node)
return res
'''
class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
s = set()
for sup in supplies:
s.add(sup)
adjList = {}
queue = supplies
for r, i in zip(recipes, ingredients):
adjList[r] = i
res = []
while queue:
visitNext = queue.pop()
if visitNext not in s:
res.append(visitNext)
for node in adjList:
if visitNext in adjList[node]:
adjList[node].remove(visitNext)
if adjList[node] == []:
queue.append(node)
return res
''' | find-all-possible-recipes-from-given-supplies | FULLY EXPLAINED Khan's Algorithm: Optimized vs Easy Python Solution | yaahallo | 0 | 37 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,244 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2361851/Python-Brute-Force-using-set-(easy-to-understand) | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
supplies_set = set(supplies)
res = set()
# Iterate until no more change in the res set
changed = True
while changed:
changed = False
for i in range(len(recipes)):
if recipes[i] not in res:
for j in range(len(ingredients[i])):
if ingredients[i][j] not in supplies_set:
break
else:
res.add(recipes[i])
supplies_set.add(recipes[i])
changed = True
return list(res) | find-all-possible-recipes-from-given-supplies | Python Brute Force using set (easy to understand) | lau125 | 0 | 34 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,245 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2336949/Python3-or-Beats-around-80-of-solutions-in-Runtime | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
#Let m = len(supplies)
#Time-Complexity: O(3n + n*m +n + n*m + n*n) -> O(n^2 + n*m)
#Space-Complexity: O(n*m + n + m + n*n +n + n + n) -> O(n*m + n^2)
n = len(recipes)
hashmap = {}
indegrees = {recipe: 0 for recipe in recipes}
supplies2 = set(supplies)
#add the mapping of each recipe to needed ingredients inside hashmap for easy
#accessing!
for i in range(n):
hashmap[recipes[i]] = ingredients[i]
#build graph of all the required dependency! edges go from
#required recipe to another recipe!
adj = {recipe: [] for recipe in recipes}
all_possible_recipes = set(recipes)
#updating indegrees array as well!
for a in range(n):
cur = recipes[a]
required = hashmap[cur]
for ingredient in required:
#this would mean that current recipe depends on the ingredient
#which in itself is another recipe! -> record in adj list!
if(ingredient in all_possible_recipes):
adj[ingredient].append(cur)
indegrees[cur] += 1
queue = deque()
#add to queue all nodes with indegrees of 0(requiring no prereqs)
for recipe in recipes:
if(indegrees[recipe] == 0):
queue.append(recipe)
output = set()
while queue:
cur_recipe = queue.pop()
needed = hashmap[cur_recipe]
canmake = True
for need in needed:
#we can't create current recipe and any of recipes that depend on it!
if(need not in supplies2):
canmake = False
break
if(canmake):
output.add(cur_recipe)
supplies2.add(cur_recipe)
#iterate through all neighbors!
neighbors = adj[cur_recipe]
for neighbor in neighbors:
indegrees[neighbor] -= 1
if(indegrees[neighbor] == 0):
queue.append(neighbor)
return list(output) | find-all-possible-recipes-from-given-supplies | Python3 | Beats around 80% of solutions in Runtime | JOON1234 | 0 | 81 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,246 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2333583/Python-Clean-Optimized-BruteForce | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
res = set()
supplies = set(supplies)
product_to_recipes = dict(zip(recipes, ingredients))
while True:
new_supplies = False
for recipe in set(product_to_recipes).difference(res):
if recipe not in supplies and set(product_to_recipes[recipe]).issubset(supplies):
new_supplies = True
supplies.add(recipe)
res.add(recipe)
if not new_supplies:
return res
return res | find-all-possible-recipes-from-given-supplies | Python Clean Optimized BruteForce | jcraddock94 | 0 | 32 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,247 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2270176/Python-Topological-Sort | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
graph = {}
for i in range(len(ingredients)):
for item in ingredients[i]:
if item not in graph.keys():
graph[item] = [recipes[i]]
else:
graph[item].append(recipes[i])
for item in supplies:
if item not in graph.keys():
graph[item] = []
for item in recipes:
if item not in graph.keys():
graph[item] = []
indegree = {}
for i in range(len(ingredients)):
indegree[recipes[i]] = len(ingredients[i])
stack = []
independent_items=[]
for item in supplies:
stack.append(item)
while len(stack)!=0:
x = stack.pop(0)
independent_items.append(x)
for item in graph[x]:
indegree[item]-=1
if indegree[item]==0:
stack.append(item)
new_supply = {supplies[i]:True for i in range(len(supplies))}
ans = []
for item in independent_items:
if item not in new_supply.keys():
ans.append(item)
return ans | find-all-possible-recipes-from-given-supplies | Python Topological Sort | user7457RV | 0 | 56 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,248 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2264580/Python3-or-Kahn's-Algorithm | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
indegree=defaultdict(int)
graph=defaultdict(list)
for recipe,ing in zip(recipes,ingredients):
indegree[recipe]=len(ing)
for each in ing:
graph[each].append(recipe)
ans=[]
q=deque(supplies)
recipes=set(recipes)
while q:
currItem=q.popleft()
if currItem in recipes:
ans.append(currItem)
for item in graph[currItem]:
indegree[item]-=1
if indegree[item]==0:
q.append(item)
return ans | find-all-possible-recipes-from-given-supplies | [Python3] | Kahn's Algorithm | swapnilsingh421 | 0 | 43 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,249 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2133163/Python3 | class Solution:
def findAllRecipes(self, recipes: list[str], ingredients: list[list[str]], supplies: list[str]) -> list[str]:
completed: set[str] = set[str]()
def checkSupplies(dishIndex: int, visited: list[str]) -> bool:
for ingred in ingredients[dishIndex]:
if ingred in completed:
continue
if ingred in visited:
return False
if ingred in supplies:
continue
if ingred not in recipes:
return False
if not checkSupplies(recipes.index(ingred),visited+[ingred]):
return False
completed.add(recipes[dishIndex])
return True
for i,dish in enumerate(recipes):
checkSupplies(i,[])
return completed | find-all-possible-recipes-from-given-supplies | Python3 | ComicCoder023 | 0 | 44 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,250 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/2004065/Python-or-DFS | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
ans=[]
def dfs(i):
if i in seen:
return
seen.add(i)
flag=True
for ing in ingredients[i]:
if ing not in supplies and ing not in ans:
flag=False
if ing not in recipes:
break
j=recipes.index(ing)
dfs(j)
if ing in ans:
flag=True
else:
break
if flag:
ans.append(recipes[i])
seen=set()
for i in range(len(recipes)):
dfs(i)
return ans | find-all-possible-recipes-from-given-supplies | Python | DFS | heckt27 | 0 | 89 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,251 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1964518/Python-Simple-easy-to-understand-Faster-than-99.38 | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
sup = set(supplies)
graph = defaultdict(set)
rgraph = defaultdict(set)
q = collections.deque()
for i,r in enumerate(recipes):
for j in ingredients[i]:
if j not in sup:
graph[r].add(j)
rgraph[j].add(r)
if r not in graph:
q.append(r)
res = []
while q:
r = q.popleft()
res.append(r)
for need in rgraph[r]:
graph[need].remove(r)
if len(graph[need]) == 0:
q.append(need)
return res | find-all-possible-recipes-from-given-supplies | Python Simple easy to understand Faster than 99.38% | Sameer177 | 0 | 115 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,252 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1928317/Python-DFS-with-Memoization.-Beats-97.66 | class Solution:
def dfs(self, i, res, visited, g, supplySet, dp, currRec):
currRec.add(i)
visited.add(i)
for j in g[i]:
# if j in supplyset, go to the next ingredient
if j in supplySet:
continue
# if j in visited, thjat indicates a cycle
if j in visited:
return False
# if we have already processed that the ingredient can't be made, return False
if j in dp and dp[j] == False:
return False
# This is where we do the processing. If j is not in suppllyset,
# we check whether the ingredient cant be made.
if (j not in supplySet and j not in currRec):
# the ingredient is not in reipe list, hence cannot be made
if j not in g:
return False
# after dfs, if we came to know that the ingredient can't be made, return False
if not self.dfs(j,res, visited,g ,supplySet,dp,currRec):
return False
# the ith recipe can be made, so add it to the map saying that the recipe can be made.
dp[i] = True
# Adding to supplyset for faster processing. check line 8
supplySet.add(i)
visited.remove(i)
return True
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
# create a set of supplies to for O(1) retrieval
supplySet = set(supplies)
# create a graph of recipe -> ingredients
g = defaultdict(list)
# create a graph of recipe -> ingredients
for i in range(len(recipes)):
for j in ingredients[i]:
g[recipes[i]].append(j)
visited = set()
currRec = set()
res = []
"""
dp[i] can be used to store the whether the recipe can be made or not.
dp[i] = False means we have processed the ingredients of the recipe and we have come to know tha tthe recipe cant be made.
"""
dp = {}
# iterate through recipes
for i in recipes:
# if the recipe has been already processed and dp[i] = True,
# it means that the recipe can be made.
if i in dp and dp[i] == True:
res.append(i)
elif i not in currRec:
# if the recipe has not been already checked, iterate through the ingredients
if self.dfs(i, res, visited, g,supplySet,dp ,currRec):
dp[i] = True
res.append(i)
else:
dp[i] = False
return res | find-all-possible-recipes-from-given-supplies | [Python] DFS with Memoization. Beats 97.66% | maverick02 | 0 | 108 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,253 |
https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1760445/python-3-oror-dfs-oror-self-understandable-oror-Easy-understanding | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
available_ingredients=[]
cook={}
for ing in supplies:
available_ingredients.append(ing)
for rec in range(len(recipes)):
cook[recipes[rec]]=ingredients[rec]
def canCook(recipe,waiting):
needed_ingrediants=cook[recipe]
count=0
for ing in needed_ingrediants:
if ing in waiting:
return False
if ing in available_ingredients:
count+=1
elif ing in recipes:
waiting.append(ing)
if canCook(ing,waiting):
available_ingredients.append(ing)
count+=1
return count==len( needed_ingrediants)
result=[]
for recipe in recipes:
if canCook(recipe,[]):
result.append(recipe)
return result | find-all-possible-recipes-from-given-supplies | python 3 || dfs || self-understandable || Easy-understanding | bug_buster | 0 | 150 | find all possible recipes from given supplies | 2,115 | 0.485 | Medium | 29,254 |
https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1646594/Left-to-right-and-right-to-left | class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
def validate(s: str, locked: str, op: str) -> bool:
bal, wild = 0, 0
for i in range(len(s)):
if locked[i] == "1":
bal += 1 if s[i] == op else -1
else:
wild += 1
if wild + bal < 0:
return False
return bal <= wild
return len(s) % 2 == 0 and validate(s, locked, '(') and validate(s[::-1], locked[::-1], ')') | check-if-a-parentheses-string-can-be-valid | Left-to-right and right-to-left | votrubac | 175 | 8,600 | check if a parentheses string can be valid | 2,116 | 0.315 | Medium | 29,255 |
https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1646610/Python3-greedy-2-pass | class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
if len(s)&1: return False
bal = 0
for ch, lock in zip(s, locked):
if lock == '0' or ch == '(': bal += 1
elif ch == ')': bal -= 1
if bal < 0: return False
bal = 0
for ch, lock in zip(reversed(s), reversed(locked)):
if lock == '0' or ch == ')': bal += 1
elif ch == '(': bal -= 1
if bal < 0: return False
return True | check-if-a-parentheses-string-can-be-valid | [Python3] greedy 2-pass | ye15 | 9 | 737 | check if a parentheses string can be valid | 2,116 | 0.315 | Medium | 29,256 |
https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/2670969/Two-pass-O(n)-solution-with-very-easy-to-understand-explanation | class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
if len(s)%2 == 1:
return False
#Two pass solution
#Left to right, check if there are enough "(" (including the locked==0 ones, that can be changed as we wish) to match ")".
Number_of_open_brackets = 0
Number_of_closing_brackets = 0
for i in range(len(s)):
if s[i] == '(' or locked[i] == '0':
Number_of_open_brackets += 1
else:
Number_of_closing_brackets += 1
if Number_of_closing_brackets > Number_of_open_brackets:
return False
#Right to Left, check if there are enough ")" (including the locked==0 ones, that can be changed as we wish) to match "(".
Number_of_open_brackets = 0
Number_of_closing_brackets = 0
for i in range(len(s)-1, -1, -1):
if s[i] == ')' or locked[i] == '0':
Number_of_closing_brackets += 1
else:
Number_of_open_brackets += 1
if Number_of_open_brackets > Number_of_closing_brackets:
return False
return True
#Need two pass because left to right one pass will not fix edge cases such as "))((", 0011. The two ( are apparently waiting to see if on the right side there is enough ) to match them | check-if-a-parentheses-string-can-be-valid | Two pass O(n) solution with very easy to understand explanation | Arana | 0 | 22 | check if a parentheses string can be valid | 2,116 | 0.315 | Medium | 29,257 |
https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1943058/Python3-solution-or-Faster-than-100-or-Single-iteration | class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
if len(s) % 2 == 1:
return False
open_count, options, options_borrowed = 0, 0, 0
for i in range(len(s)):
if locked[i] == "0":
if open_count:
open_count -= 1
options_borrowed += 1
else:
options += 1
continue
if s[i] == "(":
open_count += 1
continue
if open_count:
open_count -= 1
elif options_borrowed:
options_borrowed -= 1
options += 1
elif options:
options -= 1
else:
return False
if open_count:
return False
return True | check-if-a-parentheses-string-can-be-valid | Python3 solution | Faster than 100% | Single iteration | eden_mesfin | 0 | 237 | check if a parentheses string can be valid | 2,116 | 0.315 | Medium | 29,258 |
https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1889192/C%2B%2B-Python3-Count | class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
if len(s) % 2 == 1:
return False
# Left to right, try to balance ")"
balance = 0
for i in range(len(s)):
if s[i] == "(" or locked[i] == "0":
balance += 1
else:
balance -= 1
if balance < 0:
return False
# Right to left, try to balance "("
balance = 0
for i in range(len(s) - 1, -1, -1):
if s[i] == ")" or locked[i] == "0":
balance += 1
else:
balance -= 1
if balance < 0:
return False
return True | check-if-a-parentheses-string-can-be-valid | C++, Python3 Count | shtanriverdi | 0 | 162 | check if a parentheses string can be valid | 2,116 | 0.315 | Medium | 29,259 |
https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1646615/Python3-quasi-brute-force | class Solution:
def abbreviateProduct(self, left: int, right: int) -> str:
ans = prefix = suffix = 1
trailing = 0
flag = False
for x in range(left, right+1):
if not flag:
ans *= x
while ans % 10 == 0: ans //= 10
if ans >= 1e10: flag = True
prefix *= x
suffix *= x
while prefix >= 1e12: prefix //= 10
while suffix % 10 == 0:
trailing += 1
suffix //= 10
if suffix >= 1e10: suffix %= 10_000_000_000
while prefix >= 100000: prefix //= 10
suffix %= 100000
if flag: return f"{prefix}...{suffix:>05}e{trailing}"
return f"{ans}e{trailing}" | abbreviating-the-product-of-a-range | [Python3] quasi brute-force | ye15 | 10 | 525 | abbreviating the product of a range | 2,117 | 0.28 | Hard | 29,260 |
https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1646731/Python-almost-brute-force | class Solution:
def abbreviateProduct(self, left: int, right: int) -> str:
#Step1: count the num of trailing zeros
factor_two, factor_five = 0, 0
curr_factor = 2
while curr_factor <= right:
factor_two += (right // curr_factor) - ((left - 1) // curr_factor)
curr_factor *= 2
curr_factor = 5
while curr_factor <= right:
factor_five += (right // curr_factor) - ((left - 1) // curr_factor)
curr_factor *= 5
trailing_zeros = min(factor_two, factor_five)
#Step2: Multiply until it gets too big, while dividing 2 and 5
divide_two_so_far, divide_five_so_far = 0, 0
curr_num = 1
for i in range(left, right + 1):
multiply = i
while multiply % 2 == 0 and divide_two_so_far < trailing_zeros:
multiply //= 2
divide_two_so_far += 1
while multiply % 5 == 0 and divide_five_so_far < trailing_zeros:
multiply //= 5
divide_five_so_far += 1
curr_num *= multiply
if curr_num >= 10 ** 10:
break
#if the number doesn't get too large (less than or equal to 10 digits)
if curr_num < 10 ** 10:
return str(curr_num) + 'e' + str(trailing_zeros)
#Step2: if the number exceeds 10 ** 10, then keep track of the first and last digits
first_digits, last_digits = int(str(curr_num)[:12]), int(str(curr_num)[-5:])
start = i + 1
for i in range(start, right + 1):
multiply = i
while multiply % 2 == 0 and divide_two_so_far < trailing_zeros:
multiply //= 2
divide_two_so_far += 1
while multiply % 5 == 0 and divide_five_so_far < trailing_zeros:
multiply //= 5
divide_five_so_far += 1
first_digits = int(str(first_digits * multiply)[:12])
last_digits = int(str(last_digits * multiply)[-5:])
#output
return str(first_digits)[:5] + '...' + '{:>05d}'.format(last_digits) + 'e' + str(trailing_zeros) | abbreviating-the-product-of-a-range | Python, almost brute force | kryuki | 2 | 127 | abbreviating the product of a range | 2,117 | 0.28 | Hard | 29,261 |
https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/2489728/Best-Python3-implementation-(Top-96.6)-oror-Easy-to-understand | class Solution:
def abbreviateProduct(self, left: int, right: int) -> str:
c2 = c5 = 0
top12 = tail5 = 1
for i in range(left, right+1):
# count and remove all 2 and 5
while i % 2 == 0:
i //= 2
c2 += 1
while i % 5 == 0:
i //= 5
c5 += 1
# track top 12 and last 5
top12 = int(str(top12 * i)[:12])
tail5 = tail5 * i % 100000
# multiply the remained 2 or 5
if c2 > c5:
for _ in range(c2 - c5):
top12 = int(str(top12 * 2)[:12])
tail5 = tail5 * 2 % 100000
elif c2 < c5:
for _ in range(c5 - c2):
top12 = int(str(top12 * 5)[:12])
tail5 = tail5 * 5 % 100000
zero = min(c2, c5)
# as is included in top 12, it's easy to tell when d<=10
if len(str(top12))<=10:
return str(top12)+'e'+str(zero)
return str(top12)[:5] + '.'*3 + '0'*(5-len(str(tail5)))+str(tail5)+'e'+str(zero) | abbreviating-the-product-of-a-range | ✔️ Best Python3 implementation (Top 96.6%) || Easy to understand | explusar | 0 | 25 | abbreviating the product of a range | 2,117 | 0.28 | Hard | 29,262 |
https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1792012/Python3-accepted-solution-(using-rstrip) | class Solution:
def abbreviateProduct(self, left: int, right: int) -> str:
product=1
for i in range(left,right+1):
product *= i
if(len(str(product).rstrip("0"))<=10):
return str(product).rstrip("0") + "e" + str(len(str(product)) - len(str(product).rstrip("0")))
else:
return str(product).rstrip("0")[:5] +"..."+ str(product).rstrip("0")[-5:]+"e" + str(len(str(product)) - len(str(product).rstrip("0"))) | abbreviating-the-product-of-a-range | Python3 accepted solution (using rstrip) | sreeleetcode19 | 0 | 69 | abbreviating the product of a range | 2,117 | 0.28 | Hard | 29,263 |
https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1656189/Brute-Force-Approach-Python3-(Accepted)-(Commented) | class Solution:
def abbreviateProduct(self, left: int, right: int) -> str:
ans = 1 //Initialise the product with 1
while left <= right: // Start the multiplying numbers in
if left == right: // Exception case when left is right else the number will be multiplied 2 times
ans *= left //then only multiply either left or right
else:
ans *= left * right // Else multiply left and right numbers and multiply with ans
left += 1 // Increment left by one
right -= 1 //Decrement right by 1
count = 0 // Initialise count of trailing zeroes
ans = str(ans) // Converting integer to string
i = len(ans) - 1 // Start the pointer with end of string
while i >= 0 and ans[i] == '0': // Decrement pointer by one while the value at pointer is 0
count += 1 //and increase the count of trailing zeroes
i -= 1
fans = '' //Empty string which will store the number without the trailing zeroes
for j in range(i+1): // will use the i pointer which stored the last location of the trailing zero
fans += ans[j] //store each character until the trailing zero isn't reached
final = '' //Final ans which will give the required result
if len(fans) > 10: //If the length of the number without the trailing zeroes has a length greater than 10
temp1 = '' //Will store the first 5 character of the number
for j in range(5): // Adding the first 5 characters
temp1 += fans[j]
temp2 = '' //Will store the last 5 characters of the number
for j in range(-5,0): // Add the last 5 characters
temp2 += fans[j]
final = temp1 + '...' + temp2 + 'e' + str(count) //Final ans with first 5 character, last 5 characters + e + count of trailing zeroes
else: //If length of the number is less than 10
final = fans + 'e' + str(count) // Final ans with number without trailing zeroes + e + count of trailing zeroes
return final //Return the final string | abbreviating-the-product-of-a-range | Brute Force Approach Python3 (Accepted) (Commented) | sdasstriver9 | 0 | 52 | abbreviating the product of a range | 2,117 | 0.28 | Hard | 29,264 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1648940/Python3-1-Liner-or-O(1)-Time-and-Space-or-Short-and-Clean-Explanation | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return not num or num % 10 | a-number-after-a-double-reversal | [Python3] 1 Liner | O(1) Time and Space | Short and Clean Explanation | PatrickOweijane | 12 | 578 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,265 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2644942/Easy-Python-solution-with-explanation | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
# False cases are those if last the digit of any 2(+) digit number = 0
if len(str(num)) > 1 and str(num)[-1] == "0":
return False
else:
# Else, every integer is true
return True | a-number-after-a-double-reversal | Easy Python solution with explanation | code_snow | 2 | 95 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,266 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1683508/4-lines-python-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num==0:return True
string=str(num)
rev="".join(list("".join(list(string)[::-1]).lstrip("0"))[::-1])
return True if string==rev else False | a-number-after-a-double-reversal | 4 lines python solution | amannarayansingh10 | 2 | 147 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,267 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1988231/Python3-One-Line-Solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return (num == 0) or (num % 10) | a-number-after-a-double-reversal | [Python3] One-Line Solution | terrencetang | 1 | 45 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,268 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1768007/python-3-simple-solution-or-O(1)-or-88-lesser-memory | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num == 0:
return True
if num % 10 == 0:
return False
return True | a-number-after-a-double-reversal | python 3 simple solution | O(1) | 88% lesser memory | Coding_Tan3 | 1 | 49 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,269 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2846742/Python-solution-one-line-faster-than-94. | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return str(int(str(num)[::-1]))[::-1] == str(num) | a-number-after-a-double-reversal | Python solution one line faster than 94%. | samanehghafouri | 0 | 2 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,270 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2820688/Python-Simple-Python-Solution-Using-Math-and-Reverse-Function | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
reversed1 = int(str(num)[::-1])
reversed2 = int(str(reversed1)[::-1])
if reversed2 == num:
return True
else:
return False | a-number-after-a-double-reversal | [ Python ] ✅✅ Simple Python Solution Using Math and Reverse Function🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,271 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2819013/2-Fast-and-Simple-Python-Solutions-One-Liners | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
not (num != 0 and str(num)[len(str(num)) - 1] == '0') | a-number-after-a-double-reversal | 2 Fast and Simple Python Solutions - One-Liners | PranavBhatt | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,272 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2819013/2-Fast-and-Simple-Python-Solutions-One-Liners | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return not (num != 0 and num % 10 == 0) | a-number-after-a-double-reversal | 2 Fast and Simple Python Solutions - One-Liners | PranavBhatt | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,273 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2788810/Python-divmod-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
def rev(num):
carry = 0
ans = 0
while num:
num, carry = divmod(num, 10)
ans = ans * 10 + carry
return ans
rev1 = rev(num)
rev2 = rev(rev1)
return rev2 == num | a-number-after-a-double-reversal | Python divmod solution | kruzhilkin | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,274 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2782984/O(1)-Solution-in-C%2B%2B-JAVA-C-PYTHON-PYTHON3-C-JAVASCRIPT | class Solution(object):
def isSameAfterReversals(self, num):
"""
:type num: int
:rtype: bool
"""
if num==0:
return True
if num%10==0:
return False
return True | a-number-after-a-double-reversal | O(1) Solution in C++, JAVA, C#, PYTHON, PYTHON3, C, JAVASCRIPT | umeshsakinala | 0 | 2 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,275 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2782984/O(1)-Solution-in-C%2B%2B-JAVA-C-PYTHON-PYTHON3-C-JAVASCRIPT | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num==0:
return True
if num%10==0:
return False
return True | a-number-after-a-double-reversal | O(1) Solution in C++, JAVA, C#, PYTHON, PYTHON3, C, JAVASCRIPT | umeshsakinala | 0 | 2 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,276 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2774283/Python3-Beats-99.9 | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
def reverse(x):
temp = x
rev = 0
ans = 0
temp1=0
while temp>0:
rev*=10
last_digit= temp%10
temp = temp//10
rev += last_digit
return rev
return reverse(reverse(num))== num | a-number-after-a-double-reversal | Python3- Beats 99.9% | user9190i | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,277 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2773271/Python-(Faster-than-98)-easy-mathematical-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
rev = 0
temp = num
while num:
r = num % 10
num //= 10
rev = (rev * 10) + r
return len(str(temp)) == len(str(rev)) | a-number-after-a-double-reversal | Python (Faster than 98%) easy mathematical solution | KevinJM17 | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,278 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2754004/Python3-1-liner | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return 0 if num != 0 and num % 10 == 0 else 1 | a-number-after-a-double-reversal | Python3 1 liner | sanil_7777 | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,279 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2739925/Python-3-Solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num == 0: return True
if str(num)[-1] == "0": return False
return True | a-number-after-a-double-reversal | Python 3 Solution | mati44 | 0 | 3 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,280 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2677151/easy-python-code | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if len(str(num)) == 1 and num == 0:
return True
a = str(num)
if a[-1] == '0':
return False
else:
return True | a-number-after-a-double-reversal | easy python code | ding4dong | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,281 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2655894/Python-one-liner-with-explanation | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return [False if len(str(num)) > 1 and str(num)[-1] == "0" else True][0] | a-number-after-a-double-reversal | Python one liner with explanation | code_snow | 0 | 42 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,282 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2645241/Python-one-liner-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return num==int(str(int(str(num)[::-1]))[::-1]) | a-number-after-a-double-reversal | Python one liner solution | abhint1 | 0 | 1 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,283 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2568990/Python3-beats-98.52-of-solutions!-(28-ms-13.8-MB) | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num >= 10 and num % 10 == 0:
return False
return True | a-number-after-a-double-reversal | Python3, beats 98.52% of solutions! (28 ms, 13.8 MB) | johnonthepath | 0 | 6 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,284 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2479496/Python-1-Lines-79.87-using-string.strip | class Solution:
def isSameAfterReversals(self, x: int) -> bool:
return str(x) == str(x)[::-1].lstrip('0')[::-1] or x == 0 | a-number-after-a-double-reversal | Python 1 Lines 79.87% using string.strip | amit0693 | 0 | 21 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,285 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2479496/Python-1-Lines-79.87-using-string.strip | class Solution:
def isSameAfterReversals(self, x: int) -> bool:
StringNum = str(x) #Convert int to string
reverseNum = StringNum[::-1] #Reverse the string
removeZero = reverseNum.lstrip('0') #Remove all leading zero
DoubleReversel = removeZero[::-1] #Double reverse the string
return x == 0 or str(x) == DoubleReversel | a-number-after-a-double-reversal | Python 1 Lines 79.87% using string.strip | amit0693 | 0 | 21 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,286 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2367057/Super-simple-python-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return num==0 or num%10!=0 | a-number-after-a-double-reversal | Super simple python solution | sunakshi132 | 0 | 28 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,287 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2213478/Easiest-Python-solution-with-explanation.......-99-faster | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num-0==0: #if num=0 we need to return true so we simpy subtract 0 to check if num is 0.
return True #0-0=0 but if num>1, num-0!=0
else:
return num%10!=0 # here simply check the last digit of num and compare with 0. If its not 0 return True | a-number-after-a-double-reversal | Easiest Python solution with explanation....... 99% faster | guneet100 | 0 | 34 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,288 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2180351/Python-super-simple-one-liner-for-beginners | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return str(num) == str(int(str(num)[::-1]))[::-1] | a-number-after-a-double-reversal | Python super simple one liner for beginners | pro6igy | 0 | 18 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,289 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2175146/python3-speed-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num != 0 and str(num)[-1] == '0':
return False
return True | a-number-after-a-double-reversal | [python3] speed solution | Bezdarnost | 0 | 11 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,290 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2152068/Easy-PYTHON-solution-for-beginners | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
num = str(num)
if len(num) > 1 and num[-1] == '0':
return False
return True | a-number-after-a-double-reversal | Easy PYTHON solution for beginners | rohansardar | 0 | 17 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,291 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/2094715/PYTHON-or-One-line-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return False if str(num)[-1] == '0' and len(str(num)) > 1 else True | a-number-after-a-double-reversal | PYTHON | One line solution | shreeruparel | 0 | 26 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,292 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1940858/Python-dollarolution-(99-faster) | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return (num == 0 or (num > 0 and num%10 != 0)) | a-number-after-a-double-reversal | Python $olution (99% faster) | AakRay | 0 | 35 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,293 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1926106/Python3-simple-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
if num == 0:
return True
elif num % 10 == 0:
return False
else:
return True | a-number-after-a-double-reversal | Python3 simple solution | EklavyaJoshi | 0 | 21 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,294 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1919196/Python-or-Two-Methods-or-One-Liners | class Solution:
def isSameAfterReversals(self, num):
def reverseNum(num): return int(str(num)[::-1])
return reverseNum(reverseNum(num)) == num | a-number-after-a-double-reversal | Python | Two Methods | One-Liners | domthedeveloper | 0 | 42 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,295 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1919196/Python-or-Two-Methods-or-One-Liners | class Solution:
def isSameAfterReversals(self, num):
return int(str(int(str(num)[::-1]))[::-1]) == num | a-number-after-a-double-reversal | Python | Two Methods | One-Liners | domthedeveloper | 0 | 42 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,296 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1919196/Python-or-Two-Methods-or-One-Liners | class Solution:
def isSameAfterReversals(self, num):
return num % 10 or num == 0 | a-number-after-a-double-reversal | Python | Two Methods | One-Liners | domthedeveloper | 0 | 42 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,297 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1856743/Python-easy-solution-by-converting-to-string | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
num_str = str(num)
rev_1 = int(num_str[::-1])
num_str = str(rev_1)
rev_2 = int(num_str[::-1])
if rev_2 == num:
return True
return False | a-number-after-a-double-reversal | Python easy solution by converting to string | alishak1999 | 0 | 29 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,298 |
https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1853696/NumberA-Number-After-a-Double-Reversal%3A-easy-solution | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
first = self.reverseNum(num)
second = self.reverseNum(first)
return num == second
def reverseNum(self, num: int):
reversed_num = 0
while num != 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
return reversed_num | a-number-after-a-double-reversal | NumberA Number After a Double Reversal: easy solution | jenil_095 | 0 | 14 | a number after a double reversal | 2,119 | 0.758 | Easy | 29,299 |
Subsets and Splits