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==...
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: ...
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 r...
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...
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 ret...
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 r...
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: ret...
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 ...
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...
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 =...
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: ...
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...
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 ...
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 retur...
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)...
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.pr...
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....
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: ...
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...
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 ran...
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[...
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 rou...
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() ...
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")...
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)):...
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)...
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(...
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 anothe...
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:][-...
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 ...
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: ...
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: ...
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 re...
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 el...
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 ...
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): ...
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+spe...
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...
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 ...
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 = ''...
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(" ") ...
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()) ...
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 != ""...
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,...
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, ' ') ...
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+=p...
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 ban...
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(...
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:...
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=sor...
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='''!()-[]{};:'"\,<>./?@#$%^&amp;*_~''' sym=list(sym) d = {} for j in paragraph: for k in j: if k in sym: paragra...
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' ...
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() ret...
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 = '''!()-[]{};:'"\,<>./?@#$%^&amp;*_~''' for i in paragraph: if i in punctuation: paragraph = paragraph.replace(i, " ") ...
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 w...
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, " ") ...
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, " ") ...
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.fin...
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 ...
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...
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 ...
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 i...
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('...
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) ...
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 := lambd...
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 w...
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 d...
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: ...
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 ...
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 ...
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 &amp; sort ans, prev = 0, "" for word in words: if not word.startswith(prev): ans += len(prev) + 1 prev = word return ans + len(p...
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 ...
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: ...
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...
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 ...
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 wor...
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) ...
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)...
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)...
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 ...
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])]: ...
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: dista...
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 No...
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')...
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