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/find-right-interval/discuss/2812012/Python-Sort-and-Two-Pointers-(Same-approach-as-826.-Most-Profit-Assigning-Work) | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
start = sorted([[intervals[i][0], i] for i in range(len(intervals))])
end = sorted([[intervals[i][1], i] for i in range(len(intervals))])
i = 0
res = []
for endVal, endIdx in end:
while i < len(start) and (endVal > start[i][0]):
i += 1
if i < len(start):
res.append(start[i][1])
else:
while len(res) < len(start):
res.append(-1)
ans = []
for i in range(len(end)):
ans.append((end[i][1], res[i]))
ans.sort()
return [ele[1] for ele in sorted([[a[1], b] for a, b in zip(end, res)])] | find-right-interval | [Python] Sort and Two Pointers (Same approach as # 826. Most Profit Assigning Work) | low_key_low_key | 0 | 4 | find right interval | 436 | 0.504 | Medium | 7,700 |
https://leetcode.com/problems/find-right-interval/discuss/2644967/Python-binary-search-solution-%2B-sorting-O(nlogn) | class Solution:
def findRightInterval(self, intervals: list[list[int]]) -> list[int]:
tmp, ans = sorted(intervals), []
indices = {tuple(j): i for i, j in enumerate(intervals)}
for i in intervals:
res = Solution().binary_search(tmp, i[1]) or ()
ans.append(indices.get(tuple(res), -1))
return ans
def binary_search(self, arr, target):
l, r = 0, len(arr) - 1
while l <= r:
mid = (l + r) // 2
element = arr[mid][0]
if element < target:
l = mid + 1
elif element > target:
r = mid - 1
else:
return arr[mid]
return None if l >= len(arr) else arr[l] | find-right-interval | Python binary-search solution + sorting O(nlogn) | Mark_computer | 0 | 28 | find right interval | 436 | 0.504 | Medium | 7,701 |
https://leetcode.com/problems/find-right-interval/discuss/2606150/Python3-or-Solved-Using-Hashmap-Binary-Search-and-Sorting-greater-O(nlogn)-runtime! | class Solution:
#Let n = len(intervals)!
#Time-Complexity: O(n + nlogn + n*log(n)) -> O(nlogn)
#Space-Complexity: O(n + n) -> O(n)
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
#Brute-Force Approach: For every interval, linearly consider every other intervals
#and constantly update the lowest start value s.t. it is >= current interval's
#end value!
ans = []
hashmap = {}
arr_of_starts = []
#initializing hashmap by mapping keys as start values to the index pos. of the interval it
#belongs within!
for i in range(len(intervals)):
if(intervals[i][0] not in hashmap):
hashmap[intervals[i][0]] = i
arr_of_starts.append(intervals[i][0])
continue
#need to sort the arr_of_starts beforehand!
arr_of_starts.sort()
#iterate for each interval from left to right and find the interval with start value that's minimal
#s.t. it's greater than or equal to current interval's end value!
for j in range(len(intervals)):
cur_end = intervals[j][1]
#first, check if right interval is of itself!
if(cur_end == intervals[j][0]):
ans.append(j)
continue
#define search space w/ respect to arr of starts!
L, R = 0, len(arr_of_starts) - 1
index, lowest_start = -1, float(inf)
#as long as binary search has at least one element, continue iterations of bin. search!
while L <= R:
mid = (L + R) // 2
mid_e = arr_of_starts[mid]
#check if current middle candidate start value is >= cur_end!
if(mid_e >= cur_end):
#check if current candidate start value beats the lowest_start!
if(mid_e < lowest_start):
lowest_start = mid_e
index = hashmap[lowest_start]
#there might be even smaller values of start that satisfies criteria!
R = mid - 1
continue
#if current start value is too small, we need to search towards right portion!
else:
L = mid + 1
continue
ans.append(index)
return ans | find-right-interval | Python3 | Solved Using Hashmap, Binary-Search, and Sorting -> O(nlogn) runtime! | JOON1234 | 0 | 12 | find right interval | 436 | 0.504 | Medium | 7,702 |
https://leetcode.com/problems/find-right-interval/discuss/2405586/Python-3-Binary-search | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
A=sorted([[intervals,i] for i,intervals in enumerate(intervals)])
def find(end):
l,r=0,len(A)-1
res=-1
while l<=r:
mid=l+(r-l)//2
if A[mid][0][0]>=end:
res=A[mid][1]
r=mid-1
else:
l=mid+1
return res
res=[]
for start,end in intervals:
res.append(find(end))
return res | find-right-interval | [Python 3] Binary search | gabhay | 0 | 30 | find right interval | 436 | 0.504 | Medium | 7,703 |
https://leetcode.com/problems/find-right-interval/discuss/2078070/python-3-oror-simple-binary-search-solution-oror-O(nlogn)-O(n) | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
n = len(intervals)
starts = sorted((interval[0], i) for i, interval in enumerate(intervals))
res = []
for interval in intervals:
rightInterval = bisect.bisect_left(starts, interval[1], key=lambda x: x[0])
res.append(starts[rightInterval][1] if rightInterval != n else -1)
return res | find-right-interval | python 3 || simple binary search solution || O(nlogn) / O(n) | dereky4 | 0 | 82 | find right interval | 436 | 0.504 | Medium | 7,704 |
https://leetcode.com/problems/find-right-interval/discuss/1558998/Python-3-simple-Solution-beats-92.52-in-runtime-96.88-in-memory-using-Binary-Search | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
start = [ (interval[0], i) for i, interval in enumerate(intervals)]
start = sorted(start, key = lambda x: x[0])
start_search = [ i[0] for i in start]
rst = []
for interval in intervals:
end = interval[1]
pos = bisect.bisect_left(start_search, end)
x = start[pos][1] if pos < len(start) else -1
rst.append(x)
return rst | find-right-interval | Python 3 simple Solution beats 92.52% in runtime; 96.88% in memory using Binary Search | kate_nhy | 0 | 94 | find right interval | 436 | 0.504 | Medium | 7,705 |
https://leetcode.com/problems/find-right-interval/discuss/1507078/99-faster-oror-Greedy-Approach-oror-Well-Explained-oror-For-Beginners | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
res = [-1 for _ in range(len(intervals))]
dic = dict()
for i,ele in enumerate(intervals):
dic[ele[0]] = i
keys = sorted(dic.keys())
i = 0
for s,e in intervals:
if e<=keys[-1]:
ind = bisect.bisect_left(keys,e)
res[i] = dic[keys[ind]]
i+=1
return res | find-right-interval | ππ 99% faster || Greedy-Approach || Well-Explained || For Beginners π | abhi9Rai | 0 | 141 | find right interval | 436 | 0.504 | Medium | 7,706 |
https://leetcode.com/problems/find-right-interval/discuss/1453199/Simple-Python-O(nlogn)-sort%2Bbinary-search-solution | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
# add original indices to the intervals O(n)
for i in range(len(intervals)):
intervals[i].append(i)
# sort intervals by start O(nlogn)
intervals.sort()
ret = [-1]*len(intervals)
for i in range(len(intervals)): # O(nlogn)
_, target_end, old_idx = intervals[i]
# since the starts are sorted, we can use
# binary search to find the intervals with the
# smallest start that is larger than target_end
left, right = i, len(intervals)
while left < right:
mid = left+(right-left)//2
if intervals[mid][0] < target_end:
left = mid+1
else:
right = mid
# update ret with old index
if left < len(intervals) and intervals[left][0] >= target_end:
ret[old_idx] = intervals[left][2]
return ret | find-right-interval | Simple Python O(nlogn) sort+binary search solution | Charlesl0129 | 0 | 121 | find right interval | 436 | 0.504 | Medium | 7,707 |
https://leetcode.com/problems/find-right-interval/discuss/815413/Python-3-or-Binary-Search-or-Explanation | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
intervals = [interval + [i] for i, interval in enumerate(intervals)]
intervals.sort()
n = len(intervals)
ans = [-1] * n
for i, vals in enumerate(intervals):
(_, r, ori_idx) = vals
begin, end = i+1, n-1
while begin <= end:
mid = (begin+end) // 2
if r <= intervals[mid][0]: end = mid - 1
else: begin = mid + 1
ans[ori_idx] = intervals[begin][2] if begin < n else -1
return ans | find-right-interval | Python 3 | Binary Search | Explanation | idontknoooo | 0 | 112 | find right interval | 436 | 0.504 | Medium | 7,708 |
https://leetcode.com/problems/find-right-interval/discuss/814990/Python3-binary-search-and-heap | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
ans = []
start, mp = zip(*sorted((x, i) for i, (x, _) in enumerate(intervals)))
for x, y in intervals:
i = bisect_left(start, y)
ans.append(mp[i] if 0 <= i < len(intervals) else -1) # mapping to original index
return ans | find-right-interval | [Python3] binary search & heap | ye15 | 0 | 47 | find right interval | 436 | 0.504 | Medium | 7,709 |
https://leetcode.com/problems/find-right-interval/discuss/814990/Python3-binary-search-and-heap | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
ans = [-1] * len(intervals)
hp = []
for i, (x, y) in sorted(enumerate(intervals), key=lambda x: x[1]):
while hp and hp[0][0] <= x:
_, k = heappop(hp)
ans[k] = i
heappush(hp, (y, i))
return ans | find-right-interval | [Python3] binary search & heap | ye15 | 0 | 47 | find right interval | 436 | 0.504 | Medium | 7,710 |
https://leetcode.com/problems/find-right-interval/discuss/814615/Python-O(nlogn)-time-using-dictionary%2Bbinary-search-without-enumerate | class Solution:
def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
if not intervals:
return []
if len(intervals) == 1:
return [-1]
ref = dict()
res = []
# fill ref with key = start point, value = index
for i in range(len(intervals)):
ref[intervals[i][0]] = i
# sort dict items by key, and store as a list of lists [start, index]
reflist = sorted(ref.items(), key=lambda x: x[0])
for i in range(len(intervals)):
left = 0
right = len(reflist)-1
mid = (left+right) // 2
while left < mid and right > mid:
if intervals[i][1] == reflist[mid][0]:
res.append(reflist[mid][1])
break
elif intervals[i][1] > reflist[mid][0]:
left = mid
mid = (left+right)//2
elif intervals[i][1] < reflist[mid][0]:
right = mid
mid = (left+right)//2
if mid == left:
if intervals[i][1] <= reflist[mid+1][0]:
res.append(reflist[mid+1][1])
else:
res.append(-1)
return res | find-right-interval | Python O(nlogn) time using dictionary+binary search, without enumerate | Mowei | 0 | 30 | find right interval | 436 | 0.504 | Medium | 7,711 |
https://leetcode.com/problems/find-right-interval/discuss/406619/Python-3-(five-lines)-(beats-~93) | class Solution:
def findRightInterval(self, I: List[List[int]]) -> List[int]:
N, S, A, D, k = len(I), sorted(i[0] for i in I), [-1]*len(I), {j[0]:i for i,j in enumerate(I)}, 0
for L,R in sorted(I, key = lambda x: x[1]):
k = bisect.bisect_left(S,R,k)
if k < N: A[D[L]] = D[S[k]]
return A
- Junaid Mansuri | find-right-interval | Python 3 (five lines) (beats ~93%) | junaidmansuri | 0 | 318 | find right interval | 436 | 0.504 | Medium | 7,712 |
https://leetcode.com/problems/path-sum-iii/discuss/1049652/Python-Solution | class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
global result
result = 0
def dfs(node, target):
if node is None: return
find_path_from_node(node, target)
dfs(node.left, target)
dfs(node.right, target)
def find_path_from_node(node, target):
global result
if node is None: return
if node.val == target: result += 1
find_path_from_node(node.left, target-node.val)
find_path_from_node(node.right, target-node.val)
dfs(root, sum)
return result | path-sum-iii | Python Solution | dev-josh | 14 | 631 | path sum iii | 437 | 0.486 | Medium | 7,713 |
https://leetcode.com/problems/path-sum-iii/discuss/1850435/Python3-Prefix-Sum | class Solution(object):
def pathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: int
"""
self.targetSum=targetSum
self.hashmap={0:1}
self.prefix=0
self.result=0
self.helper(root)
return self.result
def helper(self, root):
if root is None:
return
self.prefix+=root.val
if self.prefix-self.targetSum in self.hashmap:
self.result+=self.hashmap[self.prefix-self.targetSum]
if self.prefix in self.hashmap:
self.hashmap[self.prefix]+=1
else:
self.hashmap[self.prefix]=1
self.helper(root.left)
self.helper(root.right)
self.hashmap[self.prefix]-=1
self.prefix-=root.val | path-sum-iii | Python3 Prefix Sum | muzhang90 | 2 | 109 | path sum iii | 437 | 0.486 | Medium | 7,714 |
https://leetcode.com/problems/path-sum-iii/discuss/843234/Python3-memoized-table-w-backtracking | class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
seen = {0: 1}
def fn(node, prefix):
"""Return number of paths summing to target for tree rooted at node."""
if not node: return 0 #base condition
prefix += node.val # prefix sum up to node
ans = seen.get(prefix - sum, 0)
seen[prefix] = 1 + seen.get(prefix, 0)
ans += fn(node.left, prefix) + fn(node.right, prefix)
seen[prefix] -= 1 # backtrack
return ans
return fn(root, 0) | path-sum-iii | [Python3] memoized table w/ backtracking | ye15 | 2 | 107 | path sum iii | 437 | 0.486 | Medium | 7,715 |
https://leetcode.com/problems/path-sum-iii/discuss/2317497/Python-Simple-Idea-with-Explanation | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
# Sum up from root to each depth and check if it's equal to targetSum
def dfs_calc_sum(root, path):
if not root:
return
path += root.val
if path == targetSum:
nonlocal sum_count
sum_count += 1
dfs_calc_sum(root.left, path)
dfs_calc_sum(root.right, path)
# Send each node to dfs_calc_sum function
def patrol(root):
if not root:
return
dfs_calc_sum(root, 0)
patrol(root.left)
patrol(root.right)
sum_count = 0
patrol(root)
return sum_count | path-sum-iii | Python Simple Idea with Explanation | codeee5141 | 1 | 146 | path sum iii | 437 | 0.486 | Medium | 7,716 |
https://leetcode.com/problems/path-sum-iii/discuss/2697469/Python3-Recursive-easy-Solution | class Solution:
def __init__(self):
self.ans = 0
def helper(self,root: Optional[TreeNode], targetSum: int,summ: int) ->None:
if root is None:
return
if summ==targetSum:
self.ans+=1
if root.left:
self.helper(root.left, targetSum, summ + root.left.val)
if root.right:
self.helper(root.right, targetSum, summ + root.right.val)
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
if root is None:
return 0
self.helper(root,targetSum,root.val)
self.pathSum(root.left,targetSum)
self.pathSum(root.right,targetSum)
return self.ans | path-sum-iii | Python3 Recursive easy Solution | pranjalmishra334 | 0 | 16 | path sum iii | 437 | 0.486 | Medium | 7,717 |
https://leetcode.com/problems/path-sum-iii/discuss/2165595/Python-detailed-explination-runtime-57.71-memory-29.91 | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
if not root:
return 0
return self.search(root, targetSum, 0) + self.pathSum(root.left, targetSum) + \
self.pathSum(root.right, targetSum)
def search(self, root, targetSum, prevSum):
if not root:
return 0
ways = root.val + prevSum == targetSum
return ways + self.search(root.left, targetSum, root.val + prevSum) + \
self.search(root.right, targetSum, root.val + prevSum) | path-sum-iii | Python detailed explination, runtime 57.71%, memory 29.91% | tsai00150 | 0 | 67 | path sum iii | 437 | 0.486 | Medium | 7,718 |
https://leetcode.com/problems/path-sum-iii/discuss/2165595/Python-detailed-explination-runtime-57.71-memory-29.91 | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
d = {}
return self.search(root, targetSum, d, 0)
def search(self, root, targetSum, d, curSum):
if not root:
return 0
curSum += root.val # update sum to this node
ways = d.get(curSum-targetSum, 0)
ways += curSum == targetSum
if d.get(curSum, 0):
d[curSum] += 1
else:
d[curSum] = 1
ways += self.search(root.left, targetSum, d, curSum) + \
self.search(root.right, targetSum, d, curSum)
d[curSum] -= 1
if not d[curSum]:
del d[curSum]
return ways | path-sum-iii | Python detailed explination, runtime 57.71%, memory 29.91% | tsai00150 | 0 | 67 | path sum iii | 437 | 0.486 | Medium | 7,719 |
https://leetcode.com/problems/path-sum-iii/discuss/2157133/Python-oror-Python3-oror-BFS%2Bqueue | class Solution(object):
def pathSum(self, root, targetSum):
if root is None:
return 0
queue = [(root,[])]
res = 0
while queue:
node, ans = queue.pop(0)
curr_ans = []
if node.val == targetSum:
res += 1
for val in ans:
sum_val = val + node.val
if sum_val == targetSum:
res += 1
curr_ans.append(sum_val)
curr_ans.append(node.val)
if node.left:
queue.append((node.left, curr_ans))
if node.right:
queue.append((node.right, curr_ans))
return res | path-sum-iii | Python || Python3 || BFS+queue | aul- | 0 | 40 | path sum iii | 437 | 0.486 | Medium | 7,720 |
https://leetcode.com/problems/path-sum-iii/discuss/1484104/Python-Clean-Recursive-DFS | class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
if not root:
return 0
def dfs(node = root, cumv = root.val, hashmap = {0:1}):
nonlocal count
if cumv-targetSum in hashmap:
count += hashmap[cumv-targetSum]
if cumv not in hashmap:
hashmap[cumv] = 0
if node.left:
hashmap[cumv] += 1
dfs(node.left, cumv+node.left.val, hashmap)
hashmap[cumv] -= 1
if node.right:
hashmap[cumv] += 1
dfs(node.right, cumv+node.right.val, hashmap)
hashmap[cumv] -= 1
count = 0
dfs()
return count | path-sum-iii | [Python] Clean Recursive DFS | soma28 | 0 | 198 | path sum iii | 437 | 0.486 | Medium | 7,721 |
https://leetcode.com/problems/path-sum-iii/discuss/1386247/Simple-DFS-in-Python | class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> int:
cnt = 0
if not root:
return cnt
def counter(n: TreeNode, s=0):
nonlocal cnt
if not n:
return
s += n.val
if s == targetSum:
cnt += 1
counter(n.left, s)
counter(n.right, s)
def dfs(n: TreeNode):
if not n:
return
counter(n)
dfs(n.left)
dfs(n.right)
dfs(root)
return cnt | path-sum-iii | Simple DFS in Python | mousun224 | 0 | 222 | path sum iii | 437 | 0.486 | Medium | 7,722 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738367/Python-Sliding-Window(-)-algorithm-Detailed-Explanation-Concise-Soln-or-Faster-than-80 | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# take counter of first n elements in s_dict with n = len(p) - 1
s_dict = collections.Counter(s[:len(p)-1])
# counter of p, this should not be changed
p_dict = collections.Counter(p)
start = 0
# final result list
res = []
# We iterate over the string s, and in each step we check if s_dict and p_dict match
for i in range(len(p)-1, len(s)):
# updating the counter & adding the character
s_dict[s[i]] += 1
# checking if counters match
if s_dict == p_dict:
res.append(start)
# remove the first element from counter
s_dict[s[start]] -= 1
#if element count = 0, pop it from the counter
if s_dict[s[start]] == 0:
del s_dict[s[start]]
start += 1
return res | find-all-anagrams-in-a-string | π Python - Sliding Window( π
πͺ) algorithm Detailed Explanation, Concise Soln | Faster than 80% | mystic_sd2001 | 16 | 1,400 | find all anagrams in a string | 438 | 0.49 | Medium | 7,723 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/392090/Solution-in-Python-3-(beats-~100)-(Hash) | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
LS, LP, S, P, A = len(s), len(p), 0, 0, []
if LP > LS: return []
for i in range(LP): S, P = S + hash(s[i]), P + hash(p[i])
if S == P: A.append(0)
for i in range(LP, LS):
S += hash(s[i]) - hash(s[i-LP])
if S == P: A.append(i-LP+1)
return A
- Junaid Mansuri
(LeetCode ID)@hotmail.com | find-all-anagrams-in-a-string | Solution in Python 3 (beats ~100%) (Hash) | junaidmansuri | 12 | 2,700 | find all anagrams in a string | 438 | 0.49 | Medium | 7,724 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/636879/Python-sliding-window-sol-sharing-w-Visualization | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
def helper( s: str, p: str):
signature, size_p = sum( map(hash,p) ), len(p)
size_s = len(s)
if size_s * size_p == 0 or size_p > size_s :
# Quick response:
# Reject empty string
# Reject oversize pattern
return []
cur_signature = sum( map( hash, (s[:size_p]) ) )
for tail_of_window in range( size_p, size_s ):
head_of_window = tail_of_window - size_p
if cur_signature == signature:
yield head_of_window
new_char, old_char = s[tail_of_window], s[ head_of_window ]
cur_signature += ( hash(new_char) - hash(old_char) )
# handle for last iteration
if cur_signature == signature:
yield ( size_s - size_p )
# -----------------------
return [ *helper(s, p) ] | find-all-anagrams-in-a-string | Python sliding-window sol sharing [w/ Visualization] | brianchiang_tw | 6 | 1,100 | find all anagrams in a string | 438 | 0.49 | Medium | 7,725 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738477/Python-3-(500ms)-or-Counter-Sliding-Window-O(n)-Approach-or-Easy-to-Understand | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
m = len(p)-1
res = []
pc = Counter(p)
sc = Counter(s[:m])
for i in range(m,len(s)):
sc[s[i]] += 1
if sc == pc:
res.append(i-len(p)+1)
sc[s[i-len(p)+1]] -= 1
return res | find-all-anagrams-in-a-string | Python 3 (500ms) | Counter Sliding Window O(n) Approach | Easy to Understand | MrShobhit | 5 | 476 | find all anagrams in a string | 438 | 0.49 | Medium | 7,726 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1411882/Two-Python-solutions-sliding-window-or-prefix-sum | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
target = [0]*26
for letter in p:
target[ord(letter)-ord('a')] += 1
count = [0]*26
left = right = 0
ret = []
while right < len(s):
count[ord(s[right])-ord('a')] += 1
if right-left == len(p):
count[ord(s[left])-ord('a')] -= 1
left += 1
if count == target:
ret.append(left)
right += 1
return ret | find-all-anagrams-in-a-string | Two Python solutions, sliding window or prefix sum | Charlesl0129 | 4 | 381 | find all anagrams in a string | 438 | 0.49 | Medium | 7,727 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2421680/Python3-Sliding-window-w-dicts-Explanation-9690 | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# To solve this problem, looping through substrings of s, sorting them each time and comparing to a sorted p will
# work, but will take too long for some of the test cases. How else can we solve this?
# We can use dictionaries! Store how many of which letters are in p and substrings of s!
# E.g. 'ac' -> {'a': 1, 'c': 1}
# However, looping through chars of each substring in s and creating a new dict each time takes too long. Darn.
# What if we could have one dict representing the current substring of s, and only update the changed values
# as we move the window across?!
# This function returns a dictionary object containing the number of each letter in a string
# It includes zeros for letters that are not in the string
# E.g. 'ac' -> { 'a': 1, 'b': 0, 'c': 1, ... 'z': 0 }
def create_char_dict(string):
chars = {}
for i in range(26):
chars[chr(ord('a')+i)] = 0
for char in string:
chars[char] += 1
return chars
output = []
window = len(p)
# Let's create our full alphabet dict for p and the first substring of s (which goes from 0 to the length of p)
p_chars = create_char_dict(p)
s_chars = create_char_dict(s[0:window])
if s_chars == p_chars: output.append(0)
# Now, each loop we move the substring window of s by 1.
# We update the s_chars dict to remove 1 from the character no longer included in the window, and add one
# for the new character! This saves us from looping again!
# When we find a match between p_chars and s_chars for some substring, all we need to do is save i to our output
i = 0
while i < (len(s) - window):
s_chars[s[i]] -= 1
s_chars[s[i + window]] += 1
i += 1
if s_chars == p_chars: output.append(i)
return output | find-all-anagrams-in-a-string | [Python3] Sliding window w dicts - Explanation 96%/90% | connorthecrowe | 3 | 136 | find all anagrams in a string | 438 | 0.49 | Medium | 7,728 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2375816/Python-or-Easy-solution-with-sliding-window-and-hashmap | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
result = list()
l, r = 0, len(p)-1
s_count, p_count = Counter(s[0:len(p)]), Counter(p)
while True:
# check if valid anagram, if so add leftmost index to result list.
if not len(p_count - s_count):
result.append(l)
# decrease/remove leftmost char from hashmap and increase rightmost count.
if s[l] in s_count: s_count[s[l]] -= 1
r, l = r+1, l+1
if r >= len(s):
break
s_count[s[r]] += 1
return result | find-all-anagrams-in-a-string | [Python] | Easy solution with sliding window and hashmap | lcerone | 3 | 236 | find all anagrams in a string | 438 | 0.49 | Medium | 7,729 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/638702/Common-solution-for-438-and-567 | class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
slow,fast = 0,len(s1)
hmap = collections.Counter(s1)
hmap_temp = collections.Counter(s2[slow:fast])
while fast <= len(s2):
if hmap == hmap_temp:
return True
hmap_temp[s2[slow]] -= 1
if hmap_temp[s2[slow]] == 0:
del hmap_temp[s2[slow]]
if fast < len(s2):
if hmap_temp.get(s2[fast]):
hmap_temp[s2[fast]] += 1
else:
hmap_temp[s2[fast]] = 1
slow += 1
fast += 1
return False | find-all-anagrams-in-a-string | Common solution for #438 and #567 | pratushah | 3 | 241 | find all anagrams in a string | 438 | 0.49 | Medium | 7,730 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/638702/Common-solution-for-438-and-567 | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
result = [] # just need to add this list in order to maintain the list of indexes where anagram of s starts.
slow,fast = 0,len(p)
hmap = collections.Counter(p)
hmap_temp = collections.Counter(s[slow:fast])
while fast <= len(s):
if hmap == hmap_temp:
result.append(slow)
hmap_temp[s[slow]] -= 1
if hmap_temp[s[slow]] == 0:
del hmap_temp[s[slow]]
if fast < len(s):
if hmap_temp.get(s[fast]):
hmap_temp[s[fast]] += 1
else:
hmap_temp[s[fast]] = 1
slow += 1
fast += 1
return result | find-all-anagrams-in-a-string | Common solution for #438 and #567 | pratushah | 3 | 241 | find all anagrams in a string | 438 | 0.49 | Medium | 7,731 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2801531/Python-oror-Easy-oror-Sliding-Window-%2B-Dictionary-oror-O(N)-Solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
n1,n2=len(s),len(p)
d1=Counter(p)
d2=Counter(s[:n2-1])
ans=[]
j=0
for i in range(n2-1,n1):
d2[s[i]]+=1
if d1==d2:
ans.append(j)
d2[s[j]]-=1
if d2[s[j]]==0:
del d2[s[j]]
j+=1
return ans | find-all-anagrams-in-a-string | Python || Easy || Sliding Window + Dictionary || O(N) Solution | DareDevil_007 | 2 | 194 | find all anagrams in a string | 438 | 0.49 | Medium | 7,732 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2702896/Real-O(n%2Bm)-solution-independent-of-vocabulary-size | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
p_count = defaultdict(int)
for c in p:
p_count[c] += 1
res = []
m = len(p)
missing = set(p)
window = defaultdict(int)
def update_missing(c):
if c in missing and window[c] == p_count[c]:
missing.remove(c)
elif p_count[c] and window[c] != p_count[c]:
missing.add(c)
for i, c in enumerate(s):
window[c] += 1
update_missing(c)
if i >= m - 1:
out_idx = i - m + 1
if not missing:
res.append(out_idx)
window[s[out_idx]] -= 1
update_missing(s[out_idx])
return res | find-all-anagrams-in-a-string | Real O(n+m) solution independent of vocabulary size | tapka | 2 | 166 | find all anagrams in a string | 438 | 0.49 | Medium | 7,733 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738520/Find-All-Anagrams-in-a-String-or-Python-O(n)-Solution-or-Easy-To-Understand | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s): return []
pCount, sCount = {}, {}
for i in range(len(p)):
pCount[p[i]] = 1 + pCount.get(p[i], 0)
sCount[s[i]] = 1 + sCount.get(s[i], 0)
res = [0] if sCount == pCount else []
l = 0
for i in range(len(p), len(s)):
sCount[s[i]] = 1 + sCount.get(s[i], 0)
sCount[s[l]] -=1
if sCount[s[l]] == 0:
sCount.pop(s[l])
l+=1
if sCount == pCount: res.append(l)
return res | find-all-anagrams-in-a-string | Find All Anagrams in a String | Python O(n) Solution | Easy To Understand | pniraj657 | 2 | 268 | find all anagrams in a string | 438 | 0.49 | Medium | 7,734 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1678272/Python3-oror-Sliding-window-oror-Dictionary | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s):
return []
freq_p = {}
for char in p:
if char in freq_p:
freq_p[char] += 1
else:
freq_p[char] = 1
size = len(p)
#for the first size chars, find freq
freq = {}
for idx in range(size):
if s[idx] in freq:
freq[s[idx]] += 1
else:
freq[s[idx]] = 1
start = []
if freq == freq_p:
start.append(0)
for idx in range(size,len(s)):
elem1 = s[idx]
#add the current elem in dictionary
if elem1 in freq:
freq[elem1] += 1
else:
freq[elem1] = 1
#remove the s[idx-size] from dict
elem2 = s[idx-size]
if freq[elem2] > 1:
freq[elem2] -= 1
else:
freq.pop(elem2)
#check if two dictionaries are same or not
if freq == freq_p:
start.append(idx-size+1)
return start
#TC --> O(n) ; considering n is len(s)
#SC --> O(k) ; considering k is len(p) | find-all-anagrams-in-a-string | Python3 || Sliding window || Dictionary | s_m_d_29 | 2 | 201 | find all anagrams in a string | 438 | 0.49 | Medium | 7,735 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1531863/Sliding-window-approach-Python | class Solution:
def findAnagrams(self, s: str, pattern: str):
start = 0
dic_pattern = collections.Counter(pattern)
dic_s = {}
result = []
for end in range(len(s)):
if s[end] not in dic_s:
dic_s[s[end]] = 1
else:
dic_s[s[end]] += 1
if dic_s == dic_pattern:
result.append(start)
if (end - start +1) >= len(pattern):
if dic_s[s[start]] > 1:
dic_s[s[start]] -= 1
else:
del dic_s[s[start]]
start += 1
return result | find-all-anagrams-in-a-string | Sliding window approach - Python | algoFun | 2 | 200 | find all anagrams in a string | 438 | 0.49 | Medium | 7,736 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2345463/Python-efficient-solution | class Solution:
def countLetters(self, s: str) -> dict:
counts = {}
for char in s:
try:
counts[char] += 1
except KeyError:
counts[char] = 1
return counts
def isAnagram(self, sCounts: str, tCounts: str) -> bool:
for char in sCounts:
currentCount = sCounts[char]
try:
if tCounts[char] != currentCount:
return False
except KeyError:
if currentCount != 0:
return False
return True
def findAnagrams(self, s: str, p: str) -> List[int]:
anagramLength = len(p)
checkStrLength = len(s)
pCounts = self.countLetters(p)
anagrams = []
sCounts = None
for i in range(checkStrLength - anagramLength + 1):
if not sCounts:
sCounts = self.countLetters(s[i:i + anagramLength])
else:
sCounts[s[i - 1]] -= 1
try:
sCounts[s[i + anagramLength - 1]] += 1
except KeyError:
sCounts[s[i + anagramLength - 1]] = 1
if self.isAnagram(sCounts, pCounts):
anagrams.append(i)
return anagrams | find-all-anagrams-in-a-string | Python efficient solution | Woodie07 | 1 | 113 | find all anagrams in a string | 438 | 0.49 | Medium | 7,737 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2123786/Simple-Python-Solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
n = len(s)
m = len(p)
if n < m:
return []
window = {}
pmap = {}
for i in range(m):
if p[i] not in pmap:
pmap[p[i]] = 1
else:
pmap[p[i]] += 1
ans = []
# window initialization
for i in range(0, m):
if s[i] in window:
window[s[i]] += 1
else:
window[s[i]] = 1
if window == pmap:
ans.append(0)
for i in range(1, n-m+1):
# window updation by reducing frequency of prev window element if present in smap else deleting
# and adding/increasing frequency of next element (nxt)
prev = s[i-1]
if prev in window:
window[prev] -= 1
if window[prev] == 0:
del window[prev]
nxt = s[i+m-1]
if nxt in window:
window[nxt] += 1
else:
window[nxt] = 1
if window == pmap:
ans.append(i)
return ans | find-all-anagrams-in-a-string | π β
Simple Python Solution | reinkarnation | 1 | 179 | find all anagrams in a string | 438 | 0.49 | Medium | 7,738 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738936/Pyhton-oror-Easy-to-Understand-oror-Sliding-Window-and-Arrays-oror-99.43-faster | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
l1, l2 = len(s), len(p)
if l1 < l2:
return []
res = []
arr1, arr2 = [0] * 26, [0] * 26
for i in range(l2):
if i < l2 - 1:
arr1[ord(s[i]) - 97] += 1
arr2[ord(p[i]) - 97] += 1
for i in range(l1 - l2 + 1):
arr1[ord(s[i + l2 - 1]) - 97] += 1
if arr1 == arr2:
res.append(i)
arr1[ord(s[i]) - 97] -= 1
return res | find-all-anagrams-in-a-string | Pyhton || Easy to Understand || Sliding Window and Arrays || 99.43% faster | cherrysri1997 | 1 | 83 | find all anagrams in a string | 438 | 0.49 | Medium | 7,739 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738402/Detail-Explained-Solution-(python3-slidingwindow) | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
sl, pl = len(s), len(p)
ans = []
# according to the question, p has to be shorter than s
# or there will be no valid anagrams --> return []
if sl < pl:
return ans
# using sliding windows,
# left and right pointer both starts from the longer str s
l, r = 0, 0
# build a counter to check
# if the number of each letter in anagrams is same as p
count = collections.Counter(p)
# for sliding window, we need to keep the max length of the window not exceed the pl
# also, when right pointer moves out of the str s which means we've finished the traversal
# plus, left pointer must smaller than the right pointer to maintain our window
while r < sl and (0 <= r - l < pl):
# There would be three conditions:
# 1. expand the window --> right += 1
# 2. reduce the window --> left += 1
# 3. The window frames a valid anagram --> start over from next letter
# condition 1: the letter in s is one of the letter in p
if s[r] in p and count[s[r]] != 0:
# reduce the count in counter to record we've already find it
count[s[r]] -= 1
# expand the window to check next
# cbae --> cbae
# | | | |
r += 1
# if we've find all letters in p (all counts are reduced to 0)
if all(v == 0 for v in count.values()):
# record the start index (left pointer location)
ans.append(l)
# reduce the window --> move it to right with stride 1 to check next
# cbae --> cbae
# | | | |
count[s[l]] += 1
l += 1
# condition 2: the right pointer find a repeated letter
# reduce the window until make it not repeated
# abcb --> abcb -- > abcb
# | | | | | |
elif s[r] in p and count[s[r]] == 0:
# find the repeated letter
while l < r and s[l] != s[r]:
count[s[l]] += 1
l += 1
# move the left pointer to the letter next to it
# and remove the count record from our counter
count[s[l]] += 1
l += 1
# condition 2:
# cbaeb --> cbaeb
# | | | <-- both l and r are here
elif s[r] not in p:
r += 1
l = r
# initial our counter becuase we need to start over
count = collections.Counter(p)
return ans | find-all-anagrams-in-a-string | Detail Explained Solution (python3, slidingwindow) | codingGeniusPP | 1 | 34 | find all anagrams in a string | 438 | 0.49 | Medium | 7,740 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1722751/Python-Sliding-window-explained | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
res = list()
m = len(p)
p = Counter(p)
# start the window with the first
# m characters of s
window = Counter(s[:m])
# loop over s with len(p) to spare
# to be able to move the sliding window
for i in range(len(s)-m+1):
# once we're past the first few
# chars, we need to update/decrement the
# count of the first character in the
# window and add/increment the count of the
# next character in the window.
if i > 0:
window[s[i-1]] -= 1
window[s[i+m-1]] = window.get(s[i+m-1], 0) + 1
# every iteration, we'll check if the two
# dictionaries are equal, if yes, add i to res
if len(window - p) == 0:
res.append(i)
return res | find-all-anagrams-in-a-string | [Python] Sliding window explained | buccatini | 1 | 156 | find all anagrams in a string | 438 | 0.49 | Medium | 7,741 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1347407/Python-3-Simple-Sliding-Window-Solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
anagram_p = [0] * 26
anagram_curr = [0] * 26
output = []
for char in p:
anagram_p[ord(char)-97] += 1
for char in s[0:len(p)]:
anagram_curr[ord(char)-97] += 1
if anagram_curr == anagram_p:
output.append(0)
for i in range(1, len(s) - len(p) + 1):
anagram_curr[ord(s[i-1])-97] -= 1
anagram_curr[ord(s[i+len(p)-1])-97] += 1
if anagram_curr == anagram_p:
output.append(i)
return output | find-all-anagrams-in-a-string | Python 3 Simple Sliding Window Solution | zhanz1 | 1 | 136 | find all anagrams in a string | 438 | 0.49 | Medium | 7,742 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/761487/Python3%3A-Sliding-window-with-elastic-window-length | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if not p or len(p) > len(s):
return []
anagrams = []
len_s, len_p = len(s), len(p)
# distance to zeroize for each char in order to be the same as the pattern
counter = Counter(p)
# total number of the chars that not matched
diff = len(counter.keys())
l, r = 0, 0
# outer while loop is to increment r, to substract the distance for each char
while r < len_s:
counter[s[r]] -= 1
if counter[s[r]] == 0:
diff -= 1
# an anagram is found in s[l:r+1] whenever diff == 0
if diff == 0:
# the inner while loop if to increment l, pop the chars from the substring s[l:r+1]
# to add up the distance between the substring s[l:r+1] and teh pattern
while diff == 0 and l <= r:
counter[s[l]] += 1
if counter[s[l]] == 1:
diff += 1
l += 1
# we can only ensure an anagram is found only when the last popped char
# distructs the anagram with the pattern with the same exact length
if r - l == len_p - 2:
anagrams.append(l - 1)
r += 1
return anagrams | find-all-anagrams-in-a-string | Python3: Sliding window with elastic window length | alsvia | 1 | 109 | find all anagrams in a string | 438 | 0.49 | Medium | 7,743 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2846809/Python3-Solution-Counter%2BSliding-Window | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
counter_p = collections.Counter(p)
len_window = len(p)
res = []
for i in range(len(s)-len_window+1):
counter_s = collections.Counter(s[i:i+len_window])
if counter_s == counter_p:
res.append(i)
return res | find-all-anagrams-in-a-string | Python3 Solution Counter+Sliding Window | osman74 | 0 | 1 | find all anagrams in a string | 438 | 0.49 | Medium | 7,744 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2841942/BEATS-99-SUBMISSIONS-oror-FASTEST-AND-EASIEST-oror-TWO-POINTER-APPROACH | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p)>len(s):
return []
pcount,scount={},{}
for i in range(len(p)):
pcount[p[i]]=1 + pcount.get(p[i],0)
scount[s[i]]=1 + scount.get(s[i],0)
if pcount==scount :
res=[0]
else :
res=[]
l=0
for r in range(len(p),len(s)):
scount[s[r]]=1+scount.get(s[r],0)
scount[s[l]]-=1
if scount[s[l]]==0:
scount.pop(s[l])
l +=1
if scount==pcount:
res.append(l)
return res | find-all-anagrams-in-a-string | BEATS 99% SUBMISSIONS || FASTEST AND EASIEST || TWO POINTER APPROACH | Pritz10 | 0 | 2 | find all anagrams in a string | 438 | 0.49 | Medium | 7,745 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2838494/Hashtable-%2B-Sliding-Window | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
def _build_dict(w: str) -> Dict[str, int]:
"""Builds a dictionary."""
res: Dict[str, int] = {}
for w_ in w:
if w_ in res:
res[w_] += 1
else:
res[w_] = 1
return res
def _update_dict(t1: str, t2: str, mapping: Dict[str, int]) -> None:
"""Updates the dictionary in place."""
if mapping[t1] == 1:
del mapping[t1]
else:
mapping[t1] -= 1
if t2 in mapping:
mapping[t2] += 1
else:
mapping[t2] = 1
p_dict = _build_dict(p)
res = []
for i in range(len(s) - len(p) + 1):
if i == 0:
s_dict = _build_dict(s[:len(p)])
else:
_update_dict(s[i-1], s[i+len(p)-1], s_dict)
if s_dict == p_dict:
res.append(i)
return res | find-all-anagrams-in-a-string | Hashtable + Sliding Window | fengdi2020 | 0 | 2 | find all anagrams in a string | 438 | 0.49 | Medium | 7,746 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2823266/Python-Easy-Understand-Solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
len_s = len(s)
len_p = len(p)
original = "".join(sorted(p))
anagram_index = []
for i in range(len_s - len_p + 1):
word = ''.join(sorted(s[i: i+len_p]))
if word == original:
anagram_index.append(i)
return anagram_index | find-all-anagrams-in-a-string | Python Easy Understand Solution | namashin | 0 | 3 | find all anagrams in a string | 438 | 0.49 | Medium | 7,747 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2815062/Ultra-Streamlined-Sliding-Window-Python | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
res, matches, f = [], 0, Counter(p)
for i, old, new in ((j + 1, (s[j] if j >= 0 else None), c) for j, c in enumerate(s, -len(p))):
if old != new:
if old in f:
f[old] += 1
matches -= f[old] >= 1
if new in f:
f[new] -= 1
matches += f[new] >= 0
if matches == len(p):
res += [i]
return res | find-all-anagrams-in-a-string | Ultra-Streamlined Sliding Window [Python] | constantstranger | 0 | 3 | find all anagrams in a string | 438 | 0.49 | Medium | 7,748 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2815062/Ultra-Streamlined-Sliding-Window-Python | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
res, matches, f = [], 0, defaultdict(int)
for c in p:
f[c] += 1
for i in range(len(p)):
if s[i] in f:
f[s[i]] -= 1
if f[s[i]] >= 0:
matches += 1
if matches == len(p):
res += [0]
for j, old in enumerate(s, len(p)):
if j == len(s):
break
new = s[j]
if old != new:
if old in f:
f[old] += 1
if f[old] >= 1:
matches -= 1
if new in f:
f[new] -= 1
if f[new] >= 0:
matches += 1
if matches == len(p):
res += [j - len(p) + 1]
return res | find-all-anagrams-in-a-string | Ultra-Streamlined Sliding Window [Python] | constantstranger | 0 | 3 | find all anagrams in a string | 438 | 0.49 | Medium | 7,749 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2784700/Easy-Python-solution-with-use-of-two-hashmapsSimilar-to-Problem-no.567 | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
dic1={}
for i in p:
if i in dic1:
dic1[i]+=1
else:
dic1[i]=1
i=0
j=len(p)-1
l=[]
dic2=Counter(s[i:j])
while(j<len(s)):
dic2[s[j]]+=1
if(dic1==dic2):
l.append(i)
dic2[s[i]]-=1
if(dic2[s[i]])==0:
del dic2[s[i]]
i+=1
j+=1
return l | find-all-anagrams-in-a-string | Easy Python solution with use of two hashmaps[Similar to Problem no.567] | liontech_123 | 0 | 6 | find all anagrams in a string | 438 | 0.49 | Medium | 7,750 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2784402/Easy-to-understand-solution-using-a-Sliding-Window-and-Frequency-Lists-with-Explanation! | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# Time complexity: O(s)
# Space complexity: O(1)
res = []
# sanity check
if len(p) > len(s):
return res
# init frequency lists for characters in alphabet
# we have found an anagram when the frequency lists are equal
window, original = [0] * 26, [0] * 26
i = 0
# run over window
while i < len(p):
# we know that all characters in p and s are lower case and english letters
# ord('...') - ord('a') computes the position in the alphabet
original[ord(p[i]) - ord('a')] += 1
window[ord(s[i]) - ord('a')] += 1
i += 1
# add start position to output when initial window is anagram
if window == original:
res.append(i - len(p))
# slide window over the remaining part of s
while i < len(s):
# remove old start from window
window[ord(s[i-len(p)]) - ord('a')] -= 1
# add new end of window
window[ord(s[i]) - ord('a')] += 1
# check anagram
if window == original:
res.append(i - len(p) + 1)
i += 1
return res | find-all-anagrams-in-a-string | Easy to understand solution using a Sliding Window and Frequency Lists with Explanation! | FuriFuo | 0 | 4 | find all anagrams in a string | 438 | 0.49 | Medium | 7,751 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2769520/My-python3-solution-Sliding-Window | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
res, shift, pCounter = [], len(p) - 1, Counter(p)
for i in range(len(s)):
pCounter[s[i]] -= 1
if i < shift:
continue
if set(pCounter.values()) == {0}:
res.append(i - shift)
pCounter[s[i - shift]] += 1
return res | find-all-anagrams-in-a-string | My python3 solution - Sliding Window | toshiwu006 | 0 | 4 | find all anagrams in a string | 438 | 0.49 | Medium | 7,752 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2755743/Python3-or-defaultdict-solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
ans = []
len_p = len(p)
len_s = len(s)
if len_p > len_s:
return ans
dict_s = collections.defaultdict(int)
dict_p = collections.defaultdict(int)
for i in range(len_p):
dict_p[p[i]] += 1
dict_s[s[i]] += 1
for i in range(len_s-len_p):
if dict_s == dict_p:
ans.append(i)
dict_s[s[i]] -= 1
#delete s[i] Otherwise, it will be stored in the dictionary in the form of 0
if dict_s[s[i]] == 0:
del dict_s[s[i]]
dict_s[s[i+len_p]] += 1
if dict_s == dict_p:
ans.append(len_s-len_p)
return ans | find-all-anagrams-in-a-string | Python3 | defaultdict solution | puppydog91111 | 0 | 3 | find all anagrams in a string | 438 | 0.49 | Medium | 7,753 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2754863/Sliding-Window-%2B-Hash-Table-oror-Easy-To-Understand | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s):
return []
s_count = {}
p_count = {}
for i in range(len(p)):
s_count[s[i]] = 1 + s_count.get(s[i],0)
p_count[p[i]] = 1 + p_count.get(p[i],0)
res = [0] if s_count == p_count else []
l = 0
for r in range(len(p),len(s)):
s_count[s[r]] = 1 + s_count.get(s[r],0)
s_count[s[l]] -= 1
if s_count[s[l]]==0:
s_count.pop(s[l])
l+=1
if s_count==p_count:
res.append(l)
return res | find-all-anagrams-in-a-string | Sliding Window + Hash Table || Easy To Understand | subbhashitmukherjee | 0 | 6 | find all anagrams in a string | 438 | 0.49 | Medium | 7,754 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2710359/python-easy-solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p)>len(s):
return []
scount={}
pcount={}
anagram_index = []
for i in range(len(p)):
pcount[p[i]]=1+pcount.get(p[i],0)
scount[s[i]]=1+scount.get(s[i],0)
#print(scount)
#print(pcount)
anagram_index=[0] if pcount==scount else []
left = 0
for right in range(len(p), len(s)):
scount[s[right]]=1+scount.get(s[right], 0)
scount[s[left]]-=1
if scount[s[left]]==0:
scount.pop(s[left])
left+=1
if scount==pcount:
anagram_index.append(left)
return anagram_index | find-all-anagrams-in-a-string | python easy solution | tush18 | 0 | 10 | find all anagrams in a string | 438 | 0.49 | Medium | 7,755 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2702877/Python3-or-Sliding-Window-Hashmap-or-Beats-96-w-explanation | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# edge case
if len(p) > len(s): return []
s_count, p_count = {}, {} # hashmap used to keep track of count of chars in current window in s (hence deciding if the phrase is an anagram of p)
anagram_index = [] # stores indices of result
# window for first p elements
for i in range(len(p)):
p_count[p[i]] = 1 + p_count.get(p[i], 0) # .get() checks if the char is already in dict and adds 1 to that count, otherwise sets it to 0
s_count[s[i]] = 1 + s_count.get(s[i], 0)
anagram_index = [0] if p_count == s_count else [] # appends first index (0) if first window is a anagram of p
# sliding window for rest of s, starting from len(p)
left = 0
for right in range(len(p), len(s)):
# window begins after first len(p) and is maintained through left and right pointer
s_count[s[right]] = 1 + s_count.get(s[right], 0)
# ensuring that elem outside the window is not counted and the window is maintained
s_count[s[left]] -= 1
if s_count[s[left]] == 0: # if count of a character is 0, pop it to prevent errors when comparing both dicts
s_count.pop(s[left])
left += 1 # incrementing left pointer to maintain window of len(p)
# checking if elems in window are anagrams by checking their count
if s_count == p_count:
anagram_index.append(left)
return anagram_index | find-all-anagrams-in-a-string | Python3 | Sliding Window, Hashmap | Beats 96% w/ explanation | manasakal | 0 | 7 | find all anagrams in a string | 438 | 0.49 | Medium | 7,756 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2697237/Python-solution | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
p_map = [0] * 26
window = [0] * 26
length = len(p)
ans = []
if length > len(s):
return
for i in range(length):
p_map[ord(p[i]) - ord('a')] += 1
for i in range(length):
window[ord(s[i]) - ord('a')] += 1
if window == p_map:
ans.append(0)
for i in range(length, len(s)):
window[ord(s[i]) - ord('a')] += 1
window[ord(s[i - length]) - ord('a')] -= 1
if window == p_map:
ans.append(i - length + 1)
return ans | find-all-anagrams-in-a-string | Python solution | maomao1010 | 0 | 8 | find all anagrams in a string | 438 | 0.49 | Medium | 7,757 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2663155/Happy-to-share-my-python-solution-oror-NO-EXPLANATION-oror | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
ind = []
p_count = collections.Counter(p)
s_count = collections.Counter(s[:len(p)])
i = 0
while i<=len(s)-len(p):
if s_count==p_count:
ind.append(i)
if s_count[s[i]]>0:
s_count[s[i]] -= 1
else:
del s_count[s[i]]
if i<len(s)-len(p):
s_count[s[i+len(p)]] += 1
i += 1
return ind | find-all-anagrams-in-a-string | Happy to share my python solution π || NO EXPLANATION || | daminrisho | 0 | 9 | find all anagrams in a string | 438 | 0.49 | Medium | 7,758 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2625425/python-or-sliding-window-or-hash-table | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
left, right, valid, s_length, p_length = 0, 0, 0, len(s), len(p)
window, counter, result = defaultdict(lambda: 0), Counter(p), []
while right < s_length:
char = s[right]
right += 1
if counter[char]:
window[char] += 1
if window[char] <= counter[char]:
valid += 1
while valid == p_length:
if right - left == p_length:
result.append(left)
deleted = s[left]
left += 1
if counter[deleted]:
if counter[deleted] == window[deleted]:
valid -= 1
window[deleted] -= 1
return result | find-all-anagrams-in-a-string | python | sliding window | hash table | MichelleZou | 0 | 38 | find all anagrams in a string | 438 | 0.49 | Medium | 7,759 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2621960/Python3-Faster-than-99.12 | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
d = defaultdict(lambda:0)
for i in p:
d[i] += 1
ans = []
slen, plen = len(s), len(p)
start, farthest = 0, plen
while farthest<=slen:
i = start
anagrams = d.copy()
while i<farthest:
if s[i] not in anagrams:
start = i+1
break
if anagrams[s[i]] == 0:
start += 1
break
anagrams[s[i]] -= 1
i += 1
else:
ans.append(start)
while farthest<slen and s[start] == s[farthest]:
ans.append(start+1)
start += 1
farthest += 1
start += 1
farthest = start + plen
return ans | find-all-anagrams-in-a-string | Python3 Faster than 99.12%β
| Tensor08 | 0 | 28 | find all anagrams in a string | 438 | 0.49 | Medium | 7,760 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2579455/Faster-than-98-and-imo-easier-to-follow-than-others-I've-seen-here | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# dual pointers? fast and trailing
# increment fast whilst youre killing the dictionary.
f, tr = 0, 0
res = []
d = {}
for c in p:
if c not in d:
d[c] = 0
d[c] += 1
missing = len(p)
while f < len(s):
if s[f] in d:
if d[s[f]] > 0: # all good
missing -= 1
d[s[f]] -= 1
if missing == 0: # found an anagram!
res += [tr]
d[s[tr]] += 1
tr += 1
missing = 1
else: # bad case A: not looking for this letter anymore, inc trailing
while s[tr] != s[f]:
d[s[tr]] += 1
tr += 1
missing += 1
tr += 1
else: # bad case B: letter not in anagram, skip to next char and reset
while tr < f + 1:
if s[tr] in d:
d[s[tr]] += 1
tr += 1
missing = len(p)
f += 1
return res | find-all-anagrams-in-a-string | Faster than 98% and imo easier to follow than others I've seen here | gabrielpetrov99 | 0 | 93 | find all anagrams in a string | 438 | 0.49 | Medium | 7,761 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2539068/Python3-oror-Sliding-Window-oror-easy-to-understand | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# lenght of window
k = len(p)
n = len(s)
pcounter = Counter(p)
res = []
c =len(pcounter)
i=j=0
while j<n:
#decrement the count of the element if it is present in the counter
if s[j] in pcounter :
pcounter[s[j]] -=1
# Decrement the counter when we have taken all the occurance of a character
if not pcounter[s[j]]:
c-=1
# when we reach window size
if j-i+1 ==k:
# when we have taken all the element their qantity becomes 0
if c == 0:
res.append(i)
#remove the calculation which was done for beginining of the window
if s[i] in pcounter:
pcounter[s[i]] +=1
if pcounter[s[i]] ==1:
c+=1
# slide the window
i+=1
j+=1
return res | find-all-anagrams-in-a-string | Python3 || Sliding Window || easy to understand | NitishKumarVerma | 0 | 30 | find all anagrams in a string | 438 | 0.49 | Medium | 7,762 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2535326/Python-oror-Sliding-Window-Very-intuitive | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
a = [0] * 26
for letter in p:
a[ord(letter)-97] += 1
res = []
ls = len(s)
lp = len(p)
b = [0] * 26
currLength = 0
for i in range(ls):
if currLength < lp:
b[ord(s[i])-97] += 1
currLength += 1
else:
b[ord(s[i-lp])-97] -= 1
b[ord(s[i])-97] += 1
if currLength == lp and a == b:
res.append(i-lp+1)
return res | find-all-anagrams-in-a-string | Python || Sliding Window, Very intuitive | IamCookie | 0 | 54 | find all anagrams in a string | 438 | 0.49 | Medium | 7,763 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2447356/Python3-oror-Sliding-Window-and-Hash-Maporor-Simple-and-fast | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s): return []
pCount, sCount = {}, {}
for i in range(len(p)):
pCount[p[i]] = 1 + pCount.get(p[i], 0)
sCount[s[i]] = 1 + sCount.get(s[i], 0)
res = [0] if sCount == pCount else []
l = 0
for r in range(len(p), len(s)):
sCount[s[r]] = 1 + sCount.get(s[r], 0)
sCount[s[l]] -= 1
if sCount[s[l]] == 0:
sCount.pop(s[l])
l += 1
if sCount == pCount:
res.append(l)
return res | find-all-anagrams-in-a-string | Python3 || Sliding Window and Hash Map|| Simple and fast | WhiteBeardPirate | 0 | 35 | find all anagrams in a string | 438 | 0.49 | Medium | 7,764 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2445729/Sliding-Window-with-Dictionary-oror-With-Comments-oror-Simple-to-Understand | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
window = len(p)
p_dict = {}
cur_dict = {}
# Get original dictionary of p string
for l in p:
p_dict[l] = p_dict.get(l, 0) + 1
res = []
for i in range(len(s) - window + 1):
# Initialise the first dictionary window of s string
if i == 0:
for j in range(window):
cur_dict[s[j]] = cur_dict.get(s[j], 0) + 1
else:
# Delete character on the left
cur_dict[s[i-1]] -= 1
if cur_dict[s[i-1]] == 0:
del cur_dict[s[i-1]]
# Add character on the right
cur_dict[s[i+window-1]] = cur_dict.get(s[i+window-1], 0) + 1
# If both current and original dictionary matches, append index to result
if cur_dict == p_dict:
res.append(i)
return res | find-all-anagrams-in-a-string | Sliding Window with Dictionary || With Comments || Simple to Understand | wcnd27 | 0 | 46 | find all anagrams in a string | 438 | 0.49 | Medium | 7,765 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2418999/Two-pointers(Sliding-window)-python3-solution | class Solution:
# O(n^2) time,
# O(n) space,
# Approach: two pointers, sliding window, hashmap
def findAnagrams(self, s: str, p: str) -> List[int]:
def areEqual(d1, d2) -> bool:
for key, value in d1.items():
if key not in d2.keys() or d2[key] != value: return False
return True
window = {}
p_set = Counter(p)
n = len(p)
m = len(s)
if n > m:
return []
l, r = 0, n-1
result = []
for i in range(n-1):
window[s[i]] = window.get(s[i], 0) + 1
while r < m:
window[s[r]] = window.get(s[r], 0) + 1
if areEqual(p_set, window):
result.append(l)
window[s[l]] = window.get(s[l], 0) - 1
l +=1
r +=1
return result | find-all-anagrams-in-a-string | Two pointers(Sliding window) python3 solution | destifo | 0 | 12 | find all anagrams in a string | 438 | 0.49 | Medium | 7,766 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2318451/Python-3-or-Sliding-Window-%2B-Hashmap-O(n%2Bm)-runtime | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
#Sliding window technique!
#Keep expanding sliding window until its size == len(p)
#Check if the characters you have accumulated have exact frequency count as that of p!
#If so, add Left index to answer array, shrink, and continue expansion until right pointer goes out of bounds!
#If I let m == len(s)
#Time-Complexity: O(n + m)
#Space-Complexity: O(n + n), since size of current sliding window can be at most n -> O(n)
R, L = 0, 0
ans = []
n = len(p)
comparison = {}
current_chars = {}
length = 0
for i in range(n):
if(p[i] not in comparison):
comparison[p[i]] = 1
else:
comparison[p[i]] += 1
while R < len(s):
#process right element!
if(s[R] not in current_chars):
current_chars[s[R]] = 1
else:
current_chars[s[R]] += 1
length += 1
#stopping condition: size == len(p)
while length == n:
if(current_chars == comparison):
ans.append(L)
#process left element!
if(current_chars[s[L]] == 1):
current_chars.pop(s[L])
else:
current_chars[s[L]] -= 1
L += 1
length -= 1
R += 1
return ans | find-all-anagrams-in-a-string | Python 3 | Sliding Window + Hashmap O(n+m) runtime | JOON1234 | 0 | 22 | find all anagrams in a string | 438 | 0.49 | Medium | 7,767 |
https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/2307180/Python-Sliding-Window | class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
p_dic = {}
s_dic={}
answer=[]
for i in p:
if i not in p_dic:
p_dic[i]=0
p_dic[i]+=1
window_start = 0
p_length = sum(p_dic.values())
for window_end in range(len(s)):
right_char=s[window_end]
if right_char not in s_dic:
s_dic[right_char]=0
s_dic[right_char]+=1
s_length = sum(s_dic.values())
if p_dic == s_dic:
answer.append(window_start)
if s_length==p_length:
left_char = s[window_start]
s_dic[left_char]-=1
if s_dic[left_char]==0:
del s_dic[left_char]
window_start+=1
return answer | find-all-anagrams-in-a-string | Python Sliding Window | jashan1 | 0 | 23 | find all anagrams in a string | 438 | 0.49 | Medium | 7,768 |
https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/discuss/1608540/Python3-traverse-denary-trie | class Solution:
def findKthNumber(self, n: int, k: int) -> int:
def fn(x):
"""Return node counts in denary trie."""
ans, diff = 0, 1
while x <= n:
ans += min(n - x + 1, diff)
x *= 10
diff *= 10
return ans
x = 1
while k > 1:
cnt = fn(x)
if k > cnt: k -= cnt; x += 1
else: k -= 1; x *= 10
return x | k-th-smallest-in-lexicographical-order | [Python3] traverse denary trie | ye15 | 3 | 435 | k th smallest in lexicographical order | 440 | 0.308 | Hard | 7,769 |
https://leetcode.com/problems/arranging-coins/discuss/2801813/Python-Simple-Binary-Search | class Solution:
def arrangeCoins(self, n: int) -> int:
first = 1
last = n
if n==1:
return 1
while first <= last:
mid = (first+last)//2
if mid*(mid+1) == 2*n:
return mid
elif mid*(mid+1) > 2*n:
last = mid-1
else:
first = mid+1
return last | arranging-coins | Python Simple Binary Search | BhavyaBusireddy | 2 | 69 | arranging coins | 441 | 0.462 | Easy | 7,770 |
https://leetcode.com/problems/arranging-coins/discuss/2325796/Python-Simple-Python-Solution | class Solution:
def arrangeCoins(self, n: int) -> int:
result = 0
stairs_number = 1
while n > 0:
n = n - stairs_number
stairs_number = stairs_number + 1
if n >= 0:
result = result + 1
return result | arranging-coins | [ Python ] β
β
Simple Python Solution π₯³βπ | ASHOK_KUMAR_MEGHVANSHI | 2 | 94 | arranging coins | 441 | 0.462 | Easy | 7,771 |
https://leetcode.com/problems/arranging-coins/discuss/1561360/Recursive-Python-Solution | class Solution:
def arrangeCoins(self, n: int, row=1) -> int:
if n < row:
return 0
return 1 + self.arrangeCoins(n - row, row + 1) | arranging-coins | Recursive Python Solution | ErikRodriguez-webdev | 2 | 95 | arranging coins | 441 | 0.462 | Easy | 7,772 |
https://leetcode.com/problems/arranging-coins/discuss/473189/1-Line-Python-3-Solution-AP-series-and-Quadratic-Equation-concept | class Solution:
def arrangeCoins(self, n: int) -> int:
return int((-1 + (1+(4*1*2*n))**0.5)//2) | arranging-coins | 1 Line Python 3 Solution [AP series & Quadratic Equation concept] | Mayuraksha | 2 | 214 | arranging coins | 441 | 0.462 | Easy | 7,773 |
https://leetcode.com/problems/arranging-coins/discuss/2097328/Python3-from-O(n)-to-O(1)-in-runtime-48ms-69.84 | class Solution:
def arrangeCoins(self, n: int) -> int:
return self.optimalOne(n)
return self.bruteForce(n)
# O(1) || O(1)
# runtime: 48ms 69.84%
# memory: 13.9mb 56.52%
# 1 + 2 + 3 + 4 ... n = n (n + 1) / 2 is a series
# where n is equal to the last term of our series and also represents the number of terms.
# so all we need is just solve the equation n = i*(i + 1)/2
def optimalOne(self, coins):
return int(((0.25 + 2 * coins) ** 0.5) - 1/2)
# O(n) || O(1)
# Runtime: 1724ms 8.29%; memory: 13.8mb 96.45%
def bruteForce(self, coins):
if not coins:
return coins
if coins == 1:return coins
total = 0
k = 1
while coins >= 0:
coins -= k
k += 1
total += 1
return total - 1 | arranging-coins | Python3 from O(n) to O(1) in runtime 48ms 69.84% | arshergon | 1 | 58 | arranging coins | 441 | 0.462 | Easy | 7,774 |
https://leetcode.com/problems/arranging-coins/discuss/1982248/Python-easy-to-read-and-understand | class Solution:
def arrangeCoins(self, n: int) -> int:
temp, total = 1, 1
rows = 1
while total <= n:
temp = temp+1
total += temp
if total > n:
break
rows += 1
return rows | arranging-coins | Python easy to read and understand | sanial2001 | 1 | 54 | arranging coins | 441 | 0.462 | Easy | 7,775 |
https://leetcode.com/problems/arranging-coins/discuss/1568923/Python-O(1)-time-faster-than-100 | class Solution:
def arrangeCoins(self, n: int) -> int:
x = math.floor(math.sqrt(n * 2))
return x if x * (x + 1) <= n * 2 else x - 1 | arranging-coins | Python O(1) time faster than 100% | dereky4 | 1 | 168 | arranging coins | 441 | 0.462 | Easy | 7,776 |
https://leetcode.com/problems/arranging-coins/discuss/373928/Python-1-line-99.57-math-with-total-explanation | class Solution:
def arrangeCoins(self, n: int) -> int:
return int((2*n + 1/4)**(1/2) - 1/2) | arranging-coins | Python 1-line 99.57% math with total explanation | DenysCoder | 1 | 262 | arranging coins | 441 | 0.462 | Easy | 7,777 |
https://leetcode.com/problems/arranging-coins/discuss/2829494/Arranging-Coin-or-Python | class Solution:
def arrangeCoins(self, n: int) -> int:
first = 1
last = n
if n == 1:
return 1
while first <= last:
mid = (first+last)//2
if mid*(mid+1) == 2*n:
return mid
elif mid*(mid+1) > 2*n:
last = mid-1
else:
first = mid+1
return last | arranging-coins | Arranging Coin | Python | jashii96 | 0 | 2 | arranging coins | 441 | 0.462 | Easy | 7,778 |
https://leetcode.com/problems/arranging-coins/discuss/2825684/Binary-Search-Approach-or-O(logn)-time-or-O(1)-space | class Solution:
def arrangeCoins(self, n: int) -> int:
left = 1
right = n
while left <= right:
mid = (left + right)//2
if (mid*(mid+1))//2 > n:
right = mid - 1
else:
left = mid + 1
return right | arranging-coins | Binary Search Approach | O(logn) time | O(1) space | advanced-bencoding | 0 | 8 | arranging coins | 441 | 0.462 | Easy | 7,779 |
https://leetcode.com/problems/arranging-coins/discuss/2793578/Brute-Force-Outline-and-Then-Mathematics-Explained-with-straightforward-steps. | class Solution:
def arrangeCoins(self, n: int) -> int:
'''
# Brute Force Method
coins_in_row = 1
coins_remaining = n
num_rows_built = 0
while coins_remaining > 0 :
coins_remaining -= coins_in_row
if coins_remaining >= 0 :
num_rows_built += 1
coins_in_row += 1
return num_rows_built
'''
# the last row can use at most n/2
# so we can use that as a start and work backward?
# this is still brute force but might be cheaper.
# summation part looks like the Gaussian Sum famous problem
# Upon check, it is! This means we have (levels(levels+1))/2 = n
# we are also integer bound, so we'll need to round down at the end
# start by rewriting this in the appropriate form.
# levels^2 + levels - 2N = 0 -> quadratic form
# - 1 +- sqrt(1 - 4*1*-2N) / 2 -> set to quadratic formula
# -1 +- sqrt(8N + 1) / 2 -> apply negatives
# -1 +- 2sqrt(2N + 1/4) / 2 -> factor out 4 from 8N and 1
# -1/2 + (sqrt(2N+1/4)) -> reduce to form where we will be ending up with a positive number
number_of_stairs = 2*n
number_of_stairs += 0.25
number_of_stairs = math.sqrt(number_of_stairs)
number_of_stairs -= 0.5
return int(number_of_stairs) | arranging-coins | Brute Force Outline and Then Mathematics Explained with straightforward steps. | laichbr | 0 | 6 | arranging coins | 441 | 0.462 | Easy | 7,780 |
https://leetcode.com/problems/arranging-coins/discuss/2733042/Python-Solution-oror-Quadratic-Equation-Math-oror-TC-O(1)-oror-SC-O(1)-oror-Faster-than-97.55 | class Solution:
def arrangeCoins(self, n: int) -> int:
c=-2*n
ans1=int((-1+math.sqrt(1-4*c))//2)
ans2=int((-1-math.sqrt(1-4*c))//2)
return ans1 if ans1>0 else ans2 | arranging-coins | Python Solution || Quadratic Equation Math || TC O(1) || SC O(1) || Faster than 97.55% | RA2011050010037 | 0 | 4 | arranging coins | 441 | 0.462 | Easy | 7,781 |
https://leetcode.com/problems/arranging-coins/discuss/2729260/python-binary-search-solution | class Solution:
def arrangeCoins(self, n: int) -> int:
right = n
left = 0
while right >= left:
mid = (right+left)//2
guess = (mid * mid + mid)//2
if guess == n:
return mid
elif guess < n:
left = mid + 1
else:
right = mid - 1
return right | arranging-coins | python binary search solution | muge_zhang | 0 | 3 | arranging coins | 441 | 0.462 | Easy | 7,782 |
https://leetcode.com/problems/arranging-coins/discuss/2674614/Python-O(1)-O(1) | class Solution:
def arrangeCoins(self, n: int) -> int:
return int(math.floor((-1 + (4 * (2 * (n + 1))) ** 0.5) / 2)) | arranging-coins | Python - O(1), O(1) | Teecha13 | 0 | 5 | arranging coins | 441 | 0.462 | Easy | 7,783 |
https://leetcode.com/problems/arranging-coins/discuss/2546842/Python3-or-Utilizing-Arithmetic-Series-Math-Logic-%2B-Binary-Search%3A-TCO(logn)-S.C-O(1) | class Solution:
#Time-Complexity: O(log(n))
#Space-Complexity: O(1)
def arrangeCoins(self, n: int) -> int:
#Approach: First, notice that the minimum number of coins required
#to form each and every row is a number that is sum of
#arithmetic series(1+ 2+ 3 +... +n = (n * (n+1) / 2)
#Search Space: low = 1 row high = n
#We can perform binary search on search space and constantly update
#the best maximal number of complete rows we can form!
l, h = 1, n
ans = None
while l <= h:
mid_row = (l + h) // 2
#find the required number of coins to form mid_row # of rows!
req_coins = ((mid_row) * (mid_row + 1)) / 2
#if we have enough coins, then we can form the mid_row # of rows!
#so update answer!
#reduce search space to right to possibly search for higher
#number of completed rows!
if(req_coins <= n):
ans = mid_row
l = mid_row + 1
continue
#if we don't have enough coins, mid_row # rows can't be formed!
#look for lower number of rows to form!
else:
h = mid_row - 1
continue
#once binary search ends, our ans variable will have the maximal
#complete rows we can form input number of coins n!
return ans | arranging-coins | Python3 | Utilizing Arithmetic Series Math Logic + Binary Search: TC=O(logn) S.C = O(1) | JOON1234 | 0 | 29 | arranging coins | 441 | 0.462 | Easy | 7,784 |
https://leetcode.com/problems/arranging-coins/discuss/2435939/C%2B%2BPython-Best-Optimized-Approach-with-Binary-Search | class Solution:
def arrangeCoins(self, n: int) -> int:
s = 1
e = n
while s<=e:
mid = s + (e-s)//2
temp = int(mid*(mid+1)/2)
if temp == n:
return mid
if temp < n:
s = mid + 1
else:
e = mid - 1
return e | arranging-coins | C++/Python Best Optimized Approach with Binary Search | arpit3043 | 0 | 24 | arranging coins | 441 | 0.462 | Easy | 7,785 |
https://leetcode.com/problems/arranging-coins/discuss/2370871/Python-Simple-Faster-Solutions-Binary-Search-and-Formula-oror-Documented | class Solution:
def arrangeCoins(self, n: int) -> int:
low, high = 0, n
# Repeat until the pointers low and high meet each other
while low <= high:
mid = (low + high) // 2 # middle point - pivot
if (mid * (mid+1)) >> 1 <= n:
low = mid + 1 # check better value on the right side
else:
high = mid - 1 # try finding on the left side
return high | arranging-coins | [Python] Simple Faster Solutions - Binary Search and Formula || Documented | Buntynara | 0 | 16 | arranging coins | 441 | 0.462 | Easy | 7,786 |
https://leetcode.com/problems/arranging-coins/discuss/2369075/Python-Basic-Maths-Intuitive | class Solution:
def arrangeCoins(self, n: int) -> int:
for i in range(1,2**31):
val=i*(i+1)//2
if val>n:
a=i
break
elif val==n:
return i
return a-1 | arranging-coins | [Python] Basic Maths Intuitive | pheraram | 0 | 53 | arranging coins | 441 | 0.462 | Easy | 7,787 |
https://leetcode.com/problems/arranging-coins/discuss/2339621/easy-python-code-or-O(log-n)-or-binary-search | class Solution:
def sumofn(self,n):
return (n*(n+1))/2
def arrangeCoins(self, n: int) -> int:
l,r = 0,n
while(l<=r and l<n and r>=0):
m = (l+r)//2
m1 = self.sumofn(m)
if m1 > n:
r = m-1
elif m1 < n:
l = m+1
else:
return m
if (m+1) <= n and self.sumofn(m+1) <= n:
return m+1
elif self.sumofn(m) > n:
return m-1
else:
return m | arranging-coins | easy python code | O(log n) | binary search | dakash682 | 0 | 63 | arranging coins | 441 | 0.462 | Easy | 7,788 |
https://leetcode.com/problems/arranging-coins/discuss/2329916/Arranging-Coins | class Solution:
def arrangeCoins(self, n: int) -> int:
x = n
count=0
for i in range(1,n+1):
if x >=i:
x=x-i
count+=1
else:
break
return count | arranging-coins | Arranging Coins | dhananjayaduttmishra | 0 | 20 | arranging coins | 441 | 0.462 | Easy | 7,789 |
https://leetcode.com/problems/arranging-coins/discuss/2329916/Arranging-Coins | class Solution:
def arrangeCoins(self, n: int) -> int:
l = 0
r = n
while l <=r :
m = (l+r)//2
curr = m*(m+1)//2
if curr==n:
return m
if n<curr:
r = m-1
else:
l=m+1
return r | arranging-coins | Arranging Coins | dhananjayaduttmishra | 0 | 20 | arranging coins | 441 | 0.462 | Easy | 7,790 |
https://leetcode.com/problems/arranging-coins/discuss/2170224/Python-simple-solution | class Solution:
def arrangeCoins(self, n: int) -> int:
ans = 0
for i in range(1,n+1):
n -= i
if n >= 0:
ans += 1
else:
break
return ans | arranging-coins | Python simple solution | StikS32 | 0 | 42 | arranging coins | 441 | 0.462 | Easy | 7,791 |
https://leetcode.com/problems/arranging-coins/discuss/2102773/Python-or-Simple-solution | class Solution:
def arrangeCoins(self, n: int) -> int:
levels = 0
while n > levels:
levels += 1
n -= levels
return levels | arranging-coins | Python | Simple solution | rahulsh31 | 0 | 74 | arranging coins | 441 | 0.462 | Easy | 7,792 |
https://leetcode.com/problems/arranging-coins/discuss/2099541/Python-Easy-solutions-with-complexities | class Solution:
def arrangeCoins(self, n: int) -> int:
stairs = []
temp = n
i=1
totalCoins = 0
while (n>=0):
stairs.append(i)
n = n-i
totalCoins =totalCoins + i
if totalCoins > temp:
return i-1
i = i+1
# time O(N)
# space O(N) | arranging-coins | [Python] Easy solutions with complexities | mananiac | 0 | 27 | arranging coins | 441 | 0.462 | Easy | 7,793 |
https://leetcode.com/problems/arranging-coins/discuss/2098016/cleanandsimple-python-solution-O(logN) | class Solution:
def arrangeCoins(self, n: int) -> int:
i,j=1,n+1
while i<j:
mid=(i+j)>>1
t=(mid+1)*mid//2
if t<=n:
i=mid+1
else:
j=mid
return i-1 | arranging-coins | clean&simple python solution, O(logN) | xsank | 0 | 10 | arranging coins | 441 | 0.462 | Easy | 7,794 |
https://leetcode.com/problems/arranging-coins/discuss/1863689/Python-Easiest-Solution-With-Explanation-O(logn)-or-Binary-Search-or-Beg-to-Adv | class Solution:
def arrangeCoins(self, n: int) -> int:
def coins(n):
return (n * (1 + n)) // 2 # OR (mid / 2) * (mid + 1)
# above is the formula to calculate, number of coins required to fill the rows completely.
left, right = 1, n
while left <= right:
mid = (right + left) // 2 # calculating mid of the array
a = coins(mid) # capturing the output of coins() method.
if a == n: # if the required coins are equal to the given coin
return mid # as mid represents the number of rows will be there to be filled.
elif a > n: # comparing req number of coins with the total provided number of coins.
right = mid - 1
else:
left = mid + 1
return right # returing number of completed rows | arranging-coins | Python Easiest Solution With Explanation O(logn) | Binary Search | Beg to Adv | rlakshay14 | 0 | 75 | arranging coins | 441 | 0.462 | Easy | 7,795 |
https://leetcode.com/problems/arranging-coins/discuss/1855252/Python-Easiest-Solution-With-Explanation-or-Maths-O(n)-or-Beg-to-Adv-or | class Solution:
def arrangeCoins(self, n: int) -> int:
count: int = 0 #took counter for counting the lines that are completely filled
i: int = 1 # taking variable as iterators for coins
k: int = 1 # taking variable as iterators for rows
while i <= n:
if i == k: # checking if coins and rows are equal or not
count += 1 # if i(th) coin is equal to k(th) row then
i += 1 # increase i(th) coin
k += 1 # increase k(th) row
n -= count # subtract count from n, so that it wont run for each and every coin for everytime, once we step to the next row, will subtract. So that last number of coin get deducted from total number of coins.
return count # return count if i(th) equal to k(th) row | arranging-coins | Python Easiest Solution With Explanation | Maths O(n) | Beg to Adv | | rlakshay14 | 0 | 44 | arranging coins | 441 | 0.462 | Easy | 7,796 |
https://leetcode.com/problems/arranging-coins/discuss/1851469/3-Lines-Python-Solution-oror-40-Faster-oror-Memory-less-than-70 | class Solution:
def arrangeCoins(self, n: int) -> int:
i=0
while n>i: i+=1 ; n-=i
return i | arranging-coins | 3-Lines Python Solution || 40% Faster || Memory less than 70% | Taha-C | 0 | 34 | arranging coins | 441 | 0.462 | Easy | 7,797 |
https://leetcode.com/problems/arranging-coins/discuss/1851469/3-Lines-Python-Solution-oror-40-Faster-oror-Memory-less-than-70 | class Solution:
def arrangeCoins(self, n: int) -> int:
l=0 ; r=n
while l<=r:
k=(r+l)//2
curr=k*(k+1)//2
if curr==n: return k
if n<curr: r=k-1
else: l=k+1
return r | arranging-coins | 3-Lines Python Solution || 40% Faster || Memory less than 70% | Taha-C | 0 | 34 | arranging coins | 441 | 0.462 | Easy | 7,798 |
https://leetcode.com/problems/arranging-coins/discuss/1851469/3-Lines-Python-Solution-oror-40-Faster-oror-Memory-less-than-70 | class Solution:
def arrangeCoins(self, n: int) -> int:
return int((sqrt(1+8*n)-1)/2) | arranging-coins | 3-Lines Python Solution || 40% Faster || Memory less than 70% | Taha-C | 0 | 34 | arranging coins | 441 | 0.462 | Easy | 7,799 |
Subsets and Splits