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/jewels-and-stones/discuss/2815478/Multiple-Fast-and-Simple-Solutions-Python-(One-Liner-Included) | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
return len([True for i in stones if i in jewels]) | jewels-and-stones | Multiple Fast and Simple Solutions - Python (One-Liner Included) | PranavBhatt | 0 | 2 | jewels and stones | 771 | 0.881 | Easy | 12,600 |
https://leetcode.com/problems/jewels-and-stones/discuss/2797510/Simple-Python-solution-with-Counter | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
counter_jewels = Counter(jewels)
counter_stones = Counter(stones)
count = 0
for stone in counter_stones.keys():
if stone in counter_jewels.keys():
count += counter_stones[stone]
return count | jewels-and-stones | Simple Python solution with Counter | hungqpham | 0 | 1 | jewels and stones | 771 | 0.881 | Easy | 12,601 |
https://leetcode.com/problems/jewels-and-stones/discuss/2797372/Python-solution-using-Map | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
map={}
for s in stones:
if s in map:
map[s]+=1
else:
map[s]=1
res=0
for j in jewels:
res+=map.get(j,0)
return res | jewels-and-stones | Python solution using Map | sbhupender68 | 0 | 2 | jewels and stones | 771 | 0.881 | Easy | 12,602 |
https://leetcode.com/problems/jewels-and-stones/discuss/2692893/Python-solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
for ch in stones:
if ch in jewels:
count += 1
return count | jewels-and-stones | Python solution | samanehghafouri | 0 | 1 | jewels and stones | 771 | 0.881 | Easy | 12,603 |
https://leetcode.com/problems/jewels-and-stones/discuss/2691525/Python-Fast-ONE-LINE-Solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
return sum(stones.count(jewel) for jewel in jewels) | jewels-and-stones | Python Fast ONE-LINE Solution | keioon | 0 | 4 | jewels and stones | 771 | 0.881 | Easy | 12,604 |
https://leetcode.com/problems/jewels-and-stones/discuss/2671582/Python-simple | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
ans = 0
for i in jewels:
ans += stones.count(i)
return ans | jewels-and-stones | Python simple | phantran197 | 0 | 2 | jewels and stones | 771 | 0.881 | Easy | 12,605 |
https://leetcode.com/problems/jewels-and-stones/discuss/2666126/Python-solution-using-set. | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
set=jewels
count=0
for i in range(len(stones)):
if stones[i] in set:
count+=1
return count | jewels-and-stones | Python solution using set. | Rajex | 0 | 1 | jewels and stones | 771 | 0.881 | Easy | 12,606 |
https://leetcode.com/problems/jewels-and-stones/discuss/2650668/Easiest-Iterative-python-solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
cnt= 0
for i in jewels:
for j in stones:
if(i==j):
cnt+=1
return cnt | jewels-and-stones | Easiest Iterative python solution | thesaderror | 0 | 1 | jewels and stones | 771 | 0.881 | Easy | 12,607 |
https://leetcode.com/problems/jewels-and-stones/discuss/2490577/Simple-python-code-with-explanation | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
#create the count variable
#initialise the count variable to 0
count = 0
#iterate over the elements in the stones
for i in stones:
#if that elements are in jewels
if i in jewels:
#increase the count val by 1
count = count + 1
#return the count value
return count | jewels-and-stones | Simple python code with explanation | thomanani | 0 | 14 | jewels and stones | 771 | 0.881 | Easy | 12,608 |
https://leetcode.com/problems/jewels-and-stones/discuss/2480035/Python-Solution-using-Counter-or-Dictionary-or-Runtime%3A-37-ms | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# Store given strings in Dictionaries using Counter
# Here, Dict3 gives key,value pairs from Dict2 by comparing keys present in both Dict1,Dict2
# Get only the values from Dict3 and the result will be their sum
Dict1 = Counter(jewels)
Dict2 = Counter(stones)
Dict3 = {key: Dict2[key] for key in Dict1 if key in Dict2}
return sum(Dict3.values()) | jewels-and-stones | Python Solution using Counter | Dictionary | Runtime: 37 ms | Coder0212 | 0 | 14 | jewels and stones | 771 | 0.881 | Easy | 12,609 |
https://leetcode.com/problems/jewels-and-stones/discuss/2474798/Python3-Straightforward | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# Loop through all the stones one by one, and compare it to the list of jewels using .find
total = 0
for stone in stones:
if jewels.find(stone) != -1:
total += 1
return total | jewels-and-stones | [Python3] Straightforward | connorthecrowe | 0 | 15 | jewels and stones | 771 | 0.881 | Easy | 12,610 |
https://leetcode.com/problems/jewels-and-stones/discuss/2455222/Fast-and-Simple-Python-Solution-(-3-Line-) | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
l = [stones.count(i) for i in jewels if i in stones]
if l == []: return 0
return sum(l) | jewels-and-stones | Fast & Simple Python Solution ( 3 Line ) | SouravSingh49 | 0 | 17 | jewels and stones | 771 | 0.881 | Easy | 12,611 |
https://leetcode.com/problems/jewels-and-stones/discuss/2448415/Python3-or-Olog(n)-that-beats-99-submission | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
'''Time complexity: Olog(n)'''
# Iterate through stones and note down if the stone is a jewel
ret = 0
for stone in stones:
if stone in jewels:
ret += 1
return ret | jewels-and-stones | Python3 | Olog(n) that beats 99% submission | romejj | 0 | 27 | jewels and stones | 771 | 0.881 | Easy | 12,612 |
https://leetcode.com/problems/jewels-and-stones/discuss/2435996/Python3-Optimal-Solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
# Method 1: T.C: O(n+m) S.C: O(n)
count = {}
for s in stones:
count[s] = 1 + count.get(s,0)
ans = 0
for key,val in count.items():
if key in jewels:
ans += val
return ans
# Search with tag chawlashivansh for my solutions | jewels-and-stones | Python3 Optimal Solution | chawlashivansh | 0 | 25 | jewels and stones | 771 | 0.881 | Easy | 12,613 |
https://leetcode.com/problems/jewels-and-stones/discuss/2356399/Python-solution-here | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
#iterate over each stone check if it's in jewel then count it as one jewel.
for stone in stones:
if stone in jewels:
count += 1
return count | jewels-and-stones | Python solution here | RohanRob | 0 | 45 | jewels and stones | 771 | 0.881 | Easy | 12,614 |
https://leetcode.com/problems/jewels-and-stones/discuss/2214006/1-line-ans-for-python | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:``
return len([x for x in stones if x in jewels] ) | jewels-and-stones | 1 line ans for python | tancoder24 | 0 | 19 | jewels and stones | 771 | 0.881 | Easy | 12,615 |
https://leetcode.com/problems/jewels-and-stones/discuss/2204524/Python%3A-sum(1-for-jewel-in-stones-if-jewel-in-jewels) | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
return sum([1 for jewel in stones if jewel in jewels]) | jewels-and-stones | Python: sum([1 for jewel in stones if jewel in jewels]) | Simzalabim | 0 | 43 | jewels and stones | 771 | 0.881 | Easy | 12,616 |
https://leetcode.com/problems/jewels-and-stones/discuss/2203947/Easy-Python-Solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
c = 0
for i in jewels:
if i not in stones:
continue
c += stones.count(i)
return c | jewels-and-stones | Easy Python Solution | SuvamRoutray | 0 | 39 | jewels and stones | 771 | 0.881 | Easy | 12,617 |
https://leetcode.com/problems/jewels-and-stones/discuss/2158522/Very-simple-Python-trick-in-4-lines | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
res = 0
for st in stones:
if st in jewels:
res += 1
return res | jewels-and-stones | Very simple Python trick in 4 lines | ankurbhambri | 0 | 56 | jewels and stones | 771 | 0.881 | Easy | 12,618 |
https://leetcode.com/problems/jewels-and-stones/discuss/2147842/python-or-simple-and-short-solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
c=0
l=[]
for i in jewels:
if i in stones and i not in l:
c+=stones.count(i)
l.append(i)
return c | jewels-and-stones | python | simple and short solution | T1n1_B0x1 | 0 | 27 | jewels and stones | 771 | 0.881 | Easy | 12,619 |
https://leetcode.com/problems/jewels-and-stones/discuss/2111725/Yet-another-one-liner-for-Python | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
return len([my_jewel for my_jewel in stones if my_jewel in jewels]) | jewels-and-stones | Yet another one-liner for Python | ealap | 0 | 63 | jewels and stones | 771 | 0.881 | Easy | 12,620 |
https://leetcode.com/problems/jewels-and-stones/discuss/2073113/Python-Solution-100 | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
s={}
ans=0
for stone in stones:
if stone in s:
s[stone]+=1
else:
s[stone]=1
for jewel in jewels:
if jewel in s:
ans+=s[jewel]
return ans | jewels-and-stones | Python Solution 100% | Siddharth_singh | 0 | 81 | jewels and stones | 771 | 0.881 | Easy | 12,621 |
https://leetcode.com/problems/jewels-and-stones/discuss/2022742/Python3-using-for-if-in-and-then-count-it | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
for n in stones:
if n in jewels:
count += 1
return count | jewels-and-stones | [Python3] using for, if in and then count it | Shiyinq | 0 | 30 | jewels and stones | 771 | 0.881 | Easy | 12,622 |
https://leetcode.com/problems/jewels-and-stones/discuss/1960633/Python3-Dictionary-Solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
hashmap = {}
ans = 0
for x in stones:
if x not in hashmap:
hashmap[x] = [1]
else:
hashmap[x] += [1]
for y in jewels:
if y in hashmap:
hashmap[y] += [0]
for z in hashmap:
if hashmap[z][-1] == 0:
ans += len(hashmap[z]) - 1
return ans | jewels-and-stones | Python3 Dictionary Solution | Mr_Watermelon | 0 | 31 | jewels and stones | 771 | 0.881 | Easy | 12,623 |
https://leetcode.com/problems/jewels-and-stones/discuss/1860974/Python-Easy-to-Understand-Solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
jewels_count = 0
for jewel in jewels:
jewels_count = jewels_count + stones.count(jewel)
return jewels_count | jewels-and-stones | Python Easy to Understand Solution | hardik097 | 0 | 28 | jewels and stones | 771 | 0.881 | Easy | 12,624 |
https://leetcode.com/problems/jewels-and-stones/discuss/1850611/Python-3 | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
for jewel in jewels:
for stone in stones:
if jewel == stone:
count += 1
return count | jewels-and-stones | Python 3 | natscripts | 0 | 31 | jewels and stones | 771 | 0.881 | Easy | 12,625 |
https://leetcode.com/problems/jewels-and-stones/discuss/1835658/Simple-python-solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
res = 0
for j in jewels:
res = stones.count(j) + res
return res | jewels-and-stones | Simple python solution | wiselearner | 0 | 25 | jewels and stones | 771 | 0.881 | Easy | 12,626 |
https://leetcode.com/problems/jewels-and-stones/discuss/1825320/python3-O(N)-time-O(N)-space-using-frequency-array | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
freq = [False]*58
for i in jewels:
freq[ord(i) - 65] = True
for i in stones:
if(freq[ord(i)-65]): count+=1
return count | jewels-and-stones | [python3] O(N) time O(N) space using frequency array | ankushbisht01 | 0 | 31 | jewels and stones | 771 | 0.881 | Easy | 12,627 |
https://leetcode.com/problems/jewels-and-stones/discuss/1763393/Easiest-Pythin3-solution | class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int:
count = 0
for s in jewels:
count += stones.count(s)
return count | jewels-and-stones | Easiest Pythin3 solution | Akshayjain45 | 0 | 47 | jewels and stones | 771 | 0.881 | Easy | 12,628 |
https://leetcode.com/problems/sliding-puzzle/discuss/2831256/Python-BFS%3A-77-time-70-space | class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
def isSolved(board):
if board[-1] != 0: return False
for i in range(5):
if board[i] != i + 1: return False
return True
swap = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4],
4: [1, 3, 5],
5: [2, 4],
}
q = [board[0] + board[1]]
steps = 0
seen = set()
while (len(q)):
new_q = []
for board in q:
if tuple(board) in seen: continue
seen.add(tuple(board))
if isSolved(board): return steps
zeroIdx = board.index(0)
for swapIdx in swap[zeroIdx]:
copy = board.copy()
copy[zeroIdx], copy[swapIdx] = copy[swapIdx], copy[zeroIdx]
new_q.append(copy)
steps += 1
q = new_q
return -1 | sliding-puzzle | Python BFS: 77% time, 70% space | hqz3 | 0 | 2 | sliding puzzle | 773 | 0.639 | Hard | 12,629 |
https://leetcode.com/problems/sliding-puzzle/discuss/2119859/python-3-oror-simple-bfs | class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
neighbours = ((1, 3), (0, 2, 4), (1, 5), (0, 4), (1, 3, 5), (2, 4))
board = tuple(tile for row in board for tile in row)
solved = (1, 2, 3, 4, 5, 0)
if board == solved:
return 0
q = collections.deque([(board, 0)])
visited = {board}
while q:
board, moves = q.popleft()
zero = board.index(0)
for neighbour in neighbours[zero]:
newBoard = list(board)
newBoard[zero], newBoard[neighbour] = newBoard[neighbour], newBoard[zero]
newBoard = tuple(newBoard)
if newBoard == solved:
return moves + 1
if newBoard not in visited:
visited.add(newBoard)
q.append((newBoard, moves + 1))
return -1 | sliding-puzzle | python 3 || simple bfs | dereky4 | 0 | 116 | sliding puzzle | 773 | 0.639 | Hard | 12,630 |
https://leetcode.com/problems/sliding-puzzle/discuss/1655208/Python3-heap | class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
heap = []
board = tuple(num for row in board for num in row)
heap.append((0, board))
heapq.heapify(heap)
visited = set()
visited.add(board)
def generate_neighbors(nums):
a, b, c, d, e, f = nums
if a == 0:
return [(b, 0, c, d, e, f), (d, b, c, 0, e, f)]
elif b == 0:
return [(0, a, c, d, e, f), (a, c, 0, d, e, f), (a, e, c, d, 0, f)]
elif c == 0:
return [(a, 0, b, d, e, f), (a, b, f, d, e, 0)]
elif d == 0:
return [(0, b, c, a, e, f), (a, b, c, e, 0, f)]
elif e == 0:
return [(a, b, c, 0, d, f), (a, b, c, d, f, 0), (a, 0, c, d, b, f)]
elif f == 0:
return [(a, b, c, d, 0, e), (a, b, 0, d, e, c)]
while heap:
cost, nums = heapq.heappop(heap)
if tuple([num for num in nums]) == (1, 2, 3, 4, 5, 0):
return cost
else:
for neighbor in generate_neighbors(nums):
if neighbor not in visited:
heapq.heappush(heap, (cost + 1, neighbor))
visited.add(neighbor)
return -1 | sliding-puzzle | Python3 heap | emersonexus | 0 | 150 | sliding puzzle | 773 | 0.639 | Hard | 12,631 |
https://leetcode.com/problems/sliding-puzzle/discuss/1348662/Template-Level-Order-Traversal-BFS-with-string-state-for-visited-%2B-print-path-followup | class Solution:
def __init__(self):
self.memo = dict()
def slidingPuzzle(self, board: List[List[int]]) -> int:
def getState(board):
return ''.join(str(x) for row in board for x in row)
# print(getState(board))
def setState(state):
si = 0
zx, zy = 0, 0
for row in range(2):
for i in range(3):
board[row][i] = int(state[si])
if board[row][i] == 0:
zx,zy = row, i
si += 1
# returns the position of zero ;)
return zx, zy
# now BFS
q = deque([getState(board)])
dist = 0
vis = set()
while q:
# print(q)
level_len = len(q)
for _ in range(level_len):
if q[0] == '123450':
return dist
zx, zy = setState(q.popleft())
# now check all four neighbours.. after swap what happens :)
for x, y in [[zx,zy+1], [zx+1,zy],[zx,zy-1],[zx-1,zy]]:
if 0<=x<2 and 0<=y<3:
board[zx][zy], board[x][y] = board[x][y], board[zx][zy]
state = getState(board)
if state not in vis:
vis.add(state)
q.append(state)
board[zx][zy], board[x][y] = board[x][y], board[zx][zy]
dist += 1
return -1 | sliding-puzzle | Template Level Order Traversal / BFS with string state for visited + print path followup | yozaam | 0 | 50 | sliding puzzle | 773 | 0.639 | Hard | 12,632 |
https://leetcode.com/problems/sliding-puzzle/discuss/1348662/Template-Level-Order-Traversal-BFS-with-string-state-for-visited-%2B-print-path-followup | class Solution:
# each state 6 len and 012345 permutation => (mn)! = 720 -> space = vis array of (mn)!
def slidingPuzzle(self, board: List[List[int]]) -> int:
def getState(board):
return ''.join(str(x) for row in board for x in row)
# print(getState(board))
def setState(state):
si = 0
zx, zy = 0, 0
for row in range(2):
for i in range(3):
board[row][i] = int(state[si])
if board[row][i] == 0:
zx,zy = row, i
si += 1
# returns the position of zero ;)
return zx, zy
parent = dict()
def findPath(state):
res = []
while state in parent
res.append(state)
state = parent[state]
return res
# now template BFS...
q = deque([getState(board)])
dist = 0
vis = set()
while q: # level order traversal, expand one level at a time
# print(q)
level_len = len(q)
for _ in range(level_len):
if q[0] == '123450':
return findPath(q[0])
parent_state = q[0]
zx, zy = setState(q.popleft())
# now check all four neighbours.. after swap what happens :)
for x, y in [[zx,zy+1], [zx+1,zy],[zx,zy-1],[zx-1,zy]]:
if 0<=x<2 and 0<=y<3:
board[zx][zy], board[x][y] = board[x][y], board[zx][zy]
kid_state = getState(board)
parent[kid_state] = parent_state
if state not in vis:
vis.add(state)
q.append(state)
board[zx][zy], board[x][y] = board[x][y], board[zx][zy]
dist += 1
return -1 | sliding-puzzle | Template Level Order Traversal / BFS with string state for visited + print path followup | yozaam | 0 | 50 | sliding puzzle | 773 | 0.639 | Hard | 12,633 |
https://leetcode.com/problems/sliding-puzzle/discuss/1249644/Python3-bfs | class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
board = board[0] + board[1] # flatten into vector
ans = 0
seen = set([tuple(board)])
queue = [board]
while queue:
newq = []
for x in queue:
if x == [1,2,3,4,5,0]: return ans
k = x.index(0)
for kk in (k-1, k+1, k-3, k+3):
if 0 <= kk < 6 and (k, kk) not in ((2, 3), (3, 2)):
xx = x.copy()
xx[k], xx[kk] = xx[kk], xx[k]
if tuple(xx) not in seen:
seen.add(tuple(xx))
newq.append(xx)
queue = newq
ans += 1
return -1 | sliding-puzzle | [Python3] bfs | ye15 | 0 | 73 | sliding puzzle | 773 | 0.639 | Hard | 12,634 |
https://leetcode.com/problems/global-and-local-inversions/discuss/1084172/(Optimal-Solution)-Thinking-Process-Explained-in-More-Detail-than-You'd-Ever-Want | class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
for i, a in enumerate(A):
if (abs(a - i) > 1):
return False
return True | global-and-local-inversions | (Optimal Solution) Thinking Process Explained in More Detail than You'd Ever Want | valige7091 | 3 | 215 | global and local inversions | 775 | 0.436 | Medium | 12,635 |
https://leetcode.com/problems/global-and-local-inversions/discuss/1889872/TLE | class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
currMax = float('-inf')
willBeNextMax = float('-inf')
for num in nums:
if num < currMax:
return False
else:
currMax = willBeNextMax
willBeNextMax = max(willBeNextMax, num)
return True | global-and-local-inversions | TLE | bomb483 | 1 | 122 | global and local inversions | 775 | 0.436 | Medium | 12,636 |
https://leetcode.com/problems/global-and-local-inversions/discuss/1889872/TLE | class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
i = 0
while i < len(nums):
if nums[i] != i:
if nums[i+1] != i or nums[i] != i+1:
return False
else:
i+=1
i+=1
return True | global-and-local-inversions | TLE | bomb483 | 1 | 122 | global and local inversions | 775 | 0.436 | Medium | 12,637 |
https://leetcode.com/problems/global-and-local-inversions/discuss/1889872/TLE | class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
for i, a in enumerate(nums):
if (abs(a - i) > 1):
return False
return True | global-and-local-inversions | TLE | bomb483 | 1 | 122 | global and local inversions | 775 | 0.436 | Medium | 12,638 |
https://leetcode.com/problems/global-and-local-inversions/discuss/1889872/TLE | class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
for i in range(len(nums)-1,-1,-1):
if abs(nums[i]-i) > 1:
return False
return True | global-and-local-inversions | TLE | bomb483 | 1 | 122 | global and local inversions | 775 | 0.436 | Medium | 12,639 |
https://leetcode.com/problems/global-and-local-inversions/discuss/924636/Python3-linear-sweep | class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
for i, x in enumerate(A):
if abs(i - x) > 1: return False
return True | global-and-local-inversions | [Python3] linear sweep | ye15 | 1 | 200 | global and local inversions | 775 | 0.436 | Medium | 12,640 |
https://leetcode.com/problems/global-and-local-inversions/discuss/924636/Python3-linear-sweep | class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
return all(abs(i-x) <= 1 for i, x in enumerate(A)) | global-and-local-inversions | [Python3] linear sweep | ye15 | 1 | 200 | global and local inversions | 775 | 0.436 | Medium | 12,641 |
https://leetcode.com/problems/global-and-local-inversions/discuss/924636/Python3-linear-sweep | class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
cnt = sum(nums[i] > nums[i+1] for i in range(len(nums)-1))
aux = nums.copy() # auxiliary array
def fn(nums, aux, lo, hi):
"""Return count of global inversions of nums[lo:hi]."""
if lo + 1 >= hi: return 0
mid = lo + hi >> 1
left = fn(aux, nums, lo, mid)
right = fn(aux, nums, mid, hi)
split = 0
i, j = lo, mid
for k in range(lo, hi):
if j >= hi or i < mid and aux[i] < aux[j]:
nums[k] = aux[i]
i += 1
else:
nums[k] = aux[j]
j += 1
split += mid - i # split inversions
return left + split + right
return cnt == fn(nums, aux, 0, len(nums)) | global-and-local-inversions | [Python3] linear sweep | ye15 | 1 | 200 | global and local inversions | 775 | 0.436 | Medium | 12,642 |
https://leetcode.com/problems/global-and-local-inversions/discuss/2438235/Help%3A-TLE-for-O(n)-Solution-in-Python | class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
min_elem = nums[-1]
for i in range(len(nums)-3, -1, -1):
if nums[i]>min_elem:
return False
min_elem = min(min_elem, nums[i+1])
return True | global-and-local-inversions | Help: TLE for O(n) Solution in Python | shreshtashetty | 0 | 63 | global and local inversions | 775 | 0.436 | Medium | 12,643 |
https://leetcode.com/problems/global-and-local-inversions/discuss/452947/python-solution | class Solution:
def isIdealPermutation(self, A: List[int]) -> bool:
m=float('inf')
for i in range(len(A)-1,1,-1):
m=min(m,A[i])
if A[i-2]>m:
return False
return True | global-and-local-inversions | python solution | zhuwannabeacoder | 0 | 217 | global and local inversions | 775 | 0.436 | Medium | 12,644 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/2712752/Python3-Solution-or-O(n)-or-Clean-and-Concise | class Solution:
def canTransform(self, S, E):
L, R, X = 0, 0, 0
for i, j in zip(S, E):
L += (j == 'L')
R += (i == 'R')
if i == 'R' and L: return False
if j == 'L' and R: return False
L -= (i == 'L')
R -= (j == 'R')
if L < 0 or R < 0: return False
X += (i == 'X') - (j == 'X')
return X == 0 | swap-adjacent-in-lr-string | ✔ Python3 Solution | O(n) | Clean and Concise | satyam2001 | 0 | 10 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,645 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/2410019/Python-3-2-pointers | class Solution:
def canTransform(self, start: str, end: str) -> bool:
i=j=0
n=len(start)
while i<n or j<n:
while i<n and start[i]=='X':
i+=1
while j<n and end[j]=='X':
j+=1
if i==n or j==n:
return i==j
if start[i]!=end[j]:
return False
if (start[i]=='L' and j>i) or (start[i]=='R' and i>j):
return False
i+=1
j+=1
return True | swap-adjacent-in-lr-string | [Python 3] 2 pointers | gabhay | 0 | 69 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,646 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/2319461/python-3-or-elegant-two-pointer-solution-or-O(n)O(1) | class Solution:
def canTransform(self, start: str, end: str) -> bool:
def chars(s):
for i, c in enumerate(s):
if c != 'X':
yield i, c
yield -1, ' '
for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):
if (startC != endC or
(startC == 'L' and startI < endI) or
(startC == 'R' and startI > endI)):
return False
return True | swap-adjacent-in-lr-string | python 3 | elegant two-pointer solution | O(n)/O(1) | dereky4 | 0 | 181 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,647 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/926005/Python3-two-approaches | class Solution:
def canTransform(self, start: str, end: str) -> bool:
if Counter(start) != Counter(end): return False # edge case
fs = fe = bs = be = 0 # forward s & e counter and backward s & e counter
for i in range(len(start)):
fs = 0 if start[i] == "L" else (fs + start[i] == "R")
fe = 0 if end[i] == "L" else (fs + end[i] == "R")
bs = 0 if start[~i] == "R" else (bs + start[~i] == "L")
be = 0 if end[~i] == "R" else (be + end[~i] == "L")
if fs < fe or bs < be: return False
return True | swap-adjacent-in-lr-string | [Python3] two approaches | ye15 | 0 | 277 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,648 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/926005/Python3-two-approaches | class Solution:
def canTransform(self, start: str, end: str) -> bool:
ss = [(x, i) for i, x in enumerate(start) if x != "X"]
ee = [(x, i) for i, x in enumerate(end) if x != "X"]
if len(ss) != len(ee): return False
for (s, i), (e, j) in zip(ss, ee):
if s != e: return False
if s == e == "L" and i < j: return False
if s == e == "R" and i > j: return False
return True | swap-adjacent-in-lr-string | [Python3] two approaches | ye15 | 0 | 277 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,649 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/739804/Iterative-easy-python-solution | class Solution:
def canTransform(self, start: str, end: str) -> bool:
if len(start) != len(end) or sorted(start) != sorted(end): return False
invalid = ['XR', 'LX', 'RL', 'LR']
for i in range(len(start)):
e = end[i]
s = start[i]
print([(s,e)])
if e == s: continue
if s+e in invalid: return False
if s == 'R' and e == 'X':
idx = start.find('X', i)
if idx == -1: return False
if start.find('L', i, idx) != -1: return False
start = start[:i] + 'X' + start[i+1:idx] + 'R' + start[idx+1:]
elif s == 'X' and e == 'L':
idx = start.find('L', i)
if idx == -1: return False
if start.find('R', i, idx) != -1: return False
start = start[:i] + 'L' + start[i+1:idx] + 'X' + start[idx+1:]
return True | swap-adjacent-in-lr-string | Iterative easy python solution | marzi_ash | 0 | 154 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,650 |
https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/481798/Python-2-checks-one-for-counts-one-for-equality | class Solution:
def canTransform(self, start: str, end: str) -> bool:
ret_0 = collections.defaultdict(int)
ret_1 = collections.defaultdict(int)
lst_0, lst_1 = [[]]*2
r0, r1 = [""]*2
i = 0
while i < len(start):
if start[i] in "LR":
ret_0[start[i]] += 1
r0 += start[i]
if end[i] in "LR":
ret_1[end[i]] += 1
r1 += end[i]
if ret_0["R"] >= ret_1["R"] and ret_0["L"] <= ret_1["L"]:
pass
else:
return False
i += 1
return True if r0 == r1 else False | swap-adjacent-in-lr-string | [Python] 2 checks, one for counts, one for equality | Roger_Q | 0 | 324 | swap adjacent in lr string | 777 | 0.371 | Medium | 12,651 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2464943/Easy-to-follow-python3-solutoon | class Solution:
# O(max(n^2, m)) time, h --> the highest elevation in the grid
# O(n^2) space,
# Approach: BFS, Priority queue
# I wld advise to do task scheduler question, it's pretty similar
# except that u apply bfs to traverse the grid 4 directionally
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid)
if n == 1:
return 0
def getNeighbours(coord: Tuple) -> List[Tuple]:
i, j = coord
n = len(grid)
neighbours = []
if i < n-1:
neighbours.append((i+1, j))
if i > 0:
neighbours.append((i-1, j))
if j < n-1:
neighbours.append((i, j+1))
if j > 0:
neighbours.append((i, j-1))
return neighbours
qu = deque()
waiting_qu = []
vstd = set()
waiting_qu.append([grid[0][0], (0, 0)])
vstd.add((0, 0))
time = 0
while waiting_qu:
time +=1
while waiting_qu and waiting_qu[0][0] <= time:
qu.append(heapq.heappop(waiting_qu)[1])
while qu:
cell = qu.popleft()
if cell == (n-1, n-1):
return time
nbrs = getNeighbours(cell)
for nb in nbrs:
if nb in vstd: continue
x, y = nb
elevation = grid[x][y]
vstd.add(nb)
if elevation > time:
heapq.heappush(waiting_qu, [elevation, nb])
else:
qu.append(nb)
return -1 | swim-in-rising-water | Easy to follow python3 solutoon | destifo | 1 | 34 | swim in rising water | 778 | 0.597 | Hard | 12,652 |
https://leetcode.com/problems/swim-in-rising-water/discuss/1739695/Python-easy-to-understand-or-djikstras | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid)
minheap = [(grid[0][0], 0, 0)]
visited = [[False for _ in range(n)] for _ in range(n)]
visited[0][0] = True
while minheap:
maxht, x, y = heapq.heappop(minheap)
#print(maxht, x, y)
if x == n-1 and y == n-1:
return maxht
if x > 0 and visited[x-1][y] == False:
visited[x-1][y] = True
heapq.heappush(minheap, (max(maxht, grid[x-1][y]), x-1, y))
if y > 0 and visited[x][y-1] == False:
visited[x][y-1] = True
heapq.heappush(minheap, (max(maxht, grid[x][y-1]), x, y-1))
if x < n-1 and visited[x+1][y] == False:
visited[x+1][y] = True
heapq.heappush(minheap, (max(maxht, grid[x+1][y]), x+1, y))
if y < n-1 and visited[x][y+1] == False:
visited[x][y+1] = True
heapq.heappush(minheap, (max(maxht, grid[x][y+1]), x, y+1)) | swim-in-rising-water | Python easy to understand | djikstras | sanial2001 | 1 | 162 | swim in rising water | 778 | 0.597 | Hard | 12,653 |
https://leetcode.com/problems/swim-in-rising-water/discuss/1257806/Python3-Dijkstra's-algo | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid) # dimension
pq = [(grid[0][0], 0, 0)]
seen = {(0, 0)}
while pq:
k, i, j = heappop(pq)
if i == j == n-1: return k
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < n and 0 <= jj < n and (ii, jj) not in seen:
heappush(pq, (max(k, grid[ii][jj]), ii, jj))
seen.add((ii, jj)) | swim-in-rising-water | [Python3] Dijkstra's algo | ye15 | 1 | 66 | swim in rising water | 778 | 0.597 | Hard | 12,654 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2848504/Python3-BFS-with-PriorityQueue-(faster-than-80)-soln | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
dir=[[1,0],[-1,0],[0,1],[0,-1]]
n=len(grid)
q=[[grid[0][0],0,0]]
visit=set()
while q:
lvl,i,j=heapq.heappop(q)
if i==n-1 and j==n-1:
return lvl
if (i,j) in visit:
continue
visit.add((i,j))
for d in dir:
x=i+d[0]
y=j+d[1]
if 0<=x<n and 0<=y<n and (x,y) not in visit:
if grid[x][y]<=lvl:
heapq.heappush(q,[lvl,x,y])
else:
heapq.heappush(q,[lvl+abs(grid[x][y]-lvl),x,y]) | swim-in-rising-water | Python3 BFS with PriorityQueue (faster than 80%) soln | DhruvBagrecha | 0 | 1 | swim in rising water | 778 | 0.597 | Hard | 12,655 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2814500/Python3-Dijkstra's-Algorithm-%2B-Min-Heap-or-93-ms-Beats-99.42-Memory-14.2-MB-Beats-99.21 | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
N ,minH= len(grid),[[grid[0][0],0,0]]
while minH:
t,r,c = heapq.heappop(minH)
if r == N-1 and c == N-1:
return t
for dr,dc in [[0,1],[0,-1],[1,0],[-1,0]]:
neiR ,neiC= r+dr ,c+dc
if neiC < 0 or neiR < 0 or neiR >=N or neiC>=N or grid[neiR][neiC]==-1:
continue
heapq.heappush(minH, [ max(t,grid[neiR][neiC]), neiR,neiC])
grid[neiR][neiC]=-1 | swim-in-rising-water | [Python3] Dijkstra's Algorithm + Min Heap | 93 ms Beats 99.42% Memory 14.2 MB Beats 99.21% | saarahasad | 0 | 3 | swim in rising water | 778 | 0.597 | Hard | 12,656 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2791278/Dijkstra's-Solution-by-UC-Berkeley-Computer-Science-Honor-Society. | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
"""
since this is solved using backtracking (brute force), we know we'll have to use djikstra's (or some variant of it) to solve this problem.
Realize that this problem reduces to solving the shortest value path from (0, 0) to (n - 1, n - 1) where a path's value is determined by the largest value in it.
"""
import heapq
n = len(grid)
heap = [(grid[0][0], 0, 0)]
val = [[float('inf')] * n for _ in range(n)]
val[0][0] = grid[0][0]
#we can conserve space and use our grid matrix as a visited array
while heap:
v, i, j = heapq.heappop(heap) #we want to pop the minimum value visited so far (greedily construct our path)
if grid[i][j] == '#':
continue
grid[i][j] = '#'
for r, c in [(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)]:
if not ((0 <= r < n) and (0 <= c < n)) or grid[r][c] == '#':
continue
if val[r][c] > max(grid[r][c], v):
val[r][c] = max(grid[r][c], v)
heapq.heappush(heap, (val[r][c], r, c))
return val[n - 1][n - 1]
#time complexity is O(nm log nm) space complexity is O(nm) | swim-in-rising-water | Dijkstra's Solution by UC Berkeley Computer Science Honor Society. | berkeley_upe | 0 | 7 | swim in rising water | 778 | 0.597 | Hard | 12,657 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2578606/python-solution-using-minheap-and-bfs | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
vis,n,m=set([(0,0)]),len(grid),len(grid[0])
hp=[[grid[0][0],0,0]]
heapq.heapify(hp)
moves=[(1,0),(0,1),(-1,0),(0,-1)]
while hp:
val,r,c=heapq.heappop(hp)
if r==n-1 and c==m-1:
return val
for move in moves:
tx=r+move[0]
ty=c+move[1]
if tx in range(n) and ty in range(m) and (tx,ty) not in vis:
vis.add((tx,ty))
heapq.heappush(hp,[max(val,grid[tx][ty]),tx,ty]) | swim-in-rising-water | python solution using minheap and bfs | benon | 0 | 25 | swim in rising water | 778 | 0.597 | Hard | 12,658 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2171079/Python-priority-queue | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
def travel():
heap = []
n = len(grid)
heap = [(grid[0][0], (0, 0))]
seen = set()
curr_max = -inf
while heap:
m, point = heappop(heap)
if point in seen:
continue
seen.add(point)
curr_max = max(curr_max, grid[point[0]][point[1]])
if point == (n-1, n-1):
return max(curr_max, grid[n-1][n-1])
for di, dj in [(0, 1), (0, -1), (-1, 0), (1, 0)]:
ci = point[0] + di
cj = point[1] + dj
if 0 <= ci < n and 0 <= cj < n:
heappush(heap, (grid[ci][cj], (ci, cj)))
return curr_max
return travel() | swim-in-rising-water | Python priority queue | 0xsapra1 | 0 | 40 | swim in rising water | 778 | 0.597 | Hard | 12,659 |
https://leetcode.com/problems/swim-in-rising-water/discuss/2035498/Python-solution-bfs-using-heap | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
visited = set()
minheap = [[grid[0][0], [0, 0]]]
ans = -float('inf')
while len(minheap) > 0:
h, [x, y] = heappop(minheap)
ans = max(h, ans)
if x == len(grid) - 1 and y == len(grid) - 1:
break
if (x, y) not in visited:
visited.add((x, y))
for cx, cy in [[x+1, y], [x-1, y], [x, y-1], [x, y+1]]:
if 0 <= cx < len(grid) and 0 <= cy < len(grid[0]):
if (cx, cy) not in visited:
heappush(minheap, [grid[cx][cy], [cx, cy]])
return ans | swim-in-rising-water | Python solution bfs using heap | user6397p | 0 | 34 | swim in rising water | 778 | 0.597 | Hard | 12,660 |
https://leetcode.com/problems/swim-in-rising-water/discuss/1753926/Python-BFS-O(T-*-N-2)-time-complexity | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
n = len(grid)
t = max(grid[0][0], grid[n-1][n-1])
def bfs():
queue = deque([(0, 0)])
visited = {(0, 0)}
while queue:
r, c = queue.popleft()
if r == c == n-1: return True
for r1, c1 in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:
if 0 <= r1 < n and 0 <= c1 < n and (r1, c1) not in visited and grid[r1][c1] <= t:
queue.append((r1, c1))
visited.add((r1, c1))
return False
while True:
if bfs():
return t
t += 1 | swim-in-rising-water | Python BFS O(T * N^ 2) time complexity | totoslg | 0 | 39 | swim in rising water | 778 | 0.597 | Hard | 12,661 |
https://leetcode.com/problems/swim-in-rising-water/discuss/1611810/Python-Dijkstras-using-Heap | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
#heap = [(time value to take to reach grid[x][y], (x,y))]
heap = [(grid[0][0],(0,0))]
heapq.heapify(heap)
#Visited Array
visited = [[False] * len(grid) for i in range(len(grid))]
#Get list of moves that are in bounded and have not been repeated
def get_legal_moves(x, y):
moves = [(0,0)] * 4
moves[0]=(x,y+1)
moves[1]=(x,y-1)
moves[2]=(x+1,y)
moves[3]=(x-1,y)
legal_moves = []
for mx,my in moves:
if mx>=0 and mx<len(grid) and my>=0 and my<len(grid[0]) and visited[mx][my]==False:
legal_moves.append((mx,my))
return legal_moves
#Dijkstras Algorithm
while heap != []:
cur_t, point = heappop(heap)
x,y = point
x = -x
y = -y
if visited[x][y] == False:
visited[x][y] = True
if x == y and y == len(grid) - 1:
return cur_t
for mx,my in get_legal_moves(x,y):
if grid[mx][my] <= cur_t:
heappush(heap,(cur_t,(-mx,-my)))
else:
heappush(heap,(grid[mx][my],(-mx,-my)))
return -1 | swim-in-rising-water | Python Dijkstras using Heap | 17pchaloori | 0 | 98 | swim in rising water | 778 | 0.597 | Hard | 12,662 |
https://leetcode.com/problems/swim-in-rising-water/discuss/1285824/Clean-%2B-Straightforward-Python | class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
max_seen = 0
q = []
heapq.heapify(q)
heapq.heappush(q, (grid[0][0], 0, 0))
while q:
v, r, c = heapq.heappop(q)
if grid[r][c] == '#':
continue
max_seen = max(max_seen, grid[r][c])
grid[r][c] = '#'
if r == c == rows-1:
return max_seen
for y, x in directions:
nr = r + y
nc = c + x
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != '#':
heapq.heappush(q, (grid[nr][nc], nr, nc))
return -1 | swim-in-rising-water | Clean + Straightforward Python | Pythagoras_the_3rd | 0 | 109 | swim in rising water | 778 | 0.597 | Hard | 12,663 |
https://leetcode.com/problems/swim-in-rising-water/discuss/1284995/Python3-Shortest-path-sol-for-reference | class Solution:
def swimInWater(self, grid) -> int:
rows = len(grid)
cols = len(grid[0])
T = [[float('-inf') for _ in range(cols)] for _ in range(rows)]
stack = [(grid[0][0], 0,0)]
visited = {}
while stack:
time,x,y = heapq.heappop(stack)
nei = [(1,0), (-1,0), (0,1),(0,-1)]
for dx,dy in nei:
nx, ny = x+dx, y+dy
if (nx,ny) not in visited and nx >= 0 and nx < rows and ny >= 0 and ny < cols:
T[nx][ny] = max(grid[nx][ny], time)
visited[(nx,ny)] = True
if nx == rows-1 and ny == cols-1:
return T[-1][-1]
heapq.heappush(stack, (max(grid[nx][ny], time), nx, ny))
return T[-1][-1] | swim-in-rising-water | [Python3] Shortest path sol for reference | vadhri_venkat | 0 | 31 | swim in rising water | 778 | 0.597 | Hard | 12,664 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/945679/Python-recursive-everything-you-need-to-know | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
if N == 1:
return 0
half = 2**(N - 2)
if K > half:
return 1 if self.kthGrammar(N - 1, K - half) == 0 else 0
else:
return self.kthGrammar(N - 1, K) | k-th-symbol-in-grammar | Python recursive, everything you need to know | lattices | 6 | 343 | k th symbol in grammar | 779 | 0.409 | Medium | 12,665 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2836005/Python3-Solution-or-O(logk) | class Solution:
def kthGrammar(self, N, K):
if K == 1: return 0
if K & 1: return self.kthGrammar(N - 1, K // 2 + 1)
return self.kthGrammar(N - 1, K // 2) ^ 1 | k-th-symbol-in-grammar | ✔ Python3 Solution | O(logk) | satyam2001 | 1 | 34 | k th symbol in grammar | 779 | 0.409 | Medium | 12,666 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2836005/Python3-Solution-or-O(logk) | class Solution:
def kthGrammar(self, N, K):
ans = 0
while K > 1:
ans ^= ((K & 1) ^ 1)
K = (K >> 1) + (K & 1)
return ans | k-th-symbol-in-grammar | ✔ Python3 Solution | O(logk) | satyam2001 | 1 | 34 | k th symbol in grammar | 779 | 0.409 | Medium | 12,667 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/1721536/Python-recursive-solution-beats-90.32 | **class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n==1 or k==1:
return 0
length=1<<n-1 #2(n-1)
mid=length//2
if k<=mid:
return self.kthGrammar(n-1,k)
else:
return (int (not(self.kthGrammar(n-1,k-mid))))** | k-th-symbol-in-grammar | Python recursive solution beats 90.32 % | RaghavGupta22 | 1 | 177 | k th symbol in grammar | 779 | 0.409 | Medium | 12,668 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2848679/Python-Verbose-but-easy-to-understand-with-diagrams | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1:
return 0
if k % 2 == 0:
parent = self.kthGrammar(n-1, k/2)
if parent == 0:
return 1
else:
return 0
if k % 2 == 1
parent = self.kthGrammar(n-1, (k+1)/2)
if parent == 0:
return 0
else:
return 1 | k-th-symbol-in-grammar | Python - Verbose but easy to understand with diagrams | sc1233 | 0 | 1 | k th symbol in grammar | 779 | 0.409 | Medium | 12,669 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2845821/Python-solution-with-simple-Intuition | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
# Base case
if(n==1):
return 0
# finding lenght of string at level n
length = pow(2,n-1)
# We will try to find out the k in the left part only
# as right part is mirror image for odd row and
# inverted mirror image for even row
# if k is in the left part then Hurray...
# else find mirror index in the left part
newK = k if k <= length//2 else length - k + 1
# IMP: left half of level n = whole string at level (n-1)
# if it is even row and k is in the right part
if n%2==0 and k > length//2:
return int(not(self.kthGrammar(n-1, newK)))
else: return self.kthGrammar(n-1, newK) | k-th-symbol-in-grammar | Python solution with simple Intuition | samart3010 | 0 | 3 | k th symbol in grammar | 779 | 0.409 | Medium | 12,670 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2834137/Original-Python-solution-or-Beats-75-in-Runtime-or-67-in-Memory | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
parent = 2
return self.find_parent(n-1, k-1, 2)
def find_parent(self, n, prev_index, parent) -> int:
if n == 0:
if prev_index%2 == 0:
parent = 0
else:
parent = 1
return parent
next_index = prev_index // 2
parent = self.find_parent(n-1, next_index, parent)
if parent == 0:
if prev_index%2 == 0:
parent = 0
else:
parent = 1
return parent
elif parent == 1:
if prev_index%2 == 0:
parent = 1
else:
parent = 0
return parent
return parent | k-th-symbol-in-grammar | Original Python solution | Beats 75% in Runtime | 67% in Memory | bofanj | 0 | 1 | k th symbol in grammar | 779 | 0.409 | Medium | 12,671 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2804385/Really-enjoyed-this-question-..-binary-tree-(child-parent)-%2B-recursion-concepts | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
map = {('l','0') : '0', ('r','0') : '1', ('l','1') : '1', ('r','1') : '0'}
self.q = []
def recursive(n,k):
if n == 1:
return
if int((k - 1) % 2) == 0:
self.q.append('r')
recursive(n-1,(k-1)/2)
elif int(k % 2) == 0:
self.q.append('l')
recursive(n-1,k/2)
recursive(n,k-1)
ans = '0'
for direction in self.q[::-1]:
ans = map[(direction,ans)]
return ans | k-th-symbol-in-grammar | Really enjoyed this question .. binary tree (child-parent) + recursion concepts | ariboi27 | 0 | 3 | k th symbol in grammar | 779 | 0.409 | Medium | 12,672 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2723278/Recursion-O(log(n)) | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n==1 or k==1:
return 0
prevk=ceil(k/2)
prev=self.kthGrammar(n-1,prevk)
if (prev==1 and k%2==1) or prev==0 and k%2==0:
return 1
return 0 | k-th-symbol-in-grammar | Recursion - O(log(n)) | ConfusedMoe | 0 | 6 | k th symbol in grammar | 779 | 0.409 | Medium | 12,673 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2702409/Python3-Recursive-solution | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n==1 and k==1:
return 0
mid = pow(2,n-1)//2
if k<=mid:
return self.kthGrammar(n-1,k)
else:
ans = not self.kthGrammar(n-1,k-mid)
return 1 if ans == True else 0 | k-th-symbol-in-grammar | Python3 Recursive solution | shashank732001 | 0 | 8 | k th symbol in grammar | 779 | 0.409 | Medium | 12,674 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2436677/Python3-or-Simple-Intuitive-Recursive-Approach | class Solution:
#Time-Complexity: O(n)
#Space-Complexity: O(n), since stack frames will be at most n recursive calls!
def kthGrammar(self, n: int, k: int) -> int:
#Approach: Handle this recursively!
#base case: only one symbol in 1st row!
if(n == 1):
return 0
#divide k by 2 and round up to nearest integer: kth symbol in previous n-1th row for the parent
#symbol of current kth symbol in nth row!
parent_pos = math.ceil(k / 2)
#then, we have to recurse to find if parent symbol is 0 or 1!
recurse = self.kthGrammar(n-1, parent_pos)
#we will handle differently depending on whether parent element is 0 or 1!
#Since if parent is 0, then first element of its children pair will be 0! Otherwise, a 1!
if(recurse == 0):
#if k is odd, then its first element of pair!
if(k % 2 == 1):
return 0
else:
return 1
else:
if(k % 2 == 1):
return 1
else:
return 0 | k-th-symbol-in-grammar | Python3 | Simple Intuitive Recursive Approach | JOON1234 | 0 | 74 | k th symbol in grammar | 779 | 0.409 | Medium | 12,675 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2436284/Python3-or-Memory-Limit-Exceeded-Help! | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
#base case: n == 1
if(n == 1):
return 0
if(n == 2 and k == 1):
return 0
if(n == 2 and k == 2):
return 1
#for cases of n>=3, basically there are 3 cases! k is to the left of middle, k == middle, or
#k exceeds middle position!
#hashmap: map keys: n -> vals: Sn which is string of length 2^(n-1)
hashmap = {}
hashmap[0] = ""
hashmap[1] = "0"
#iterate for i = 3 to i =n!
for i in range(2, n+1, 1):
#prev: Si-1 string!
prev = hashmap[i-1]
#nxt: store the overall string which is concatenating s1 + s2 + ... + si-1 strings!
nxt = ""
for j in range(1, i-1):
nxt += hashmap[j]
hashmap[i] = prev + "1" + nxt
prev = ""
nxt = ""
#once for loop is over, we have sn string! refer to it to get answer!
#Sn string stored in current!
current = hashmap[n]
print(current)
#kth char will be at index k-1 in the given string!
ans = current[k-1]
#typecast the digit character to an int type!
return int(ans) | k-th-symbol-in-grammar | Python3 | Memory Limit Exceeded Help! | JOON1234 | 0 | 27 | k th symbol in grammar | 779 | 0.409 | Medium | 12,676 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/2252221/Easy-python-solution-using-recursion. | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1 and k == 1:
return 0
mid = (2**(n-1))//2
if k <= mid:
return self.kthGrammar(n-1,k)
else:
if (self.kthGrammar(n-1,k-mid) == 1):
return 0
return 1 | k-th-symbol-in-grammar | Easy python solution using recursion. | 1903480100017_A | 0 | 78 | k th symbol in grammar | 779 | 0.409 | Medium | 12,677 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/1792537/Python-Recursion | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if k == 1:
return 0
up = self.kthGrammar(n-1,(k+1)//2)
return (k+up+1)%2 | k-th-symbol-in-grammar | [Python] Recursion | haydarevren | 0 | 84 | k th symbol in grammar | 779 | 0.409 | Medium | 12,678 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/1663473/Sexy-Python-Recursive-Method | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1 or k == 1:
return 0
c = self.kthGrammar(n-1, (k+1)//2)
if c == 1 and k % 2 == 0:
return 0
elif c == 1 and k % 2 == 1:
return 1
elif c == 0 and k % 2 == 0:
return 1
elif c == 0 and k % 2 == 1:
return 0
``` | k-th-symbol-in-grammar | Sexy Python Recursive Method | MemphisMeng | 0 | 137 | k th symbol in grammar | 779 | 0.409 | Medium | 12,679 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/1611117/python-3-oror-recursion-oror-clean-oror-easy | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
def solve(n,k):
if n==1 and k==1:
return 0
mid=pow(2,n-1)//2
if k<=mid:
return solve(n-1,k)
elif k>mid:
return int(not(solve(n-1,k-mid)))
return solve(n,k) | k-th-symbol-in-grammar | python 3 || recursion || clean || easy | minato_namikaze | 0 | 113 | k th symbol in grammar | 779 | 0.409 | Medium | 12,680 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/1529774/python-symmetric-and-opposite-solution | class Solution:
def kthGrammar(self, row: int, col: int) -> int:
if row == 1 or col == 1:
return 0
width = 2 ** (row - 1) + 1 # +1 since 1-indexed
if col <= width // 2: # prefix same as above row
return self.kthGrammar(row - 1, col)
# the odd rows are symmetric
# the even rows are opposite
return 1 ^ row % 2 ^ self.kthGrammar(row - 1, width - col) | k-th-symbol-in-grammar | python symmetric & opposite solution | feexon | 0 | 89 | k th symbol in grammar | 779 | 0.409 | Medium | 12,681 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/925863/Python3-recursive-and-iterative-implementations | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
if K == 1: return 0
if K > 2**(N-2): return 1^self.kthGrammar(N, K-2**(N-2))
return self.kthGrammar(N-1, K) | k-th-symbol-in-grammar | [Python3] recursive & iterative implementations | ye15 | 0 | 75 | k th symbol in grammar | 779 | 0.409 | Medium | 12,682 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/925863/Python3-recursive-and-iterative-implementations | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
ans = 0
while K > 1:
if K > 2**(N-2):
ans ^= 1
K -= 2**(N-2)
else: N -= 1
return ans | k-th-symbol-in-grammar | [Python3] recursive & iterative implementations | ye15 | 0 | 75 | k th symbol in grammar | 779 | 0.409 | Medium | 12,683 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/925863/Python3-recursive-and-iterative-implementations | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
return bin(K-1).count("1") & 1 | k-th-symbol-in-grammar | [Python3] recursive & iterative implementations | ye15 | 0 | 75 | k th symbol in grammar | 779 | 0.409 | Medium | 12,684 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/925863/Python3-recursive-and-iterative-implementations | class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if n == 1: return 0
return int(self.kthGrammar(n-1, (k+1)//2) == k&1) | k-th-symbol-in-grammar | [Python3] recursive & iterative implementations | ye15 | 0 | 75 | k th symbol in grammar | 779 | 0.409 | Medium | 12,685 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/920667/Python-straight-forward-solution | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
def helper(n: int, k: int):
if (n, k) == (1, 1):
return 0
if k % 2 != 0:
return helper(n - 1, ceil(k / 2))
else:
return helper(n - 1, ceil(k / 2)) ^ 1
return helper(N, K) | k-th-symbol-in-grammar | Python straight-forward solution | liangy3928 | 0 | 57 | k th symbol in grammar | 779 | 0.409 | Medium | 12,686 |
https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/376136/Python-recursion-with-memoization | class Solution:
def kthGrammar(self, N: int, K: int) -> int:
memo = {(1,1): 0}
def helper(n,k):
if (n,k) in memo:
return memo[(n,k)]
if k==1: return 0
t = helper(n-1, math.ceil(k/2))
if t==0:
if k%2==0: return 1
else: return 0
if t==1:
if k%2==0: return 0
else: return 1
return helper(N,K) | k-th-symbol-in-grammar | Python recursion with memoization | aaby | 0 | 107 | k th symbol in grammar | 779 | 0.409 | Medium | 12,687 |
https://leetcode.com/problems/reaching-points/discuss/808072/Python-recursive-solution-runtime-beats-98.91 | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
if sx > tx or sy > ty: return False
if sx == tx: return (ty-sy)%sx == 0 # only change y
if sy == ty: return (tx-sx)%sy == 0
if tx > ty:
return self.reachingPoints(sx, sy, tx%ty, ty) # make sure tx%ty < ty
elif tx < ty:
return self.reachingPoints(sx, sy, tx, ty%tx)
else:
return False | reaching-points | Python recursive solution runtime beats 98.91 % | yiz486 | 14 | 3,300 | reaching points | 780 | 0.324 | Hard | 12,688 |
https://leetcode.com/problems/reaching-points/discuss/1305255/Python3-iteratively-reduce-tx-and-ty | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while sx < tx or sy < ty:
if tx > ty:
k = (tx - sx)//ty
if k == 0: break
tx -= k * ty
else:
k = (ty - sy)//tx
if k == 0: break
ty -= k * tx
return sx == tx and sy == ty | reaching-points | [Python3] iteratively reduce tx & ty | ye15 | 3 | 671 | reaching points | 780 | 0.324 | Hard | 12,689 |
https://leetcode.com/problems/reaching-points/discuss/1037275/Python-Iterative-Solution-time-complexity%3A-O(log-max(tx-ty)) | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while sx <= tx and sy <= ty:
if tx == sx:
return (ty - sy) % sx == 0
elif ty == sy:
return (tx - sx) % sy == 0
elif tx > ty:
tx %= ty
else:
ty %= tx
return False | reaching-points | Python Iterative Solution, time complexity: O(log max(tx, ty)) | cheng-hao2 | 1 | 635 | reaching points | 780 | 0.324 | Hard | 12,690 |
https://leetcode.com/problems/reaching-points/discuss/462622/easy-to-understand-python16ms-c%2B%2B4ms-same-logic | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
if tx<sx or ty<sy:
return False
elif tx==sx:
if (ty-sy)%sx==0:
return True
else:
return False
elif ty==sy:
if (tx-sx)%sy==0:
return True
else:
return False
else:
return self.reachingPoints(sx,sy,tx-ty,ty) or self.reachingPoints(sx,sy,tx,ty-tx) | reaching-points | easy to understand, python/16ms, c++/4ms, same logic | felicia1994 | 1 | 979 | reaching points | 780 | 0.324 | Hard | 12,691 |
https://leetcode.com/problems/reaching-points/discuss/2849022/Python-easy-to-read-and-understand-or-recursion | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
q = [(sx, sy)]
visit = set()
visit.add((sx, sy))
while q:
num = len(q)
for i in range(num):
x, y = q.pop(0)
if x == tx and y == ty:
return True
if x <= tx and y <= ty:
if (x, x+y) not in visit:
visit.add((x, x+y))
q.append((x, x+y))
if (x+y, y) not in visit:
visit.add((x+y, y))
q.append((x+y, y))
return False | reaching-points | Python easy to read and understand | recursion | sanial2001 | 0 | 1 | reaching points | 780 | 0.324 | Hard | 12,692 |
https://leetcode.com/problems/reaching-points/discuss/2849022/Python-easy-to-read-and-understand-or-recursion | class Solution:
def dfs(self, x, y, tx, ty):
if x > tx or y > ty:
return 0
if x == tx and y == ty:
return 1
if (x, y) in self.d:
return self.d[(x, y)]
self.d[(x, y)] = self.dfs(x+y, y, tx, ty) or self.dfs(x, x+y, tx, ty)
return self.d[(x, y)]
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
self.d = {}
return self.dfs(sx, sy, tx, ty) | reaching-points | Python easy to read and understand | recursion | sanial2001 | 0 | 1 | reaching points | 780 | 0.324 | Hard | 12,693 |
https://leetcode.com/problems/reaching-points/discuss/2848304/Python3-Impossible-not-to-understand-Intuitive-Method-with-Detailed-Explanation | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
while tx >= sx + ty or ty >= sy + tx: # make sure we can still make substractions
if tx > ty:
tx = sx + (tx - sx) % ty # the smallest we can get by deducting ty from tx
else:
ty = sy + (ty - sy) % tx # the smallest we can get by subtracting tx from ty
return tx == sx and ty == sy | reaching-points | [Python3] [Impossible not to understand] Intuitive Method with Detailed Explanation | JackieWDo | 0 | 1 | reaching points | 780 | 0.324 | Hard | 12,694 |
https://leetcode.com/problems/reaching-points/discuss/2814772/Speed-up-via-edge-cases-for-19-ms-or-less.-%3A) | class Solution:
def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:
# if both of sx, sy are even, only evens can be generated, but not all evens can be generated
# as such, if you have any odds only in the end target, return false
if (sx % 2 == sy % 2 == 0) and ((tx % 2 != 0) or (ty % 2 != 0)) :
return False
# or if you have matches that are exactly equal, return True
elif (sx == sy == tx == ty) or (sx == tx and sy == ty) :
return True
else :
# otherwise, return the euclidean gcd procession
return self.euclidean_gcd(sx, sy, tx, ty)
def euclidean_gcd(self, sx, sy, tx, ty) :
# loop while tx and ty are greater than or equaal to their target
# count = 0
# loop zero printing can be commented out
# self.print_euclidean_progression(sx, sy, tx, ty, count)
while (tx >= sx) and (ty >= sy) :
# if these are equal to each other, break
if tx == ty :
break
# otherwise, depending on which is larger
elif tx > ty :
# if the other target is above their start still
if ty > sy :
# modulo reduction to remainder
tx %= ty
else :
# if it is at the target, return the modulo result for gcd
return (tx - sx) % ty == 0
else :
# see above section for logic breakdown
if tx > sx :
ty %= tx
else :
return (ty - sy) % tx == 0
# increment count
# count += 1
# loop repeats with new values
# self.print_euclidean_progression(sx, sy, tx, ty, count)
# either you broke early due to tx == ty or you completed thee loop when they are less than the valuation
# could still be the case that sx == tx and sy == ty
# handled by above edge cases for non-loop progression variant
# return (sx == tx and sy == ty)
return False
def print_euclidean_progression(self, sx, sy, tx, ty, count) :
print("At count ", count, " the values of sx, sy are ", (sx, sy), " and the values of tx, ty are ", (tx, ty)) | reaching-points | Speed up via edge cases for 19 ms or less. :) | laichbr | 0 | 6 | reaching points | 780 | 0.324 | Hard | 12,695 |
https://leetcode.com/problems/rabbits-in-forest/discuss/838445/Python-3-or-Hash-Table-1-liner-or-Explanations | class Solution:
def numRabbits(self, answers: List[int]) -> int:
return sum((key+1) * math.ceil(freq / (key+1)) if key+1 < freq else key+1 for key, freq in collections.Counter(answers).items()) | rabbits-in-forest | Python 3 | Hash Table 1 liner | Explanations | idontknoooo | 1 | 178 | rabbits in forest | 781 | 0.552 | Medium | 12,696 |
https://leetcode.com/problems/rabbits-in-forest/discuss/838445/Python-3-or-Hash-Table-1-liner-or-Explanations | class Solution:
def numRabbits(self, answers: List[int]) -> int:
ans, cnt = 0, collections.Counter(answers)
for key, freq in cnt.items():
if key + 1 < freq: ans += (key+1) * math.ceil(freq / (key+1))
else: ans += key+1
return ans | rabbits-in-forest | Python 3 | Hash Table 1 liner | Explanations | idontknoooo | 1 | 178 | rabbits in forest | 781 | 0.552 | Medium | 12,697 |
https://leetcode.com/problems/rabbits-in-forest/discuss/2656728/Python-or-Counter | class Solution:
def numRabbits(self, answers: List[int]) -> int:
freqs = Counter(answers)
total = 0
for ans, freq in freqs.items():
total += (ceil(freq / (ans + 1)))*(ans + 1)
return total | rabbits-in-forest | Python | Counter | on_danse_encore_on_rit_encore | 0 | 3 | rabbits in forest | 781 | 0.552 | Medium | 12,698 |
https://leetcode.com/problems/rabbits-in-forest/discuss/2554810/Python-simple-to-understand-using-hashmap-O(n) | class Solution:
def numRabbits(self, answers: List[int]) -> int:
d = defaultdict(int)
for i in answers:
d[i] += 1
res = 0
for i in d:
res += ceil(d[i] / (i+1)) * (i+1)
return res | rabbits-in-forest | Python simple to understand using hashmap O(n) | rjnkokre | 0 | 19 | rabbits in forest | 781 | 0.552 | Medium | 12,699 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.