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/binary-tree-pruning/discuss/2539816/Short-and-fast-python-solution-30ms. | class Solution(object):
def pruneTree(self, root):
if not root:
return None
root.left=self.pruneTree(root.left)
root.right=self.pruneTree(root.right)
if root.val==0 and not root.left and not root.right:
return None
return root | binary-tree-pruning | Short and fast python solution 30ms. | babashankarsn | 0 | 6 | binary tree pruning | 814 | 0.726 | Medium | 13,200 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2539091/Python-Simple-Python-Solution-Using-DFS-or-Recursion | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root == None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.left == None and root.right == None and root.val == 0:
return None
else:
return root | binary-tree-pruning | [ Python ] ✅✅ Simple Python Solution Using DFS | Recursion 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 8 | binary tree pruning | 814 | 0.726 | Medium | 13,201 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2539019/Python-or-Post-Order-Traversal-or-O(n)-Time-or-O(1)-space | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def post(node):
if not node:
return None, False
node.left, left = post(node.left)
node.right, right = post(node.right)
isOne = node.val==1
if left or right or isOne:
return node, True
return None, False
return post(root)[0] | binary-tree-pruning | Python | Post Order Traversal | O(n) Time | O(1) space | coolakash10 | 0 | 2 | binary tree pruning | 814 | 0.726 | Medium | 13,202 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2538571/814.-Binary-Tree-Pruning | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not(root):
return
root.left=self.pruneTree(root.left) None none none
root.right=self.pruneTree(root.right) none 1 1 1 1
if not(root.left) and not(root.right) and not (root.val):
return None
else:
return root | binary-tree-pruning | 814. Binary Tree Pruning | 12gaurav | 0 | 8 | binary tree pruning | 814 | 0.726 | Medium | 13,203 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2538528/Binary-Tree-Pruning-Python-or-Java | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
if self.pruneTree(root.left) is None:
root.left = None
if self.pruneTree(root.right) is None:
root.right = None
if root.val != 1 and root.left is None and root.right is None:
root = None
return root | binary-tree-pruning | Binary Tree Pruning [ Python | Java ] | klu_2100031497 | 0 | 6 | binary tree pruning | 814 | 0.726 | Medium | 13,204 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2538323/BinaryTree-or-Python3-or-Buttom-up-or-Easy-to-understand | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# buttom up approach
if root:
leftsub = self.pruneTree(root.left)
rightsub = self.pruneTree(root.right)
if leftsub or rightsub or root.val:
root.left = leftsub
root.right = rightsub
return root | binary-tree-pruning | BinaryTree | Python3 | Buttom up | Easy to understand | NitishKumarVerma | 0 | 1 | binary tree pruning | 814 | 0.726 | Medium | 13,205 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2537619/Python-oror-easy-code-with-comments-oror-O(N)-oror | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
'''
using recursion check on every node if it is 0
and have no child return None otherwise node itself,
that returned node will be assigned to calling place,
which is in return same address, on which it was stored
'''
if not root: return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.val == 0 and not root.right and not root.left:
return None
return root | binary-tree-pruning | Python || easy code with comments || O(N) || ✅ ✅ | umesh_malik | 0 | 10 | binary tree pruning | 814 | 0.726 | Medium | 13,206 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2537590/EASY-PYTHON3-SOLUTION | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
if self.pruneTree(root.left) is None:
root.left = None
if self.pruneTree(root.right) is None:
root.right = None
if root.val != 1 and root.left is None and root.right is None:
root = None
return root | binary-tree-pruning | 🔥 EASY PYTHON3 SOLUTION 🔥 | rajukommula | 0 | 2 | binary tree pruning | 814 | 0.726 | Medium | 13,207 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2537547/Simple-Python-Solution-oror-~99-faster-oror-DFS | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.left is None and root.right is None and root.val == 0:
return None
return root | binary-tree-pruning | Simple Python Solution || 🔥 ~99% faster || DFS | wilspi | 0 | 14 | binary tree pruning | 814 | 0.726 | Medium | 13,208 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2537250/Python-DFS | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not self.check_n_prune(root): return None
return root
def check_n_prune(self, root):
if not root: return False
if not self.check_n_prune(root.left):
root.left = None
if not self.check_n_prune(root.right):
root.right = None
if not root.val and not root.left and not root.right:
return False
return True | binary-tree-pruning | Python DFS | li87o | 0 | 11 | binary tree pruning | 814 | 0.726 | Medium | 13,209 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2459967/Python-or-C%2B%2B-%3A-DFS-with-recursion | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def prune(root):
if root:
root.left = prune(root.left)
root.right = prune(root.right)
if root.left is None and root.right is None:
if not root.val:
return None
return root
return root
return prune(root) | binary-tree-pruning | Python | C++ : DFS with recursion | joshua_mur | 0 | 20 | binary tree pruning | 814 | 0.726 | Medium | 13,210 |
https://leetcode.com/problems/binary-tree-pruning/discuss/2047628/Python-Solution-oror-Easy-to-understand | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def helper(node):
if node is None:
return 0
leftSum = helper(node.left)
rightSum = helper(node.right)
if leftSum == 0:
node.left = None
if rightSum == 0:
node.right = None
return leftSum+rightSum+node.val
helper(root)
if root.val == 0 and not root.left and not root.right:
root = None
return root
``` | binary-tree-pruning | Python Solution || Easy to understand | b160106 | 0 | 28 | binary tree pruning | 814 | 0.726 | Medium | 13,211 |
https://leetcode.com/problems/binary-tree-pruning/discuss/1815541/Python-or-DFS | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(node):
if not node:
return True,None#True means remove the node
l,node.left=dfs(node.left)
r,node.right=dfs(node.right)
if l and r and node.val==0:
return True,None
return False,node#False means keep the node
if dfs(root)[0]:
return None
return root | binary-tree-pruning | Python | DFS | heckt27 | 0 | 31 | binary tree pruning | 814 | 0.726 | Medium | 13,212 |
https://leetcode.com/problems/binary-tree-pruning/discuss/1799697/Python-faster-than-88-with-86-less-memory | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# BFS to check all nodes
'''
1. BFS through tree from node
2. if left subtree is all 0s, set node.left = None, same for right,
3. move to next node, repeat 1-3
4. return new subtree
'''
has_one_p = self.traversal_f(root)
if has_one_p != True:
root.left = None
root.right = None
#root.val = None
return None
self.prune_helper_f(root)
return root
def prune_helper_f(self, root):
queue = [root]
while queue:
node = queue.pop()
if node:
left_has_one = self.traversal_f(node.left)
right_has_one = self.traversal_f(node.right)
if left_has_one == True:
queue.append(node.left)
else:
node.left = None
if right_has_one == True:
queue.append(node.right)
else:
node.right = None
def traversal_f(self, node):
#elements = False
if node:
if node.val == 1:
return True
else:
return self.traversal_f(node.left) or self.traversal_f(node.right) | binary-tree-pruning | Python faster than 88% with 86% less memory | aemono | 0 | 46 | binary tree pruning | 814 | 0.726 | Medium | 13,213 |
https://leetcode.com/problems/binary-tree-pruning/discuss/1632525/Easy-to-understand-python-solution.-Beats-95-solutions | class Solution:
def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return root
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if not root.left and not root.right and root.val != 1:
return None
return root | binary-tree-pruning | Easy to understand python solution. Beats 95% solutions | mandavawala | 0 | 33 | binary tree pruning | 814 | 0.726 | Medium | 13,214 |
https://leetcode.com/problems/binary-tree-pruning/discuss/1358116/Python-faster-than-99-16-ms | class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
if root is None:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if root.val == 0 and root.left is None and root.right is None:
return None
return root | binary-tree-pruning | Python - faster than 99%, 16 ms | SG5 | 0 | 44 | binary tree pruning | 814 | 0.726 | Medium | 13,215 |
https://leetcode.com/problems/binary-tree-pruning/discuss/1357342/PythonJavascript-or-85-speed-or-Recursion | class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
if root is None:
return False
self.containsOne(root)
if root.val == 0 and not root.right and not root.left:
return None
return root
def containsOne(self, root) -> bool:
if not root:
return False
containsLeft = self.containsOne(root.left)
containsRight = self.containsOne(root.right)
if not containsLeft:
root.left = None
if not containsRight:
root.right = None
return root.val == 1 or containsLeft or containsRight | binary-tree-pruning | Python/Javascript | 85% speed | Recursion | Chris_R | 0 | 28 | binary tree pruning | 814 | 0.726 | Medium | 13,216 |
https://leetcode.com/problems/binary-tree-pruning/discuss/1077412/Python-3-Simple-Recursive-Approach-w-comments | class Solution:
def pruneTree(self, root: TreeNode) -> TreeNode:
# Base case - return None if node does not exist
if root is None:
return None
else:
# recursively traverse the left and right subtrees
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
# Condition to check if subtree doesn't have 1 as node value i.e root.val == 0
if root.left is None and root.right is None and root.val == 0:
return None
else:
return root | binary-tree-pruning | [Python 3] - Simple Recursive Approach w/ comments | sarthak6246 | 0 | 35 | binary tree pruning | 814 | 0.726 | Medium | 13,217 |
https://leetcode.com/problems/bus-routes/discuss/2275016/Python3-BFS-Approach | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
m = defaultdict(set)
for i, route in enumerate(routes):
for node in route:
m[node].add(i)
ans = -1
vis = set()
queue = deque()
queue.append(source)
while queue:
l = len(queue)
ans += 1
for _ in range(l):
cur = queue.popleft()
if cur == target:
return ans
for bus in m[cur]:
if bus not in vis:
vis.add(bus)
queue.extend(routes[bus])
return -1 | bus-routes | [Python3] BFS Approach | van_fantasy | 1 | 127 | bus routes | 815 | 0.457 | Hard | 13,218 |
https://leetcode.com/problems/bus-routes/discuss/1752569/Python-or-BFS | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source==target:
return 0
busstop=defaultdict(list)#List of Buses departing from every bus stops
for busnum,stops in enumerate(routes):
for stop in stops:
busstop[stop].append(busnum)#'busnum' is departing from the bustop 'stop'
q=[]
visit=set()
for bus in busstop[source]:#Grab all the buses departing from the source busstop
q.append((bus,1))
visit.add(bus)
while q:
busnum,numofbus=q.pop(0)
if target in routes[busnum]:#If my target is in current bus route return the numofbus I have taken
return numofbus
for stops in routes[busnum]:#Get me all the stops for my current bus
for buses in busstop[stops]:#Get me all the buses which departs from the stop of my current bus
if buses not in visit:#If I have not taken the bus add it to my queue
visit.add(buses)
q.append((buses,numofbus+1))
return -1 | bus-routes | Python | BFS | heckt27 | 1 | 87 | bus routes | 815 | 0.457 | Hard | 13,219 |
https://leetcode.com/problems/bus-routes/discuss/1309920/Python3-bfs | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
mp = {}
for i, route in enumerate(routes):
for x in route:
mp.setdefault(x, []).append(i)
ans = 0
seen = {source}
queue = [source]
while queue:
newq = []
for x in queue:
if x == target: return ans
for i in mp[x]:
for xx in routes[i]:
if xx not in seen:
seen.add(xx)
newq.append(xx)
routes[i] = []
ans += 1
queue = newq
return -1 | bus-routes | [Python3] bfs | ye15 | 1 | 89 | bus routes | 815 | 0.457 | Hard | 13,220 |
https://leetcode.com/problems/bus-routes/discuss/2717782/Clear-Python3-solution-without-collections-library | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
# Step 0: Special case of an empty route
if source == target: return 0
# Step 1: Create a dict of [stop -> busses stopping at this stop]
stop2bus = dict()
for i in range(len(routes)):
for stop in routes[i]:
if stop not in stop2bus: stop2bus[stop] = set()
stop2bus[stop].add(i)
# Step 2: BFS over the bus stops
bfs_queue = [(source,0)] # Tuple of (bus stop, number of busses taken to get to the stop)
visited = {source} # Set of visited bus stops to avoid cycles
while len(bfs_queue) > 0: # BFS
stop, numBusses = bfs_queue.pop(0)
if stop==target: return numBusses # If we arrived at the target, stop here!
if stop in stop2bus:
for bus in stop2bus[stop]: # Check all busses at this stop
for neighbour in routes[bus]: # Check all stops of each bus
if neighbour not in visited:
# Add all new stops to the neighbours
bfs_queue.append((neighbour,numBusses+1))
visited.add(neighbour)
routes[bus]=[]
return -1 # If we finished the BFS and did not reach the target, it is unreachable | bus-routes | Clear Python3 solution without collections library | lucieperrotta | 0 | 2 | bus routes | 815 | 0.457 | Hard | 13,221 |
https://leetcode.com/problems/bus-routes/discuss/2594474/Python-3-Simple-Solution | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
queue = deque([(source, 0)])
graph = defaultdict(set)
visited = set()
for routeIdx, route in enumerate(routes):
for busStop in route:
graph[busStop].add(routeIdx)
while queue:
curStop, curDist = queue.popleft()
if curStop == target:
return curDist
visited.add(curStop)
for routeIdx in graph[curStop]:
for stop in routes[routeIdx]:
if stop not in visited:
queue.append((stop, curDist + 1))
routes[routeIdx] = set()
return -1 | bus-routes | Python 3 Simple Solution | lwlypalace | 0 | 55 | bus routes | 815 | 0.457 | Hard | 13,222 |
https://leetcode.com/problems/bus-routes/discuss/2495803/Clean-Fast-Python3-or-BFS | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
stop_to_bus = defaultdict(list)
source_buses, target_buses = [], set()
for bus, route in enumerate(routes):
for stop in route:
if stop == source:
source_buses.append((bus, 1))
if stop == target:
target_buses.add(bus)
stop_to_bus[stop].append(bus)
if len(target_buses) == 0:
return -1
if any(sb in target_buses for sb, _ in source_buses):
return 1
# BFS
q, seen = deque(source_buses), set(source_buses)
while q:
cur_bus, buses = q.pop()
for stop in routes[cur_bus]:
for nxt_bus in stop_to_bus[stop]:
if nxt_bus in target_buses:
return buses + 1
if nxt_bus not in seen:
seen.add(nxt_bus)
q.appendleft((nxt_bus, buses + 1))
return -1 | bus-routes | Clean, Fast Python3 | BFS | ryangrayson | 0 | 16 | bus routes | 815 | 0.457 | Hard | 13,223 |
https://leetcode.com/problems/bus-routes/discuss/1413191/BFS-with-sets-89-speed | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
if source == target:
return 0
set_routes = [set(route) for route in routes]
start_buses = [i for i, s in enumerate(set_routes) if source in s]
state = set()
for i in start_buses[::-1]:
state.update(set_routes.pop(i))
if target in state:
return 1
n_buses = 1
while state:
new_state = set()
n_buses += 1
new_busses = [i for i, s in enumerate(set_routes) if state & s]
for i in new_busses[::-1]:
new_state.update(set_routes.pop(i))
if target in new_state:
return n_buses
state = new_state
return -1 | bus-routes | BFS with sets, 89% speed | EvgenySH | 0 | 196 | bus routes | 815 | 0.457 | Hard | 13,224 |
https://leetcode.com/problems/ambiguous-coordinates/discuss/934654/Python3-valid-numbers | class Solution:
def ambiguousCoordinates(self, s: str) -> List[str]:
s = s.strip("(").strip(")")
def fn(s):
"""Return valid numbers from s."""
if len(s) == 1: return [s]
if s.startswith("0") and s.endswith("0"): return []
if s.startswith("0"): return [s[:1] + "." + s[1:]]
if s.endswith("0"): return [s]
return [s[:i] + "." + s[i:] for i in range(1, len(s))] + [s]
ans = []
for i in range(1, len(s)):
for x in fn(s[:i]):
for y in fn(s[i:]):
ans.append(f"({x}, {y})")
return ans | ambiguous-coordinates | [Python3] valid numbers | ye15 | 7 | 302 | ambiguous coordinates | 816 | 0.561 | Medium | 13,225 |
https://leetcode.com/problems/ambiguous-coordinates/discuss/2786263/Python-or-Clear-explained-or-Clean | class Solution:
def ambiguousCoordinates(self, s: str) -> List[str]:
def possibleSplit(inputStr):
# integer (no leading zeros or '0' itself)
output = [inputStr] if inputStr[0] != '0' or inputStr == '0' else []
# float
for i in range(1, len(inputStr)):
digit, decimal = inputStr[:i], inputStr[i:]
# checking digit (left extra zeros)
if len(digit) >= 2 and digit[0] == '0':
break
# checking decimal (right extra zeros)
if decimal[-1] == '0':
break
output.append(f'{digit}.{decimal}')
return output
numStr = s[1:-1]
output = []
for i in range(1, len(numStr)):
for x in possibleSplit(numStr[:i]):
for y in possibleSplit(numStr[i:]):
output.append(f'({x}, {y})')
return output | ambiguous-coordinates | Python | Clear explained | Clean | yzhao156 | 0 | 7 | ambiguous coordinates | 816 | 0.561 | Medium | 13,226 |
https://leetcode.com/problems/ambiguous-coordinates/discuss/2470876/Python3-or-Solved-Using-General-Intuition-and-Handling-Edge-Cases-With-%220%22 | class Solution:
#Time-Complexity: O(n^3), since outer for loop runs n times, and in worst case,
#the first_value and second_value array of coordinates used to pairing up is in worst case
#at most size n if the substring we passed to helper is around n characters!
#Space-Complexity: O(2*n * n) -> O(n^2)
def ambiguousCoordinates(self, s: str) -> List[str]:
#First, we need to decide how to split s into two numbers! This will decide where to put
#comma!
#Then, we need to see if we are able to put decimal point in only one of the two splitted
#numbers!
#we also need to exclude the parentheses characteres!
s = s[1:len(s)-1]
#we need to define some helper to determine all possible valid coordinate values
#we can form using substring x as input!
def helper(x):
#if x is single character, then itself is a valid coordinate value and only one!
if(len(x) == 1):
return [x]
#if x has both first and last character be a 0, it can't ever result in a
#valid coordinate value!
if(x[0] == "0" and x[len(x)-1] == "0"):
return []
#if only first character is 0, only valid coordinate value it can form is
#in form 0.xxxxxx...!
if(x[0] == "0"):
return ["0." + x[1:]]
#if last digit is a 0, it can always be simplified no matter where I place
#decimal point, thus only possible coordinate value candidate is x itself!
if(x[-1] == '0'):
return [x]
#otherwise, we can simply generate all possible coordinate values by placing
#decimal point between every two digits!
else:
#string x as itself is one of many ways!
local = [x]
#we will iterate from first char to 2nd to last char!
cur = ""
for i in range(0, len(x) - 1):
cur += x[i]
second_portion = x[i+1:]
overall = cur + "." + second_portion
local.append(overall)
return local
ans = []
n = len(s)
#For each iteration, we consider a possible split!
for i in range(1, n):
#consider splitting the string input s into left and right portions!
#Left portion will determine all possible first coordinate values!
#Right portion will determine all possible second coordinate values!
l = s[:i]
r = s[i:]
#Once we find all possible first and second coordinate values, we simply
#need to find all pairings!
left_vals = helper(l)
right_vals = helper(r)
#before running for loop, we need to make sure that left_vals and right_vals is both
#not an empty array. If even one of them is empty, it is not possible to form
#a single valid 2-d coordinate pairing!
if(not left_vals and not right_vals):
continue
for l in left_vals:
for r in right_vals:
new_pairing = "(" + l + ", " + r + ")"
ans.append(new_pairing)
return ans | ambiguous-coordinates | Python3 | Solved Using General Intuition and Handling Edge Cases With "0" | JOON1234 | 0 | 12 | ambiguous coordinates | 816 | 0.561 | Medium | 13,227 |
https://leetcode.com/problems/ambiguous-coordinates/discuss/1480758/Using-itertools-product-81-speed | class Solution:
def generate_nums(self, s: str) -> List[str]:
if len(s) == 1:
return [s]
ans = [] if s.startswith("0") else [s]
if s.endswith("0"):
return ans
for i in range(1, len(s)):
a, b = s[:i], s[i:]
if a.startswith("0") and len(a) > 1:
break
ans.append(f"{a}.{b}")
return ans
def ambiguousCoordinates(self, s: str) -> List[str]:
s = s[1:-1]
ans = []
for i in range(1, len(s)):
a, b = s[:i], s[i:]
for x, y in product(self.generate_nums(a), self.generate_nums(b)):
ans.append(f"({x}, {y})")
return ans | ambiguous-coordinates | Using itertools product, 81% speed | EvgenySH | 0 | 51 | ambiguous coordinates | 816 | 0.561 | Medium | 13,228 |
https://leetcode.com/problems/ambiguous-coordinates/discuss/1207183/python-elongated-every-case-checking-and-generating-string-on-basis-of-every-case | class Solution:
def ambiguousCoordinates(self, s: str) -> List[str]:
#three choices add a ./_/nothing
# we cannot add after a gap after last element is zero after a decimal
#check decimal occured
#if we are adding a gap we can make the decimal occured false
#cannot add another 0 if decimal is not occured and last element is 0
#cannot add more than one gap
#check gap added
#decimal occured
#gap occured
#if decimal occured we cannot add another decimal
q=deque()
q.append((s[1],False,False,0))
a=set()
s = s[1:-1]
while q:
st,gapocc,decimalocc,li = q.popleft()
st2=st
st = st.split(' ')[-1]
if li==len(s)-1:
ss = st2.split(' ')
if len(ss)==2:
a.add('('+ss[0]+', '+ss[1]+')')
continue
ch = s[li+1]
lch = st[-1]
if li==len(s)-2:
if decimalocc==False and gapocc:
if ch!='0':
q.append((st2+'.'+ch,gapocc,True,li+1))
if float(st)!=0:
q.append((st2+ch,gapocc,decimalocc,li+1))
continue
if decimalocc and gapocc:
if ch=='0':
continue
else:
q.append((st2+ch,gapocc,decimalocc,li+1))
continue
if gapocc==False and decimalocc:
#if gap not made len of st>1
if lch!='0':
q.append((st2+' '+ch,True,decimalocc,li+1))
continue
if not decimalocc and not gapocc:
q.append((st2+' '+ch,True,decimalocc,li+1))
continue
if decimalocc==False and gapocc:
q.append((st2+'.'+ch,gapocc,True,li+1))
if float(st)!=0:
q.append((st2+ch,gapocc,decimalocc,li+1))
if decimalocc and gapocc==False:
if lch!='0':
q.append((st2+' '+ch,True,False,li+1))
q.append((st2+ch,gapocc,decimalocc,li+1))
if decimalocc and gapocc:
q.append((st2+ch,gapocc,decimalocc,li+1))
if not decimalocc and not gapocc:
if float(st)!=0:
q.append((st2+ch,gapocc,decimalocc,li+1))
q.append((st2+' '+ch,True,False,li+1))
q.append((st2+'.'+ch,gapocc,True,li+1))
return a
pass | ambiguous-coordinates | python elongated every case checking and generating string on basis of every case | user4436H | 0 | 38 | ambiguous coordinates | 816 | 0.561 | Medium | 13,229 |
https://leetcode.com/problems/ambiguous-coordinates/discuss/1206720/python3-Solution-for-reference-based-on-string-arrangement. | class Solution:
def ambiguousCoordinates(self, s: str) -> List[str]:
s = s[1:-1]
sp = [(s[:x], s[x:]) for x in range(1,len(s))]
o = []
for left, right in sp:
la = []
if left[0] == '0' and len(left) > 1 and set(left) != set(["0"]):
if left[1:][-1] != '0':
la.append((left[:1] + '.' + left[1:]))
else:
if (len(left) > 1 and set(left) != set(["0"])) or len(left) == 1:
la.append(left)
for y in range(1, len(left)):
if int(left[y:]) != 0 and left[y:][-1] != '0':
la.append((left[:y] + '.' + left[y:]))
ra = []
if right[0] == '0' and len(right) > 1 and set(right) != set(["0"]):
if right[1:][-1] != '0':
o += ["(%s, %s)"%(i, (right[:1] + '.' + right[1:])) for i in la]
else:
if (len(right) > 1 and set(right) != set(["0"])) or len(right) == 1:
o += ["(%s, %s)"%(i, right) for i in la]
for y in range(1, len(right)):
if int(right[y:]) != 0 and right[y:][-1] != '0':
rightside = right[:y] + '.' + right[y:]
o += ["(%s, %s)"%(i, rightside) for i in la]
return o | ambiguous-coordinates | [python3] Solution for reference based on string arrangement. | vadhri_venkat | 0 | 71 | ambiguous coordinates | 816 | 0.561 | Medium | 13,230 |
https://leetcode.com/problems/linked-list-components/discuss/933679/Python3-counting-end-of-component | class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
Gs = set(G)
ans = 0
while head:
if head.val in Gs and (head.next is None or head.next.val not in Gs): ans += 1
head = head.next
return ans | linked-list-components | [Python3] counting end of component | ye15 | 3 | 180 | linked list components | 817 | 0.581 | Medium | 13,231 |
https://leetcode.com/problems/linked-list-components/discuss/1946978/Intuitive-and-Consice-Python-Solution-O(N)-Time-O(1)-Space | class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
nums = set(nums)
cur = head
res = 0
connected = False
while cur:
if cur.val in nums:
if not connected:
res += 1
connected = True
else:
connected = False
cur = cur.next
return(res) | linked-list-components | Intuitive and Consice Python Solution O(N) Time O(1) Space | lukefall425 | 2 | 121 | linked list components | 817 | 0.581 | Medium | 13,232 |
https://leetcode.com/problems/linked-list-components/discuss/468700/Python-3-(three-lines)-(108-ms) | class Solution:
def numComponents(self, H: ListNode, G: List[int]) -> int:
S, c = set(G), 0
while H != None: c, H = c + (H.val in S and (H.next == None or H.next.val not in S)), H.next
return c
- Junaid Mansuri
- Chicago, IL | linked-list-components | Python 3 (three lines) (108 ms) | junaidmansuri | 2 | 381 | linked list components | 817 | 0.581 | Medium | 13,233 |
https://leetcode.com/problems/linked-list-components/discuss/1578443/Python3-Solution-with-using-hashset | class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
s = set(G)
res = 0
while head:
if head.val in s and (head.next == None or head.next.val not in s):
res += 1
head = head.next
return res | linked-list-components | [Python3] Solution with using hashset | maosipov11 | 1 | 60 | linked list components | 817 | 0.581 | Medium | 13,234 |
https://leetcode.com/problems/linked-list-components/discuss/661254/Python-3-two-pointer | class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
count = 0
p1, p2 = head, head
while p2:
if p1.val in G:
p2 = p1.next
p1 = p2
if not p2 or p2.val not in G:
count+=1
else:
p1 = p2.next
p2 = p1
return count | linked-list-components | Python 3 two-pointer | zzj8222090 | 1 | 84 | linked list components | 817 | 0.581 | Medium | 13,235 |
https://leetcode.com/problems/linked-list-components/discuss/2237732/Python-or-Hashing-or-Dictionary | class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
d,count={},0
for num in nums:
d[num] = 0
while head:
if head.val in d:
head = head.next
while head and head.val in d:
head = head.next
count += 1
else:
head = head.next
return count | linked-list-components | Python | Hashing | Dictionary | volleyfreak | 0 | 52 | linked list components | 817 | 0.581 | Medium | 13,236 |
https://leetcode.com/problems/linked-list-components/discuss/1837929/python-3-oror-HashSet-oror-O(n) | class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
nums = set(nums)
res = 0
prevInNums = False
while head:
if head.val in nums:
if not prevInNums:
prevInNums = True
res += 1
else:
prevInNums = False
head = head.next
return res | linked-list-components | python 3 || HashSet || O(n) | dereky4 | 0 | 77 | linked list components | 817 | 0.581 | Medium | 13,237 |
https://leetcode.com/problems/linked-list-components/discuss/1389193/Python3-Simple-1-Pass-O(N)-Time-and-Space | class Solution:
def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:
nums = set(nums)
a = connected = 0
while head:
if head.val in nums:
if not connected:
a = a + 1
connected = 1
else:
connected = 0
head = head.next
return a | linked-list-components | [Python3] Simple 1 Pass, O(N) Time & Space | whitehatbuds | 0 | 78 | linked list components | 817 | 0.581 | Medium | 13,238 |
https://leetcode.com/problems/linked-list-components/discuss/407564/Python-Simple-Solution | class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
temp = head
a = []
while(temp):
a.append(temp.val)
temp = temp.next
t = []
m = []
for i in range(len(a)):
if a[i] not in G:
if not t:
pass
else:
m.append(t)
t = []
else:
t.append(a[i])
if t:
m.append(t)
return len(m) | linked-list-components | Python Simple Solution | saffi | 0 | 231 | linked list components | 817 | 0.581 | Medium | 13,239 |
https://leetcode.com/problems/race-car/discuss/1512080/Greedy-Approach-oror-Normal-conditions-oror-94-faster-oror-Well-Coded | class Solution:
def racecar(self, target: int) -> int:
q = deque()
q.append((0,0,1))
while q:
m,p,s = q.popleft()
if p==target:
return m
rev = -1 if s>0 else 1
q.append((m+1,p+s,s*2))
if (p+s<target and s<0) or (p+s>target and s>0): # If you are back to the target and speed is reverse or if you are ahead of target and speed is positive then reverse the speed
q.append((m+1,p,rev))
return -1 | race-car | 📌📌 Greedy Approach || Normal conditions || 94% faster || Well-Coded 🐍 | abhi9Rai | 9 | 764 | race car | 818 | 0.435 | Hard | 13,240 |
https://leetcode.com/problems/race-car/discuss/2349577/Python-easy-to-read-and-understand-or-BFS | class Solution:
def racecar(self, target: int) -> int:
q = [(0, 1)]
steps = 0
while q:
num = len(q)
for i in range(num):
pos, speed = q.pop(0)
if pos == target:
return steps
q.append((pos+speed, speed*2))
rev_speed = -1 if speed > 0 else 1
if (pos+speed) < target and speed < 0 or (pos+speed) > target and speed > 0:
q.append((pos, rev_speed))
steps += 1 | race-car | Python easy to read and understand | BFS | sanial2001 | 2 | 323 | race car | 818 | 0.435 | Hard | 13,241 |
https://leetcode.com/problems/race-car/discuss/2721389/Python3-or-BFS | class Solution:
def racecar(self, target: int) -> int:
dq=deque([(0,0,1)])
while dq:
move,pos,speed=dq.popleft()
if pos==target:
return move
dq.append((move+1,pos+speed,speed*2))
if (pos+speed>target and speed>0) or pos+speed<target and speed<0:
speed=-1 if speed>0 else 1
dq.append((move+1,pos,speed))
else:
continue | race-car | [Python3] | BFS | swapnilsingh421 | 0 | 24 | race car | 818 | 0.435 | Hard | 13,242 |
https://leetcode.com/problems/most-common-word/discuss/2830994/Python-oror-Long-but-FAST-oror-Memory-beats-82.67! | class Solution:
def getSplit(self, s):
result = []
strS = ''
for i in s.lower():
if i not in "!?',;. ": strS += i
else:
if len(strS) > 0: result.append(strS)
strS = ''
if len(strS) > 0: result.append(strS)
return result
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph = self.getSplit(paragraph)
freq = {}
for s in paragraph:
if s not in banned:
if s in freq: freq[s] += 1
else: freq[s] = 1
m = max(freq.values())
for k in freq:
if freq[k] == m: return k | most-common-word | Python || Long but FAST || Memory beats 82.67%! | qiy2019 | 1 | 27 | most common word | 819 | 0.449 | Easy | 13,243 |
https://leetcode.com/problems/most-common-word/discuss/1916788/Python3-oror-very-easy-yet-very-fast | class Solution:
def mostCommonWord(self, para: str, banned: List[str]) -> str:
p = []
s = ''
banned = set(banned)
rem = {"!","?","'",",",";","."," "}
freq = {}
for c in para:
if c in rem:
if s: p.append(s)
s = ''
continue
if c.isupper(): s += c.lower()
else: s += c
if s: p.append(s)
maxfreq, maxword = 0, ''
for w in p:
if w in banned: continue
if w not in freq: freq[w] = 0
freq[w] += 1
if freq[w] > maxfreq:
maxfreq = freq[w]
maxword = w
return maxword | most-common-word | Python3 || very easy yet very fast | Dewang_Patil | 1 | 200 | most common word | 819 | 0.449 | Easy | 13,244 |
https://leetcode.com/problems/most-common-word/discuss/2846399/BEATS-91-EASY-APPROACH-USING-HASHMAP | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
string=""
for i in paragraph:
if i==" " or i=="," or i==".":
string+=" "
elif i.isalpha():
string+=i.lower()
res=""
string=string.split(" ")
dic=Counter(string)
for i in banned:
if i in dic:
del dic[i]
if "" in dic:
del dic[""]
m=max(dic.values())
for i,j in dic.items():
if j==m and i.isalpha():
res+=i
return res | most-common-word | BEATS 91% , EASY APPROACH USING HASHMAP | 2003480100009_A | 0 | 1 | most common word | 819 | 0.449 | Easy | 13,245 |
https://leetcode.com/problems/most-common-word/discuss/2803466/Most-Common-Word-or-PYTHON | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
l = re.findall(r'\w+', paragraph.lower())
d={}
for i in l:
if i not in d:
d[i]=1
else:
d[i]+=1
d = Counter(d)
d=list(d.most_common())
for i in d:
if i[0] not in banned:
return i[0] | most-common-word | Most Common Word | PYTHON | saptarishimondal | 0 | 5 | most common word | 819 | 0.449 | Easy | 13,246 |
https://leetcode.com/problems/most-common-word/discuss/2739287/Python-Easy | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
from collections import Counter
lst = paragraph.split(" ")
lst_2 = []
for word in lst:
tmp = ""
for letter in word:
if (letter.islower() or letter.isupper()):
tmp += letter.lower()
else:
if (tmp != "" and tmp not in banned):
lst_2.append(tmp)
tmp = ""
if (tmp != "" and tmp not in banned):
lst_2.append(tmp)
count = Counter(lst_2)
ans = ""
max_ = 0
for key in count:
if (count[key] > max_):
ans = key
max_ = count[key]
return ans | most-common-word | Python Easy | lucasschnee | 0 | 11 | most common word | 819 | 0.449 | Easy | 13,247 |
https://leetcode.com/problems/most-common-word/discuss/2530071/Python-fast-solution-with-writing-a-split-function | class Solution:
def mostCommonWord(self, paragraph: str, banned: list[str]) -> str:
def split(string):
string = string.lower()
for i in string:
if i in "!?',;.":
string = string.replace(i, ' ')
return string.split()
paragraph, d = split(paragraph), {}
for i in paragraph:
if i not in banned:
d[i] = d.get(i, 0) + 1
return max(d, key=d.get) | most-common-word | Python fast solution with writing a split function | Mark_computer | 0 | 82 | most common word | 819 | 0.449 | Easy | 13,248 |
https://leetcode.com/problems/most-common-word/discuss/2474888/Python3-Simple-using-dict-w-explanation-(9699) | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# Convert the paragraph to all lowercase
paragraph = paragraph.lower()
# Remove punctuation
remove = list("!?';,.")
for r in remove: paragraph = paragraph.replace(r, ' ')
# Ensure only one space between words and split string into a list by space
paragraph = paragraph.replace(' ', ' ').replace(' ', ' ')
paragraph = paragraph.strip().split(" ")
# Use a dict to count all instances of words (if they aren't banned)
counts = {}
for word in paragraph:
if word not in banned: counts[word] = counts.get(word, 0) + 1
# Return the key of the highest value in the dictionary
return max(counts, key=counts.get) | most-common-word | [Python3] Simple using dict - w explanation (96%/99%) | connorthecrowe | 0 | 82 | most common word | 819 | 0.449 | Easy | 13,249 |
https://leetcode.com/problems/most-common-word/discuss/2460868/Dictionary-O(N)-one-pass-(Pseudo-Code-and-Comments-)%3A | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
freq={}
# INVALID STRINGS
spe_char,sp=("!?',;."),' '
max_freq,i=0,0
while len(paragraph) > i:
# CREATING VALID WORD
word=""
while 'a'<= paragraph[i].lower() <= 'z' and i < len(paragraph):
word+=paragraph[i].lower()
i+=1
if i==len(paragraph):
break
# SKIP INVALID CHARaCTERS
i+=1
# STORE VALID WORD IN DICTIONARY WITH FREQUENCIES
if word != sp and word not in banned and word not in spe_char:
if word not in freq:
freq[word]=1
else:
freq[word]+=1
# KEEP TRACK OF MOST COMMON WORD
if freq[word] > max_freq:
max_freq=freq[word]
MCW=word
return MCW | most-common-word | Dictionary O(N)-one pass (Pseudo Code and Comments ): | shreyasg13 | 0 | 35 | most common word | 819 | 0.449 | Easy | 13,250 |
https://leetcode.com/problems/most-common-word/discuss/2263684/Python-Liner-with-explanation | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
return Counter([word for word in "".join([ch.lower() for ch in paragraph.replace(",", " ")if ch.isalpha() or ch == " "]).split() if word not in banned]).most_common()[0][0] | most-common-word | Python १-Liner with explanation | amaargiru | 0 | 68 | most common word | 819 | 0.449 | Easy | 13,251 |
https://leetcode.com/problems/most-common-word/discuss/2263684/Python-Liner-with-explanation | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph = paragraph.replace(",", " ")
extracted_words = "".join([ch.lower() for ch in paragraph if ch.isalpha() or ch == " "]).split()
not_banned_words = [word for word in extracted_words if word not in banned]
counted_words = Counter(not_banned_words)
most_common_word = counted_words.most_common()[0][0]
return most_common_word | most-common-word | Python १-Liner with explanation | amaargiru | 0 | 68 | most common word | 819 | 0.449 | Easy | 13,252 |
https://leetcode.com/problems/most-common-word/discuss/2013903/Python-interesting-solution | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
ans = {}
for i in set(re.split(r'[^a-z]', paragraph.lower())) - set(banned):
if i:
ans[i] = re.split(r'[^a-z]', paragraph.lower()).count(i)
return max(ans,key=ans.get) | most-common-word | Python interesting solution | StikS32 | 0 | 86 | most common word | 819 | 0.449 | Easy | 13,253 |
https://leetcode.com/problems/most-common-word/discuss/1949711/Simple-python3-solution | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph=re.sub(r'[,.!?;\']',' ',paragraph)
paragraph=paragraph.lower()
a=paragraph.split()
count=0
word=""
for i in list(set(a)):
if a.count(i)>count and i not in banned:
count=a.count(i)
word=i
return word | most-common-word | Simple python3 solution | mopasha1 | 0 | 107 | most common word | 819 | 0.449 | Easy | 13,254 |
https://leetcode.com/problems/most-common-word/discuss/1922398/Python-or-using-Counter | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph=paragraph.lower()
paragraph=re.sub(r'[,.!?;\']',' ',paragraph)
paragraph=paragraph.split()
paragraph=[w for w in paragraph if w not in banned]
PC=Counter(paragraph)
hold=sorted(PC.items(),key=lambda x:x[1], reverse=True)
return hold[0][0] | most-common-word | Python | using Counter | ginaaunchat | 0 | 80 | most common word | 819 | 0.449 | Easy | 13,255 |
https://leetcode.com/problems/most-common-word/discuss/1908088/Easiest-and-Simplest-Python3-Solution-oror-Faster-100-oror-Easy-to-Understand | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph=paragraph.lower()
sym='''!()-[]{};:'"\,<>./?@#$%^&*_~'''
sym=list(sym)
d = {}
for j in paragraph:
for k in j:
if k in sym:
paragraph = paragraph.replace(k,' ')
x=paragraph.split(' ')
x=list(x)
for i in x:
if i not in banned and i!='':
if i not in d:
d[i]=1
else:
d[i]=d[i]+1
max=0
temp=[]
for k, v in d.items():
if v==max:
temp.append(k)
if v>max:
max=v
temp=[]
temp.append(k)
return "".join(temp) | most-common-word | Easiest & Simplest Python3 Solution || Faster 100% || Easy to Understand | RatnaPriya | 0 | 74 | most common word | 819 | 0.449 | Easy | 13,256 |
https://leetcode.com/problems/most-common-word/discuss/1851724/PYTHON-SIMPLE-step-by-step-solution-(28ms) | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
#Clean the paragraph
cleaned = [];
#For each character, append it to the list if
for char in paragraph:
#It is a lowercase character
if (char >= 'a' and char <= 'z' ):
cleaned.append( char );
#It is an uppercase character that we can lower
elif (char >= 'A' and char <= 'Z' ):
cleaned.append( char.lower() );
#But if it is a whitespace or anything else
#We assign a whitespace
else:
cleaned.append( ' ' );
#We reassemble the cleaned paragraph
wordsPara = "".join( cleaned );
#And then split it by white space to get the words
wordsPara = wordsPara.split();
#Lastly, we count the uniqie words
counter = Counter( wordsPara ) ;
#Make a set for the banned words
banHammer = set();
#Add the lower case version to the set
for ban in banned:
banHammer.add( ban.lower() );
#For each banned word
for key in banHammer:
#If it is in our counter
#We delete the key
if key in counter:
del counter[ key ];
#Lastly, we track the max occurences and max word
maxOccurence = -1;
maxWord = None;
#As we go through our counter
for word in counter:
#Each time looking at the occurences
occurence = counter[ word ];
#And if there is a more frequently appearing word
if occurence > maxOccurence:
#Updating the max
maxOccurence = occurence;
#And assigning the maxWord to be that word
maxWord = word;
#We return the maxWord
return maxWord; | most-common-word | PYTHON SIMPLE step-by-step solution (28ms) | greg_savage | 0 | 103 | most common word | 819 | 0.449 | Easy | 13,257 |
https://leetcode.com/problems/most-common-word/discuss/1686270/Python-(3-Lines)-Using-Regex-Counter-and-Generator | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# Replace special characters with spaces and convert the banned list to a set
paragraph, banned = re.sub("[,.?'!;]", " ", paragraph), set(banned)
words = Counter(paragraph.lower().split()).most_common()
return next((word for word, _ in words if word not in banned), "") | most-common-word | Python (3 Lines) - Using Regex, Counter & Generator | TheGreatMuffinMan | 0 | 55 | most common word | 819 | 0.449 | Easy | 13,258 |
https://leetcode.com/problems/most-common-word/discuss/1644303/Simple-Python3-solution-with-no-imports-%2B-memory-efficient | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
paragraph = paragraph.lower()
punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
for i in paragraph:
if i in punctuation:
paragraph = paragraph.replace(i, " ")
words = paragraph.split()
unique_words = " ".join(sorted(set(words), key=words.index)).split()
for i in unique_words[:]:
if i in banned:
unique_words.remove(i)
res = {}
for i in paragraph.split():
if i in unique_words:
res[i] = paragraph.split().count(i)
return max(res, key=res.get) | most-common-word | Simple Python3 solution with no imports + memory efficient | y-arjun-y | 0 | 74 | most common word | 819 | 0.449 | Easy | 13,259 |
https://leetcode.com/problems/most-common-word/discuss/1634063/Python3-96.60-Faster-47.85-Less-memory-usage | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
s = "!?',;."
paragraph = paragraph.lower()
for i in s:
paragraph =paragraph.replace(i, " ")
paragraph = paragraph.split()
occur = {}
for word in paragraph:
if word not in banned:
if word in occur:
occur[word] += 1
else:
occur[word] = 1
maximum = 0
result = None
for k, v in occur.items():
if v > maximum:
maximum = v
result = k
return result | most-common-word | Python3 96.60% Faster, 47.85% Less memory usage | Ghadeer_Elsalhawy | 0 | 90 | most common word | 819 | 0.449 | Easy | 13,260 |
https://leetcode.com/problems/most-common-word/discuss/1619168/Python-Two-Solutions-with-Explanation-beats-99.89-memory-96.32-runtime | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# going to populate set with O(1) lookup time in comparison to O(n)
banned = set(banned)
# purge all symbols
for i in "!?',;.":
paragraph = paragraph.replace(i, " ")
words = {}
paragraph = paragraph.lower()
# two choices here:
# .split() O(n) space
# two pointers O(1)
# both will require O(n) time, so we should go ahead and pick the optimal space solution
p1, p2 = 0, 0
while p2 <= len(paragraph):
if p2 == len(paragraph) or paragraph[p2] == " ": # if we are at the end of a word / paragraph
word = paragraph[p1:p2] # pick up the word
if word not in banned:
if word in words:
words[word] += 1
else:
words[word] = 1
# find next word, or end, whichever comes first
while p2 < len(paragraph) and paragraph[p2] == " ":
p2 += 1
p1 = p2
p2 += 1
return max(words, key=words.get) | most-common-word | [Python] Two Solutions with Explanation, beats 99.89% memory 96.32% runtime | mateoruiz5171 | 0 | 116 | most common word | 819 | 0.449 | Easy | 13,261 |
https://leetcode.com/problems/most-common-word/discuss/1619168/Python-Two-Solutions-with-Explanation-beats-99.89-memory-96.32-runtime | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# going to populate set with O(1) lookup time in comparison to O(n)
banned = set(banned)
# purge all symbols
for i in "!?',;.":
paragraph = paragraph.replace(i, " ")
words = {}
# two choices here:
# .split() O(n) space
# two pointers O(1) space
# we can try and attempt better run time using split, at the expense of having O(n + b) aux space
paragraph = paragraph.lower().split()
for word in paragraph:
if word not in banned:
if word in words:
words[word]+=1
else:
words[word]=1
return max(words, key=words.get) | most-common-word | [Python] Two Solutions with Explanation, beats 99.89% memory 96.32% runtime | mateoruiz5171 | 0 | 116 | most common word | 819 | 0.449 | Easy | 13,262 |
https://leetcode.com/problems/most-common-word/discuss/1547444/python3 | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
# can also use
# normalized_str = ''.join([c.lower() if c.isalnum() else ' ' for c in paragraph]) to remove punctuactions
# then split() -> words = normalized_str.split()
word_list = re.findall(r'\w+', paragraph.lower())
maps = {}
for word in word_list:
if word.isalpha():
maps[word] = maps.get(word, 0) + 1
if banned:
for word in banned:
if word in maps:
maps.pop(word.lower())
# for key,value in sorted(maps.items(), key = lambda x: x[1], reverse = True):
# print(key, value)
# return key
# or write like below
return max(maps.items(), key = lambda x: x[1])[0]
# Amazon | most-common-word | python3 | siyu14 | 0 | 82 | most common word | 819 | 0.449 | Easy | 13,263 |
https://leetcode.com/problems/most-common-word/discuss/1425694/Python3%3A-List-and-Dictionary-Comprehension | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
punc = [",", ".", "!", "?", ";", "'"]
for i in range(len(punc)):
paragraph = paragraph.replace(punc[i], " ")
paragraph = [char.lower() for char in paragraph.split() if char.lower() not in banned]
counts = {word:paragraph.count(word) for word in paragraph}
max_num = max(counts.values())
for word, num in counts.items():
if num == max_num:
return word | most-common-word | Python3: List and Dictionary Comprehension | pan3l | 0 | 51 | most common word | 819 | 0.449 | Easy | 13,264 |
https://leetcode.com/problems/most-common-word/discuss/844418/Python3-Easy-to-understand-using-Hash-map | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
modified_para=''
for i,letter in enumerate(paragraph):
if letter in ("!", "?", "'", ",", ";", "."):
modified_para+= " "
else:
modified_para+=letter
para=modified_para.split(" ")
new_para=[]
for i, word in enumerate(para):
if word:
new_para.append(word.lower())
hmap={}
max_w,max_l='',0
for i, word in enumerate(new_para):
if word not in hmap:
hmap[word]=1
else:
hmap[word]+=1
if max_l<hmap[word] and word not in banned:
max_l=hmap[word]
max_w=word
return max_w | most-common-word | [Python3] Easy to understand using Hash map | _vaishalijain | 0 | 111 | most common word | 819 | 0.449 | Easy | 13,265 |
https://leetcode.com/problems/most-common-word/discuss/405400/Python3%3A-Regex-and-dict-(40-ms-13.9-MB) | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
ret = ""
seen = {} # {word: times seen}
words = []
# 1: populate dict with words, except banned
words = re.findall(r"[\w]+", paragraph.lower())
for word in words:
if word not in banned:
seen[word] = seen.get(word, 0) + 1
# 2: find the most seen
maxseen = 0
for w in seen:
if maxseen < seen[w]:
maxseen = seen[w]
ret = w
return ret | most-common-word | Python3: Regex and dict (40 ms, 13.9 MB) | coderr0r | 0 | 181 | most common word | 819 | 0.449 | Easy | 13,266 |
https://leetcode.com/problems/most-common-word/discuss/401945/Python-with-dictionary-one-pass | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
ban = set(banned)
m = collections.defaultdict(int)
current = ''
for c in paragraph.lower():
if c.isalpha():
current += c
elif current and current not in ban:
m[current] += 1
current = ''
else:
current = ''
if current and current not in ban:
m[current] += 1
return max(m.keys(), key = lambda k: m[k]) | most-common-word | Python with dictionary, one pass | noonamer | 0 | 147 | most common word | 819 | 0.449 | Easy | 13,267 |
https://leetcode.com/problems/most-common-word/discuss/384407/Solution-in-Python-3-(beats-~94)-(two-lines) | class Solution:
def mostCommonWord(self, p: str, b: List[str]) -> str:
a = ''
for i in p:
if i in "!?',;.": i = ' '
a += i
a, M = a.lower().split(), 0
for i in set(a):
if i in b: continue
m = a.count(i)
if m > M: M, w = m, i
return w | most-common-word | Solution in Python 3 (beats ~94%) (two lines) | junaidmansuri | 0 | 504 | most common word | 819 | 0.449 | Easy | 13,268 |
https://leetcode.com/problems/most-common-word/discuss/384407/Solution-in-Python-3-(beats-~94)-(two-lines) | class Solution:
def mostCommonWord(self, p: str, b: List[str]) -> str:
P = collections.Counter(i for i in "".join(i if i not in "!?',;." else ' ' for i in p).lower().split() if i not in set(b))
return max(zip(P.values(),P.keys()))[1]
- Junaid Mansuri
(LeetCode ID)@hotmail.com | most-common-word | Solution in Python 3 (beats ~94%) (two lines) | junaidmansuri | 0 | 504 | most common word | 819 | 0.449 | Easy | 13,269 |
https://leetcode.com/problems/most-common-word/discuss/839063/Python3-solution-using-replace-and-no-regex | class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
result = ''
word_count = {}
# Replace all puctuations with white spaces
paragraph = paragraph.lower()\
.replace('!', ' ')\
.replace('?', ' ')\
.replace('\'', ' ')\
.replace(',', ' ')\
.replace(';', ' ')\
.replace('.', ' ')
# Split paragraph by white spaces (irrespective of the nubmer of white spaces)
for w in paragraph.split():
if w not in banned: # Optional: can use set() to drop duplicates in banned
# Increase word count
word_count[w] = word_count.get(w, 0) + 1
# If new word has a count greater than previous word then replace resulting word
if word_count[w] > word_count.get(result, 0):
result = w
return result | most-common-word | Python3 solution using replace and no regex | ecampana | -1 | 265 | most common word | 819 | 0.449 | Easy | 13,270 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key=len, reverse=True)
res = []
for suffix in words:
if not any(word.endswith(suffix) for word in res): # check that this word is not actually a suffix
res.append(suffix)
return sum(len(word)+1 for word in res) # append hash '#' symbol to each word that is not a suffix | short-encoding-of-words | [Python] Concise Brute Force & Trie Solutions with Explanation | zayne-siew | 23 | 1,100 | short encoding of words | 820 | 0.607 | Medium | 13,271 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = set(words) # important - e.g. ["time","time"] -> "time#"
counter = Counter(word[i:] for word in words for i in range(len(word)))
return sum(len(word)+1 for word in words if counter[word] == 1) | short-encoding-of-words | [Python] Concise Brute Force & Trie Solutions with Explanation | zayne-siew | 23 | 1,100 | short encoding of words | 820 | 0.607 | Medium | 13,272 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
trie = (d := lambda: defaultdict(d))() # multi-level collections.defaultdict
for word in words:
curr = trie
for i in range(len(word)):
curr = curr[word[~i]]
return (dfs := lambda node, curr: sum(dfs(adj, curr+1) for adj in node.values()) if node else curr)(trie, 1) | short-encoding-of-words | [Python] Concise Brute Force & Trie Solutions with Explanation | zayne-siew | 23 | 1,100 | short encoding of words | 820 | 0.607 | Medium | 13,273 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = list(set(words))
trie = (d := lambda: defaultdict(d))()
nodes = [reduce(dict.__getitem__, word[::-1], trie) for word in words] # equivalent to trie[word[-1]][word[-2]]...
return sum((len(word)+1) for word, node in zip(words, nodes) if len(node) == 0) | short-encoding-of-words | [Python] Concise Brute Force & Trie Solutions with Explanation | zayne-siew | 23 | 1,100 | short encoding of words | 820 | 0.607 | Medium | 13,274 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2173272/Easy-Python-Solution-using-hashmap-with-Explanation-and-Comments | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
# hashmap to store all the non repeating words
store = {}
# storing all the words in hashmap for faster access O(1)
for w in words:
store[w] = 1
"""
going through each word and checking if any of the
suffix is present as a different word in the initial array
Note: the max length of array `words` = n
and max length of any word in the array, i.e. `words[i].length` <= 7
deletion in hashmap worst case complexity: O(n); average/best case: O(1)
Therefore the time complexity would be: O(n * 7 * n) = O(n^2)
"""
for w in words:
for i in range(1, len(w)):
# checking if suffix exists in O(1)
if store.get(w[i:], None):
# deleting the suffix if it exists: worst case complexity O(n)
del store[w[i:]]
# getting the number of elements left in hashmap
cnt = len(store)
# getting lenght of each individual element and adding it to the variable
for k in store.keys():
cnt += len(k)
return cnt | short-encoding-of-words | Easy Python Solution using hashmap with Explanation and Comments | the_sky_high | 4 | 163 | short encoding of words | 820 | 0.607 | Medium | 13,275 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1101151/Explanation-for-the-Clean-Trie-Python-Solution | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = list(set(words))
Trie = lambda: collections.defaultdict(Trie)
trie = Trie()
# For each word put A REFEENCE to her reversed trie traversal in list
nodes = []
for word in words:
current_trie = trie
for c in reversed(word):
current_trie = current_trie[c]
nodes.append(current_trie)
#Add word to the answer if it's node has no neighbors
return sum(len(word) + 1
for i, word in enumerate(words)
if not nodes[i]) | short-encoding-of-words | 🌟Explanation for the Clean Trie Python Solution🌟 | AvivYaniv | 4 | 232 | short encoding of words | 820 | 0.607 | Medium | 13,276 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1095944/Python3-easy-soln-greater-Short-Encoding-of-Words | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key = lambda x : -len(x))
lookup = set()
res = 0
for word in words:
if word in lookup:
continue
res += len(word) + 1
for x in range(1, len(word)+1):
lookup.add(word[-x:])
return res | short-encoding-of-words | [Python3] easy soln -> Short Encoding of Words | avEraGeC0der | 2 | 197 | short encoding of words | 820 | 0.607 | Medium | 13,277 |
https://leetcode.com/problems/short-encoding-of-words/discuss/982733/Python3-trie-and-sort | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
trie = {} # toy trie
for word in words:
node = trie
for c in reversed(word): node = node.setdefault(c, {})
node["#"] = word
# traverse the trie recursively
def fn(node):
"""Traverse the trie to encode words."""
if len(node) == 1 and "#" in node: return len(node["#"]) + 1
ans = 0
for key in node:
if key != "#": ans += fn(node[key])
return ans
return fn(trie) | short-encoding-of-words | [Python3] trie & sort | ye15 | 2 | 119 | short encoding of words | 820 | 0.607 | Medium | 13,278 |
https://leetcode.com/problems/short-encoding-of-words/discuss/982733/Python3-trie-and-sort | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = sorted(word[::-1] for word in words) # reverse & sort
ans, prev = 0, ""
for word in words:
if not word.startswith(prev): ans += len(prev) + 1
prev = word
return ans + len(prev) + 1 | short-encoding-of-words | [Python3] trie & sort | ye15 | 2 | 119 | short encoding of words | 820 | 0.607 | Medium | 13,279 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172378/Python-sorting | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = sorted(w[::-1] for w in words)
result = 0
for i, word in enumerate(words):
if i == len(words) - 1 or not words[i+1].startswith(word):
result += len(word) + 1
return result | short-encoding-of-words | Python, sorting | blue_sky5 | 1 | 24 | short encoding of words | 820 | 0.607 | Medium | 13,280 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2184947/Python-using-Trie | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
res = 0
trie = {}
words.sort(key=lambda x:len(x), reverse=True)
for word in words:
curr = trie
can_encode = True
for c in reversed(word):
if c not in curr:
curr[c] = {}
can_encode = False
curr = curr[c]
if not can_encode:
res += len(word) + 1
return res | short-encoding-of-words | Python using Trie | Kennyyhhu | 0 | 12 | short encoding of words | 820 | 0.607 | Medium | 13,281 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2176515/Python-or-Commented-or-Set-or-O(nlogn) | # Set Solution
# Time: O(nlogn + n), Sorts words list using lenth of words (largest to smallest), then iterates through words list once.
# Space: O(n), Set holding words not in s.
class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key=len, reverse=True) # Sorts words largest to smallest.
wordSet = set(words) # Holds words not in s.
s = '' # Reference string.
for word in words: # Iterates through words.
if word not in wordSet: continue # Continues to next word if already in s.
s += word + '#' # Adds word to s with delimiter.
for i in range(len(word)): # Iterates through word subsequences.
if word[i:] not in wordSet: continue # Conintues to next character is subsequence is not in word set.
wordSet.remove(word[i:]) # Removes subsequence from word set.
return len(s) # Returns length of s, which will be the shortest reference string. | short-encoding-of-words | Python | Commented | Set | O(nlogn) | bensmith0 | 0 | 6 | short encoding of words | 820 | 0.607 | Medium | 13,282 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2176308/Python3-Faster-than-99-Runtime-Less-than-100-Memory | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key = lambda x : x[::-1])
length = 0
for i in range(len(words)-1):
if words[i] != words[i+1][-len(words[i]):]:
length += len(words[i]) + 1
length += len(words[-1]) + 1
return length | short-encoding-of-words | Python3 Faster than 99% Runtime Less than 100% Memory | hcks | 0 | 5 | short encoding of words | 820 | 0.607 | Medium | 13,283 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2173944/Python-Solution-(Easy)-with-comments | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
# Initializing encoded string and array of indices
enc=""
ind=[]
# Sorting words in descending order of length
# Reason: Bigger strings should be parsed first so that smaller words are already there in result
words.sort(key=len,reverse=True)
# Iterate over words
for word in words:
# Append hash to each word as it must end with '#'
s=word+'#'
# If s is not there in encoded string
if s not in enc:
# Add s to enc
enc+=s
# Append index of where the word is to array of indices
ind.append(enc.index(s))
# Return length of encoded string
return len(enc) | short-encoding-of-words | Python Solution (Easy) with comments | sakshiegarg | 0 | 6 | short encoding of words | 820 | 0.607 | Medium | 13,284 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2173882/Python-Simple-Python-Solution-By-Sorting-the-Words-by-Their-Length | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = sorted(words, key = len, reverse = True)
result = ''
for i in words:
if i + '#' not in result:
result = result + i + '#'
return len(result) | short-encoding-of-words | [ Python ] ✅✅ Simple Python Solution By Sorting the Words by Their Length 🥳✌👍 | ASHOK_KUMAR_MEGHVANSHI | 0 | 12 | short encoding of words | 820 | 0.607 | Medium | 13,285 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2173838/Constant-Space-With-Sort-Python-and-Java | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key=lambda x: x[::-1])
last = words[0]
tot = len(last) + 1
for i in range(1,(len(words) ) ):
cur = words[i]
if cur.endswith(last):
tot += len(cur) - len(last)
else:
tot += len(cur) + 1
last = cur
return tot | short-encoding-of-words | Constant Space With Sort - Python & Java | ericghara | 0 | 8 | short encoding of words | 820 | 0.607 | Medium | 13,286 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172849/Python3-BruteForce-Approach | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key=len, reverse=True)
string = ""
for i in words:
if i+'#' not in string:
string+=i+'#'
return len(string) | short-encoding-of-words | Python3 BruteForce Approach | thetimeloops | 0 | 11 | short encoding of words | 820 | 0.607 | Medium | 13,287 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172835/Python3-Solution | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key = lambda x : -len(x))
lookup = set()
res = 0
for word in words:
if word in lookup:
continue
res += len(word) + 1
for x in range(1, len(word)+1):
lookup.add(word[-x:])
return res | short-encoding-of-words | Python3 Solution | creativerahuly | 0 | 11 | short encoding of words | 820 | 0.607 | Medium | 13,288 |
https://leetcode.com/problems/short-encoding-of-words/discuss/2172621/Python-oror-Beats-85-oror-No-trie-oror-15-lines-code | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key = lambda x : -len(x))
lookup = set()
res = 0
for word in words:
if word in lookup:
continue
res += len(word) + 1
for x in range(1, len(word)+1):
lookup.add(word[-x:])
return res | short-encoding-of-words | Python || Beats 85% || No trie || 15 lines code | anirudh_22 | 0 | 15 | short encoding of words | 820 | 0.607 | Medium | 13,289 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1868612/3-Python-Solutions | class Solution:
def minimumLengthEncoding(self, W: List[str]) -> int:
ans=set(W)
for word in W:
for i in range(1,len(word)): ans.discard(word[i:])
return len("#".join(list(ans)))+1 | short-encoding-of-words | 3 Python Solutions | Taha-C | 0 | 48 | short encoding of words | 820 | 0.607 | Medium | 13,290 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1868612/3-Python-Solutions | class Solution:
def minimumLengthEncoding(self, W: List[str]) -> int:
W.sort(key=len,reverse=True) ; ans=''
for i in W:
if i+'#' not in ans: ans+=i+'#'
return len(ans) | short-encoding-of-words | 3 Python Solutions | Taha-C | 0 | 48 | short encoding of words | 820 | 0.607 | Medium | 13,291 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1868612/3-Python-Solutions | class Solution:
def minimumLengthEncoding(self, W: List[str]) -> int:
ans=len('#'.join(W))+1 ; i=0 ; n=len(W)
while i<n:
j=i+1
while i+1<=j<n:
if W[i][-1]==W[j][-1]:
if W[i] == W[j]: ans-=len(W[j])+1 ; W=W[:j]+W[j+1:] ; j-=1 ; n-=1
elif W[i] in W[j]: ans-=len(W[i])+1 ; W=W[:i]+W[i+1:] ; j-=1 ; n-=1
elif W[j] in W[i]: ans-=len(W[j])+1 ; W=W[:j]+W[j+1:] ; j-=1 ; n-=1
j+=1
i+=1
return ans | short-encoding-of-words | 3 Python Solutions | Taha-C | 0 | 48 | short encoding of words | 820 | 0.607 | Medium | 13,292 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1386283/Python-100-fast-O(nlogn)-short-and-clean | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = [word[::-1] for word in words]
words.sort(reverse=True)
ans = len(words[0])+1
for i in range(1,len(words)):
if words[i]==words[i-1][:len(words[i])]:
continue
else:
ans+=len(words[i])+1
return ans | short-encoding-of-words | Python, 100% fast, O(nlogn), short & clean | Ulankenway | 0 | 86 | short encoding of words | 820 | 0.607 | Medium | 13,293 |
https://leetcode.com/problems/short-encoding-of-words/discuss/1095909/Python3-Java-Sorting-array-O%3A-nlogn | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words = sorted(words,key=len)
#print(words)
ret = ''
for w in words[::-1]:
if (w+'#') not in ret:
ret = ret + w +'#'
#print(ret)
return len(ret) | short-encoding-of-words | [Python3, Java] Sorting array O: nlogn | lemi99 | 0 | 76 | short encoding of words | 820 | 0.607 | Medium | 13,294 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1226696/Python3Any-improvement | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
L = []
for idx, value in enumerate(s):
if value == c:
L.append(idx)
distance = []
i = 0
for idx, value in enumerate(s):
if value == c:
distance.append(0)
i += 1
elif idx < L[0]:
distance.append(L[0] - idx)
elif idx > L[-1]:
distance.append(idx - L[-1])
else:
distance.append(min((L[i] - idx), (idx - L[i-1])))
return distance | shortest-distance-to-a-character | 【Python3】Any improvement ? | qiaochow | 5 | 293 | shortest distance to a character | 821 | 0.714 | Easy | 13,295 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1090998/2-line-python-solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
ids = [i for i in range(len(s)) if s[i] == c]
return [min([abs(i-id_) for id_ in ids]) for i in range(len(s))] | shortest-distance-to-a-character | 2-line python solution | mhviraf | 4 | 476 | shortest distance to a character | 821 | 0.714 | Easy | 13,296 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/914650/Python3-100-faster-100-less-memory-(20ms-14mb) | class Solution:
def shortestToChar(self, S: str, C: str) -> List[int]:
l = [0] * len(S)
prev = None
for i, x in enumerate(S):
if x == C:
# only correct the closer half of the indexes between previous and current if previous is not None
start = 0 if prev is None else (i + prev) // 2 + 1
# slice assign where corrections are needed to a range
l[start:i + 1] = range(i - start, -1, -1)
prev = i
elif prev is not None:
l[i] = i - prev
return l | shortest-distance-to-a-character | Python3 100% faster, 100% less memory (20ms, 14mb) | haasosaurus | 4 | 709 | shortest distance to a character | 821 | 0.714 | Easy | 13,297 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1054131/Python.-O(n)-Simple-and-easy-understanding-cool-solution. | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
n = lastC =len(s)
ans = [n] * n
for i in itertools.chain(range(n), range(n)[::-1]):
if s[i] == c: lastC = i
ans[i] = min(ans[i], abs( i - lastC))
return ans | shortest-distance-to-a-character | Python. O(n), Simple & easy-understanding cool solution. | m-d-f | 3 | 363 | shortest distance to a character | 821 | 0.714 | Easy | 13,298 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2183851/Python3-O(n)-oror-O(n)-Runtime%3A-53ms-78.92-Memory%3A-13.9mb-91.60 | class Solution:
def shortestToChar(self, string: str, char: str) -> List[int]:
return self.optimalSolution(string, char)
# O(n) || O(n)
# Runtime: 53ms 78.92% Memory: 13.9mb 91.60%
def optimalSolution(self, string, char):
n = len(string)
leftArray, rightArray, result = ([float('inf')] * n,
[float('inf')] * n,
[float('inf')] * n)
temp = float('inf')
for i in range(len(string)):
if string[i] == char:
temp = 0
leftArray[i] = temp
temp += 1
temp = float('inf')
for i in reversed(range(len(string))):
if string[i] == char:
temp = 0
rightArray[i] = temp
temp += 1
for i in range(len(result)):
result[i] = min(leftArray[i], rightArray[i])
return result
# O(n^2) || O(n) Runtime: TLE
def bruteForce(self, string, char):
sequence = [float('inf')] * len(string)
newList = []
for idx, val in enumerate(string):
if val == char:
newList.append(idx)
for val1 in newList:
for idx2, val2 in enumerate(string):
sequence[idx2] = min(sequence[idx2], abs(idx2-val1))
return sequence | shortest-distance-to-a-character | Python3 O(n) || O(n) # Runtime: 53ms 78.92% Memory: 13.9mb 91.60% | arshergon | 2 | 126 | shortest distance to a character | 821 | 0.714 | Easy | 13,299 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.