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/car-fleet/discuss/1875553/Python-easy-to-read-and-understand-or-sorting | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
n = len(position)
time = []
nums = sorted(zip(position, speed), reverse=True)
for x, y in nums:
time.append((target-x) / y)
ans, prev = 0, 0
for i in range(n):
if time[i] > prev:
ans += 1
prev = time[i]
return ans | car-fleet | Python easy to read and understand | sorting | sanial2001 | 1 | 128 | car fleet | 853 | 0.501 | Medium | 13,900 |
https://leetcode.com/problems/car-fleet/discuss/2778734/Simple-Python3-Implementation | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
values = [[position[i], (target - position[i]) / speed[i]] for i in range(len(position))]
stack = []
for car in sorted(values):
while len(stack) and stack[-1][1] <= car[1]:
stack.pop()
stack.append(car)
return len(stack) | car-fleet | Simple Python3 Implementation | PartialButton5 | 0 | 7 | car fleet | 853 | 0.501 | Medium | 13,901 |
https://leetcode.com/problems/car-fleet/discuss/2640964/Python-greedy-solution-with-sort | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
position_time = []
for i in range(len(position)):
time = (target - position[i]) / speed[i]
position_time.append((position[i], time))
position_time.sort(key = lambda x: x[0], reverse = True)
print(position_time)
res = len(position)
prev_time = position_time[0][1]
for i in range(1, len(position)):
time = position_time[i][1]
if time <= prev_time:
res -= 1
else:
prev_time = time
return res | car-fleet | Python greedy solution with sort | michaelniki | 0 | 4 | car fleet | 853 | 0.501 | Medium | 13,902 |
https://leetcode.com/problems/car-fleet/discuss/2601404/Python-Readable-solution | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
# sort the positions
position_speed = sorted(zip(position, speed), reverse=True)
# get the arrival time of all cars (distance_to_go / speed)
arrivals = [(target - position) * (1/speed) for position, speed in position_speed]
# get the maximum amount of fleets we would have if reach target independently
fleets = len(position)
# iterate over all arrival times and compare to the car further down the road
# skip first car in order to be able to compare to something
# NOTE: idx is automatically pointing at the car before us, as we start at element 1
for idx, time in enumerate(arrivals[1:]):
# we arrive earlier or at the same time as car before us, so we make a fleet
# and need to adapt our arrival time
if time <= arrivals[idx]:
fleets -= 1
arrivals[idx+1] = arrivals[idx]
return fleets | car-fleet | [Python] - Readable solution | Lucew | 0 | 63 | car fleet | 853 | 0.501 | Medium | 13,903 |
https://leetcode.com/problems/car-fleet/discuss/2598994/Python-sorting-stack-Solution | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
# pairs: (pos,speed)
stack = []
pairs = sorted([(position[i],speed[i]) for i in range(len(position))])
for i in range(len(pairs) - 1,-1,-1):
stack.append((target - pairs[i][0]) / pairs[i][1])
if len(stack) >= 2 and stack[-1] <= stack[-2]:
# don't use while here, since a car could only collide with the car right in front of it
stack.pop()
return len(stack) | car-fleet | Python sorting stack Solution | al5861 | 0 | 49 | car fleet | 853 | 0.501 | Medium | 13,904 |
https://leetcode.com/problems/car-fleet/discuss/1989844/Python-or-O(nlogn)-or-98-faster-or-Commented | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
distSpeed = []
stack = []
# Create an List of tuples which contains (position, speed) values.
for i in range(len(position)):
distSpeed.append((position[i],speed[i]))
# Sort the array as the car which are behind will never be able to overtake the car ahead all they can do is to join the fleet.
distSpeed = sorted(distSpeed, reverse=True)
# Check if the time taken is more than the car ahead if so than we have a new fleet else if the time taken is less than the
# Car ahead it will join the same fleet so the car can basically be ignored.
# time taken = distance / speed
for dist, speed in distSpeed:
distance = target-dist
if not stack or (distance/speed)>stack[-1]:
stack.append(distance/speed)
return len(stack) | car-fleet | Python | O(nlogn) | 98% faster | Commented | CSociety | 0 | 90 | car fleet | 853 | 0.501 | Medium | 13,905 |
https://leetcode.com/problems/car-fleet/discuss/1973327/Optimal-and-Concise-Solution | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
data = [(target - position[i], speed[i]) for i in range(len(position))]
data.sort(key=lambda x:x[0])
stack = []
for distance, speed in data:
time = distance / speed
if not stack or time > stack[-1]:
stack.append(time)
return len(stack) | car-fleet | Optimal & Concise Solution | EdwinJagger | 0 | 44 | car fleet | 853 | 0.501 | Medium | 13,906 |
https://leetcode.com/problems/car-fleet/discuss/477860/python-solution | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
n = len(position)
xv = sorted(zip(position,speed))
ans = n
for i in range(n-2,-1,-1):
if xv[i][1]>xv[i+1][1]: # if the car behind goes faster
t_fleet = (xv[i+1][0]-xv[i][0])/(xv[i][1]-xv[i+1][1]) # time when the car behind catches the one in front
if xv[i][0]+xv[i][1]*t_fleet<=target: # if the catch-up is before the target position
ans -= 1
xv[i] = xv[i+1] # update the state of the car behind by the state of the car in front
return ans | car-fleet | python solution | felicia1994 | 0 | 96 | car fleet | 853 | 0.501 | Medium | 13,907 |
https://leetcode.com/problems/car-fleet/discuss/1529278/python3-O(NlogN) | class Solution: # O(NlogN)
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
stack = [] # no. of fleet
# pair of distance and speed to sort it
pair = [(p,s) for p,s in zip(position,speed) ]
# sort the pair based on positions and travesing from reverse order
for p,s in sorted(pair)[::-1]:
# find the time
t = (target - p) /s
stack.append(t)
if len(stack) >= 2 and stack[-1] <= stack[-2]: # fleet
stack.pop()
return len(stack)
```
feel free to ask Q...
#happytohelpu | car-fleet | python3 - O(NlogN) | Shubham_Muramkar | -1 | 94 | car fleet | 853 | 0.501 | Medium | 13,908 |
https://leetcode.com/problems/k-similar-strings/discuss/321201/three-solutions-of-this-problem-good-for-understanding-DFS-DFS-with-memo-and-BFS | class Solution:
# DFS
def kSimilarity(self, A: str, B: str) -> int:
N = len(A)
def dfs(A, B, pos):
if A == B:
return 0
while A[pos] == B[pos]:
pos += 1
minCnt = float('inf')
for i in range(pos + 1, N):
if B[i] == A[pos] and B[i] != A[i]:
B[i], B[pos] = B[pos], B[i]
tmp = dfs(A, B, pos + 1) + 1
minCnt = min(tmp, minCnt)
B[i], B[pos] = B[pos], B[i]
return minCnt
return dfs(list(A), list(B), 0)
# DFS with memorization
def kSimilarity1(self, A: str, B: str) -> int:
N = len(A)
def dfs(A, B, pos):
sB = ''.join(B)
if sB in map:
return map[sB]
if A == B:
return 0
while A[pos] == B[pos]:
pos += 1
minCnt = float('inf')
for i in range(pos + 1, N):
if B[i] == A[pos] and B[i] != A[i]:
B[i], B[pos] = B[pos], B[i]
tmp = dfs(A, B, pos + 1) + 1
minCnt = min(tmp, minCnt)
B[i], B[pos] = B[pos], B[i]
map[sB] = minCnt
return minCnt
map = collections.defaultdict()
return dfs(list(A), list(B), 0)
# BFS
def kSimilarity2(self, A: str, B: str) -> int:
N = len(B)
q = collections.deque([B])
visited = set(B)
cnt = 0
pos = 0
while q:
qSize = len(q)
for _ in range(qSize):
cur = q.popleft()
if cur == A:
return cnt
pos = 0
while cur[pos] == A[pos]:
pos += 1
lCur = list(cur)
for i in range(pos + 1, N):
if lCur[i] == A[pos] and lCur[i] != A[i]:
lCur[i], lCur[pos] = lCur[pos], lCur[i]
sCur = ''.join(lCur)
if sCur not in visited:
q.append(sCur)
visited.add(sCur)
lCur[i], lCur[pos] = lCur[pos], lCur[i]
cnt += 1
return cnt | k-similar-strings | three solutions of this problem, good for understanding DFS, DFS with memo and BFS | shchshhappy | 21 | 2,900 | k similar strings | 854 | 0.401 | Hard | 13,909 |
https://leetcode.com/problems/k-similar-strings/discuss/2385252/Python-BFS-Solution-(fully-explained-and-commented) | class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
#the deque keeps track of the set of strings that we want to perform swaps on
#at the start, the deque contains only s1
deque = collections.deque([s1])
#this set wasn't mentioned in the "intuition" part. it helps us avoid doing repeated work by adding the same strings to our deque
seen = set()
answ=0 #counter for the number of "swaps" done so far
while deque:
for _ in range(len(deque)): #loops through each string in the deque
string = deque.popleft() #gets the first string in the deque
if string ==s2: return answ
#finds the first non-matching letter in s1
#this satisfies condition 1 of a "useful" swap
#ex: this would be s1[3] in the above example
i=0
while string[i]==s2[i]:
i+=1
#checks all the other letters for potential swaps
for j in range(i+1, len(string)):
if string[i]==s2[j]!=s1[j]: #checks conditions 2 and 3 of a useful swap
#swaps the letters at positions i and j
new = string[:i] + string[j] + string[i+1:j] + string[i] + string[j+1:]
#adds the "new string" if it was not previously added
if new not in seen:
seen.add(new)
deque.append(new)
#record that one more swap was done for each string in the deque
answ+=1 | k-similar-strings | Python BFS Solution (fully explained & commented) | ahil_io | 16 | 626 | k similar strings | 854 | 0.401 | Hard | 13,910 |
https://leetcode.com/problems/k-similar-strings/discuss/1521457/Python3-bfs | class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
ans = 0
seen = {s1}
queue = deque([s1])
while queue:
for _ in range(len(queue)):
s = queue.popleft()
if s == s2: return ans
for i in range(len(s)):
if s[i] != s2[i]:
for j in range(i+1, len(s)):
if s[j] != s2[j] and s[j] == s2[i]:
ss = s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]
if ss not in seen:
seen.add(ss)
queue.append(ss)
break
ans += 1 | k-similar-strings | [Python3] bfs | ye15 | 3 | 381 | k similar strings | 854 | 0.401 | Hard | 13,911 |
https://leetcode.com/problems/k-similar-strings/discuss/2599050/Python-Easy-to-understand-backtracking | class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
n = len(s1)
arr, s2_arr = list(s1), list(s2)
min_steps = float('inf')
def helper(steps,i):
nonlocal min_steps
if steps >= min_steps: return
if i == n:
min_steps = min(min_steps, steps)
return
# if character at index i is already correct
if arr[i] == s2[i]:
helper(steps,i+1)
return
for j in range(i+1,n):
'''
skip if:
1. characters at i and j are the same
2. character at j is not what we need at i
3. character at j is already correctly placed
'''
if arr[i] == arr[j] or arr[j] != s2[i] or arr[j] == s2[j]: continue
arr[i], arr[j] = arr[j], arr[i]
helper(steps+1,i+1)
arr[i], arr[j] = arr[j], arr[i]
helper(0,0)
return min_steps | k-similar-strings | [Python] Easy to understand backtracking | fomiee | 0 | 70 | k similar strings | 854 | 0.401 | Hard | 13,912 |
https://leetcode.com/problems/k-similar-strings/discuss/1840466/Easy-DP-Solution-using-Cache | class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
@cache
def dfs(a,b,pos):
if a==b :
return 0
while a[pos]==b[pos] :
pos+=1
a,b=list(a),list(b)
ans=10**18
for i in range(pos+1,len(a)):
if b[i]==a[pos] and b[i]!=a[i] :
b[i],b[pos]=b[pos],b[i]
ans=min(ans,dfs(tuple(a),tuple(b),pos+1)+1)
b[i],b[pos]=b[pos],b[i]
return ans
return dfs(tuple(s1),tuple(s2),0) | k-similar-strings | Easy DP Solution using Cache | P3rf3ct0 | 0 | 319 | k similar strings | 854 | 0.401 | Hard | 13,913 |
https://leetcode.com/problems/k-similar-strings/discuss/464826/python-32ms-solution-faster-than-100-with-extremely-small-memory | class Solution:
def kSimilarity(self, A: str, B: str) -> int:
la = []
lb = []
for a, b in zip(A, B):
if a != b:
la.append(a)
lb.append(b)
queue = {''.join(la): 0}
while lb:
q = {}
for pre, swap in queue.items():
if pre[-1] != lb[-1]:
eq = []
for i, ch in enumerate(pre[:-1]):
if ch == lb[-1] and lb[i] != ch:
eq.append(i)
if lb[i] == pre[-1]:
eq = [i]
break
for i in eq:
tmp = pre[:i] + pre[-1] + pre[i + 1:-1]
q[tmp] = min(swap + 1, q.get(tmp, float('inf')))
else:
q[pre[:-1]] = min(swap, q.get(pre[:-1], float('inf')))
lb.pop()
queue = q
return list(queue.values())[0] | k-similar-strings | python 32ms solution faster than 100% with extremely small memory | yutaoli | 0 | 195 | k similar strings | 854 | 0.401 | Hard | 13,914 |
https://leetcode.com/problems/score-of-parentheses/discuss/2299821/Python-or-faster-than-83-or-easy-understanding-or-explaining-with-comments | class Solution:
def scoreOfParentheses(self, s: str) -> int:
stk = [0] # temp value to help us
for char in s:
if char == '(':
stk.append(0) # new parent: current sum = 0
else:
# An expression will be closed
# Find its value: either 1 for empty () or 2 * its sub-expressions
# we can calc both with a simple max()
value = max(2 * stk.pop(), 1)
# Add the expression sum to its parent current sum
# Assume we have expression E that is (CHD)
# where C, H, D are valid-subexpressions with values 5, 10, 4
# then E is (5+10+4) = (19) = 38
# Every time we finish an expression, we add its value to its parent
# get the parent and update its sum with a finished sub-expression
stk[-1] += value
return stk.pop()
``` | score-of-parentheses | Python | faster than 83% | easy-understanding | explaining with comments | Saiko15 | 3 | 130 | score of parentheses | 856 | 0.65 | Medium | 13,915 |
https://leetcode.com/problems/score-of-parentheses/discuss/1080614/Python.-Super-simple-O(1)-space-solution. | class Solution:
def scoreOfParentheses(self, S: str) -> int:
res, balance = 0, 0
for index, par in enumerate(S):
balance += 1 if par == "(" else -1
if index and S[index - 1] + par == "()":
res += 2 ** balance
return res | score-of-parentheses | Python. Super simple O(1) space solution. | m-d-f | 3 | 443 | score of parentheses | 856 | 0.65 | Medium | 13,916 |
https://leetcode.com/problems/score-of-parentheses/discuss/939553/Python3-stack-O(N) | class Solution:
def scoreOfParentheses(self, S: str) -> int:
ans, stack = 0, []
for c in S:
if c == "(":
stack.append(ans)
ans = 0
else: ans = max(1, 2*ans) + stack.pop()
return ans | score-of-parentheses | [Python3] stack O(N) | ye15 | 3 | 131 | score of parentheses | 856 | 0.65 | Medium | 13,917 |
https://leetcode.com/problems/score-of-parentheses/discuss/939553/Python3-stack-O(N) | class Solution:
def scoreOfParentheses(self, S: str) -> int:
ans = k = 0
for i in range(len(S)):
k += 1 if S[i] == "(" else -1
if S[i-1:i+1] == "()": ans += 2**k
return ans | score-of-parentheses | [Python3] stack O(N) | ye15 | 3 | 131 | score of parentheses | 856 | 0.65 | Medium | 13,918 |
https://leetcode.com/problems/score-of-parentheses/discuss/1080672/Python-or-T-O(n)-S-O(1)-or-Beats-94 | class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
res, balance = 0, 0
for index, ch in enumerate(S):
balance = balance+1 if ch == '(' else balance-1
if index and S[index-1] + ch == '()':
res += 2 ** balance
return res | score-of-parentheses | Python | T-O(n), S-O(1) | Beats 94% | vsahoo | 1 | 101 | score of parentheses | 856 | 0.65 | Medium | 13,919 |
https://leetcode.com/problems/score-of-parentheses/discuss/2658545/Python-Stack-Implementation-O(N)-time-complexity | class Solution:
def scoreOfParentheses(self, s: str) -> int:
stack=[]
for i in s:
if i=="(":
stack.append("(")
else:
if stack[-1]=="(":
stack.pop()
stack.append(1)
else:
sum1=0
while stack[-1]!="(":
a=stack.pop()
sum1+=a
stack.pop()
stack.append(2*sum1)
return sum(stack) | score-of-parentheses | Python - Stack Implementation O(N) time complexity | utsa_gupta | 0 | 5 | score of parentheses | 856 | 0.65 | Medium | 13,920 |
https://leetcode.com/problems/score-of-parentheses/discuss/2656497/Score-of-Parentheses-oror-Python3-oror-Stack | class Solution:
def scoreOfParentheses(self, s: str) -> int:
stack=[]
for i in range(len(s)):
if s[i]=='(':
stack.append(-1)
else:
if stack[-1]==-1:
stack.pop()
stack.append(1)
else:
t=0
while stack[-1]!=-1:
t+=stack.pop()
stack.pop()
stack.append(2*t)
return sum(stack) | score-of-parentheses | Score of Parentheses || Python3 || Stack | shagun_pandey | 0 | 5 | score of parentheses | 856 | 0.65 | Medium | 13,921 |
https://leetcode.com/problems/score-of-parentheses/discuss/2656405/easy-python-solution-using-stack | class Solution:
def scoreOfParentheses(self, s: str) -> int:
s1=[]
for i in s:
if i=="(":
s1.append(i)
else:
if s1[-1]=="(":
s1.pop()
s1.append(1)
else:
sumi=0
while s1[-1]!="(":
sumi+=s1.pop()
s1.pop()
s1.append(2*sumi)
return sum(s1) | score-of-parentheses | easy python solution using stack | insane_me12 | 0 | 5 | score of parentheses | 856 | 0.65 | Medium | 13,922 |
https://leetcode.com/problems/score-of-parentheses/discuss/2656182/python-easy-solution-in-0(n)-and-space-in0(1)-with-explaination | class Solution:
def scoreOfParentheses(self, s: str) -> int:
cur=0
stack=[] #making stack
for i in s:
if i=='(':
stack.append(cur) # if found '(' then push cur i.e 0 in stack
cur=0 # make cur as 0 again
else:
cur=stack.pop()+max(cur*2,1) #if not found open "(" then pop cur from stack and add with the maximum of cur and 1
return cur | score-of-parentheses | python easy solution in 0(n) and space in0(1) with explaination | tush18 | 0 | 9 | score of parentheses | 856 | 0.65 | Medium | 13,923 |
https://leetcode.com/problems/score-of-parentheses/discuss/2183901/Best-Recursive-Solution-oror-No-Stack-Used-oror-Easy-Approach | class Solution:
def __init__(self):
self.i = 0
def scoreOfParentheses(self, s: str) -> int:
score = 0
length = len(s)
while self.i < length:
bracket = s[self.i]
self.i += 1
if bracket == "(":
if s[self.i] == ")":
score += 1
self.i += 1
else:
score += 2*self.scoreOfParentheses(s)
else:
return score
return score | score-of-parentheses | Best Recursive Solution || No Stack Used || Easy Approach | Vaibhav7860 | 0 | 45 | score of parentheses | 856 | 0.65 | Medium | 13,924 |
https://leetcode.com/problems/score-of-parentheses/discuss/1858473/Terrible-but-Solution-that-doesn't-really-use-any-algorithm-or-database-concepts | class Solution:
def scoreOfParentheses(self, s: str) -> int:
arr = [""]*len(s)
i = len(s)-1
openings = 0
while i >= 0:
if s[i] == ")":
if s[i-1] == "(":
arr[i-1] = "+1"
else:
arr[i] = ")"
j = i
closings = 1
while closings > 0:
j-=1
if s[j] == ")":
closings += 1
elif s[j] == "(":
closings -= 1
arr[j] = "2*("
i-=1
equation = "".join(arr) | score-of-parentheses | Terrible but Solution that doesn't really use any algorithm or database concepts | bomb483 | 0 | 12 | score of parentheses | 856 | 0.65 | Medium | 13,925 |
https://leetcode.com/problems/score-of-parentheses/discuss/1858065/Readable-Python-solution-with-explanation-faster-than-99.91 | class Solution:
def scoreOfParentheses(self, s: str) -> int:
# 1st part
# Let's create a_plus_b list.
# s == "(())(()()(()))()"
# a_plus_b == ['(())', '(()()(()))', '()']
a_plus_b = []
count = 0
start = 0
for i in range(len(s)):
if s[i] == "(":
count += 1
elif s[i] == ")":
count -= 1
if count == 0:
a_plus_b.append(s[start:i + 1])
start = i + 1
# 2nd part
# We have to iterate over each sub_string in a_plus_b list.
solution = 0
for sub_string in a_plus_b:
sub_solution = 0
# We have to iterate over each parenthesis (p) in sub_string.
# We simply count p, count = 0
# count += 1 if p == "("
# count -= 1 if p == ")"
# also if p == ")" we have to add 2**count to sub_solution
# but only if previous parnethesis was "(", that's what check_point is used for
# "( ( ) ( ) ( ( ) ) )" p
# 1 2 1 2 1 2 3 2 1 0 count
# + + + x x + valid as previous parenthesis is "("
# x invalid as previous parentehsis is ")"
# if valid (+):
# sub_solution += 2**count
count = 0
check_point = 1
for p in sub_string:
if p == "(":
count += 1
if check_point == 0:
check_point = 1
elif p == ")":
count -= 1
if check_point == 1:
solution += 2 ** count
check_point = 0
solution += sub_solution
sub_solution = 0
return solution | score-of-parentheses | Readable Python solution with explanation [faster than 99.91%] | zebra-f | 0 | 23 | score of parentheses | 856 | 0.65 | Medium | 13,926 |
https://leetcode.com/problems/score-of-parentheses/discuss/1857979/Runtime%3A-28-ms-faster-than-94.45-of-Python3.-O(1)-extra-memory-usage | class Solution:
def scoreOfParentheses(self, s: str) -> int:
multiplier = 1
score = 0
closing = False
for elem in s:
if elem == "(":
multiplier <<= 1
closing = False
else:
multiplier >>= 1
score += multiplier * (not closing)
closing = True
return score | score-of-parentheses | Runtime: 28 ms, faster than 94.45% of Python3. O(1) extra memory usage | mg1999 | 0 | 24 | score of parentheses | 856 | 0.65 | Medium | 13,927 |
https://leetcode.com/problems/score-of-parentheses/discuss/1857206/Python3-Solution-with-using-stack | class Solution:
def scoreOfParentheses(self, s: str) -> int:
stack = [0]
for c in s:
if c == '(':
stack.append(0)
else:
elem = stack.pop()
stack[-1] += max(2 * elem, 1)
return stack[-1] | score-of-parentheses | [Python3] Solution with using stack | maosipov11 | 0 | 8 | score of parentheses | 856 | 0.65 | Medium | 13,928 |
https://leetcode.com/problems/score-of-parentheses/discuss/1856884/Python-or-TC-O(N)SC-O(N)-or-faster-than-98.6-or-Easy-to-understand-2-diff-approaches | class Solution(object):
def scoreOfParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
score = 0
for par in s:
if par == "(":
stack.append(score)
score = 0
else:
score += stack.pop()+ max(score,1)
return score | score-of-parentheses | Python | TC-O(N)/SC-O(N) | faster than 98.6% | Easy to understand 2 diff approaches | Patil_Pratik | 0 | 26 | score of parentheses | 856 | 0.65 | Medium | 13,929 |
https://leetcode.com/problems/score-of-parentheses/discuss/1856884/Python-or-TC-O(N)SC-O(N)-or-faster-than-98.6-or-Easy-to-understand-2-diff-approaches | class Solution(object):
def scoreOfParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
score = 0
for par in s:
val = 0
if par == "(":
stack.append(0)
else:
while stack[-1] != 0:
val += stack.pop()
val = max(2*val, 1)
stack.pop()
stack.append(val)
while stack:
score += stack.pop()
return score | score-of-parentheses | Python | TC-O(N)/SC-O(N) | faster than 98.6% | Easy to understand 2 diff approaches | Patil_Pratik | 0 | 26 | score of parentheses | 856 | 0.65 | Medium | 13,930 |
https://leetcode.com/problems/score-of-parentheses/discuss/1856659/Python-Simple-Python-Solution-Using-Stack-and-Iterative-Approach | class Solution:
def scoreOfParentheses(self, s: str) -> int:
score = 0
stack = []
for i in s:
if i == '(':
stack.append(i)
else:
top = stack.pop()
if top == '(' and i == ')':
stack.append(1)
else:
score = 0
while top != '(':
score = score + top
top = stack.pop()
stack.append(2*score)
return sum(stack) | score-of-parentheses | [ Python ] ✔✔ Simple Python Solution Using Stack and Iterative Approach 🔥✌ | ASHOK_KUMAR_MEGHVANSHI | 0 | 40 | score of parentheses | 856 | 0.65 | Medium | 13,931 |
https://leetcode.com/problems/score-of-parentheses/discuss/1856566/Python3-96.62-or-Recurssion-and-Stack-or-Well-explained-and-Easy-Implementation | class Solution:
def scoreOfParentheses(self, s: str) -> int:
if not s:
return 0
# use to stack to cancel the left most parentheses
st = []
for i, c in enumerate(s):
# add any left
if c == '(':
st.append(1)
else:
# pop right
st.pop()
# if stack is empty, then we find where is the right part for the left most parentheses
if not st:
# if there is nothing in between, and 1 as base case
if i == 1:
return 1 + self.scoreOfParentheses(s[2:])
# otherwise, recursive to solve the subproblem
return 2 * self.scoreOfParentheses(s[1:i]) + self.scoreOfParentheses(s[i+1:]) | score-of-parentheses | Python3 96.62% | Recurssion & Stack | Well explained & Easy Implementation | doneowth | 0 | 18 | score of parentheses | 856 | 0.65 | Medium | 13,932 |
https://leetcode.com/problems/score-of-parentheses/discuss/1677933/No-Stack-Very-Easy-to-Understand-O(n)-and-O(1) | class Solution(object):
def scoreOfParentheses(self, S):
depth = -1
total = 0
for index, element in enumerate(S):
if element == '(':
depth += 1
elif element == ')' and S[index - 1] == '(':
total += 2 ** depth
depth -= 1
else:
depth -= 1
return total | score-of-parentheses | No Stack - Very Easy to Understand - O(n) & O(1) | leeik | 0 | 47 | score of parentheses | 856 | 0.65 | Medium | 13,933 |
https://leetcode.com/problems/score-of-parentheses/discuss/1677933/No-Stack-Very-Easy-to-Understand-O(n)-and-O(1) | class Solution:
def scoreOfParentheses(self, s: str) -> int:
total_sum = 0
multiplier = 1
for index, value in enumerate(s):
if value == '(':
if s[index + 1] == ')':
total_sum += multiplier * 1
else:
multiplier *= 2
else:
if s[index - 1] == ')':
multiplier //= 2
return total_sum | score-of-parentheses | No Stack - Very Easy to Understand - O(n) & O(1) | leeik | 0 | 47 | score of parentheses | 856 | 0.65 | Medium | 13,934 |
https://leetcode.com/problems/score-of-parentheses/discuss/1621479/Python-Easy-Solution-or-Faster-than-99 | class Solution:
def scoreOfParentheses(self, s: str) -> int:
# Approach 1:
stck = [0]
for brac in s:
if brac == "(":
stck.append(0)
else:
fir = stck.pop()
sec = stck.pop()
stck.append(sec+max(2*fir, 1))
return stck.pop()
# Approach 2:
stck = [0]
scre = 0
for brac in s:
if brac == "(":
stck.append(0)
else:
fir = stck.pop()
stck[-1] += max(2*fir, 1)
return stck.pop() | score-of-parentheses | Python Easy Solution | Faster than 99% ✔ | leet_satyam | 0 | 105 | score of parentheses | 856 | 0.65 | Medium | 13,935 |
https://leetcode.com/problems/score-of-parentheses/discuss/1191550/Python3-simple-solution-using-stack | class Solution:
def scoreOfParentheses(self, S: str) -> int:
z = [0]
for i in S:
if i == '(':
z.append(0)
else:
x = z.pop()
z[-1] += max(2*x,1)
return z[0] | score-of-parentheses | Python3 simple solution using stack | EklavyaJoshi | 0 | 82 | score of parentheses | 856 | 0.65 | Medium | 13,936 |
https://leetcode.com/problems/score-of-parentheses/discuss/1081769/Python3-easy-to-understand | class Solution:
def scoreOfParentheses(self, S: str) -> int:
if not S:
return 0
n = len(S)
power = deque()
val = {} # {index:val}
res = 0
for i in range(n):
if S[i] == "(":
power.append(i)
else:
x = power.pop()
if x+1 == i:
val[i-1] = 1
else:
for k,v in val.items():
if x < k:
val[k] *= 2
return sum(val.values()) | score-of-parentheses | Python3 easy to understand | 2017JAMESFU | 0 | 57 | score of parentheses | 856 | 0.65 | Medium | 13,937 |
https://leetcode.com/problems/score-of-parentheses/discuss/843810/Intuitive-approach-by-accumulating-number-of-left-parenthesis-and-flag-to-calculate-score-or-not | class Solution:
def scoreOfParentheses(self, S: str) -> int:
left_parenthesis_count = 0
score = 0
score_flag = False
for c in S:
if c == '(':
left_parenthesis_count += 1
score_flag = True
else:
left_parenthesis_count -= 1
if score_flag:
score += pow(2, left_parenthesis_count)
score_flag = False
return score | score-of-parentheses | Intuitive approach by accumulating number of left parenthesis and flag to calculate score or not | puremonkey2001 | 0 | 50 | score of parentheses | 856 | 0.65 | Medium | 13,938 |
https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/1265778/Python3-greedy-(priority-queue) | class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:
ans, rsm = inf, 0
pq = [] # max-heap
for q, w in sorted(zip(quality, wage), key=lambda x: x[1]/x[0]):
rsm += q
heappush(pq, -q)
if len(pq) > k: rsm += heappop(pq)
if len(pq) == k: ans = min(ans, rsm * w/q)
return ans | minimum-cost-to-hire-k-workers | [Python3] greedy (priority queue) | ye15 | 1 | 83 | minimum cost to hire k workers | 857 | 0.521 | Hard | 13,939 |
https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/2637950/Python3-or-Priority-Queue | class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:
n=len(wage)
arr=[[wage[i]/quality[i],quality[i]] for i in range(n)]
arr.sort(key=lambda x:x[0])
kSmallest=0
pq=[]
for i in range(k):
heapq.heappush(pq,-arr[i][1])
kSmallest+=arr[i][1]
minCost=arr[k-1][0]*kSmallest
for c in range(k,n):
if pq and abs(pq[0])>arr[c][1]:
qRem=-heappop(pq)
kSmallest-=qRem
kSmallest+=arr[c][1]
heappush(pq,-arr[c][1])
minCost=min(minCost,arr[c][0]*kSmallest)
return minCost | minimum-cost-to-hire-k-workers | [Python3] | Priority Queue | swapnilsingh421 | 0 | 6 | minimum cost to hire k workers | 857 | 0.521 | Hard | 13,940 |
https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/2609100/Python3-Solution-or-O(nlogn)-or-Heap | class Solution:
def mincostToHireWorkers(self, Q, W, K):
ans, csum, H = float('inf'), 0, []
for q, w in sorted(zip(Q, W), key = lambda x: x[1] / x[0]):
csum += q
heapq.heappush(H, -q)
if len(H) > K: csum += heapq.heappop(H)
if len(H) == K: ans = min(ans, csum * w / q)
return ans | minimum-cost-to-hire-k-workers | ✔ Python3 Solution | O(nlogn) | Heap | satyam2001 | 0 | 14 | minimum cost to hire k workers | 857 | 0.521 | Hard | 13,941 |
https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/1258759/Python-Solution-using-heap | class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], K: int) -> float:
workers=[]
for w,q in zip(wage, quality):
workers.append([float(w) / q, q] )
workers.sort()
print(workers)
res = float('inf')
qsum = 0
heap = []
for r, q in workers:
heapq.heappush(heap, -q)
#print(heap)
qsum += q
if len(heap) > K:
qsum += heapq.heappop(heap)
if len(heap) == K:
res = min(res, qsum * r)
print(heap)
return res | minimum-cost-to-hire-k-workers | Python Solution using heap | jaipoo | 0 | 130 | minimum cost to hire k workers | 857 | 0.521 | Hard | 13,942 |
https://leetcode.com/problems/mirror-reflection/discuss/2376355/Python3-oror-4-lines-geometry-w-explanation-oror-TM%3A-9281 | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
L = lcm(p,q)
if (L//q)%2 == 0:
return 2
return (L//p)%2 | mirror-reflection | Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81% | warrenruud | 73 | 3,400 | mirror reflection | 858 | 0.633 | Medium | 13,943 |
https://leetcode.com/problems/mirror-reflection/discuss/2376355/Python3-oror-4-lines-geometry-w-explanation-oror-TM%3A-9281 | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
# L*G = p*q <=> L/q = p/G <=> L/p = q/G
G = gcd(p,q)
p//= G
q//= G
if p%2 == 0:
return 2
return q%2 | mirror-reflection | Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81% | warrenruud | 73 | 3,400 | mirror reflection | 858 | 0.633 | Medium | 13,944 |
https://leetcode.com/problems/mirror-reflection/discuss/939784/Beautiful-easy-solution(with-explanation) | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
def step(right, up, distance):
if distance == p:
return 1 if (up and right) else 2 if up else 0
elif distance > p:
return step(not right, not up, distance % p)
else:
return step(not right, up, distance+q)
return step(True, True, q) | mirror-reflection | Beautiful easy solution(with explanation) | code_much_more | 6 | 354 | mirror reflection | 858 | 0.633 | Medium | 13,945 |
https://leetcode.com/problems/mirror-reflection/discuss/2377770/Faster-than-100-python-users-oror-Easy-Python-Solution-oror-GCD-LCM-Solution | class Solution(object):
def gcd(self,a,b):
if a == 0:
return b
return self.gcd(b % a, a)
def lcm(self,a,b):
return (a / self.gcd(a,b))* b
def mirrorReflection(self, p,q):
lcm=self.lcm(p,q)
m=lcm//p
n=lcm//q
if n%2==0:
return 2
if m%2==0:
return 0
return 1
# basically you can just ignore the north wall and imagine the mirrors
# as two parallel mirrors with just extending east and west walls and the end points of east walls are made of 0 reflector then 1 reflector the oth the 1th and so onn....
# eventually we gotta find the point where m*p=n*q
# and we can find m and n by lcm of p and q
# now the consept is simple .....
# if number of extensions of q(ie n) is even that means the end reflection must have happened on west wall ie. reflector 2 else
# else there are two possibility reflector 1 or 0 which depends on the value of m(ie. the full fledged square extentions) if its even or odd | mirror-reflection | Faster than 100%😍🎆 python users || Easy Python Solution🤑 || GCD ,LCM Solution😎 | ChinnaTheProgrammer | 3 | 92 | mirror reflection | 858 | 0.633 | Medium | 13,946 |
https://leetcode.com/problems/mirror-reflection/discuss/2377324/Python-or-Java-or-Easy-Solution-using-simple-geometric-observation-or-Commented-code | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
'''
Using simple geometry and just by observing we can decide where
will the ray hit. for example:
p = 2, q = 1; the ray first meets 2nd receptor after it gets reflected
for 1 time
p = 3, q = 1; the ray first meets 1st receptor after it gets reflected
for 2 times.
From the given examples one can easly observe that
1:if p is even and q is odd, it'll surely hit 2nd receptor for the first
time
2:if both p and q is odd, it'll surely hit 1st receptor for the first time
'''
# base case if both p and q are equal, it will always hit receptor 1,
# irrespective of their nature
if p == q:
return 1
while p % 2 == 0 and q % 2 == 0:
p //= 2
q //= 2
if p % 2 == 1 and q % 2 == 0:
return 0
elif p % 2 == 1 and q % 2 == 1:
return 1
elif p % 2 == 0 and q % 2 == 1:
return 2 | mirror-reflection | Python | Java | Easy Solution using simple geometric observation | Commented code | __Asrar | 2 | 39 | mirror reflection | 858 | 0.633 | Medium | 13,947 |
https://leetcode.com/problems/mirror-reflection/discuss/2376238/Python-solution-using-directions | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
if p == q:
return 1
height = q
right, up = False, True
while 1:
if height + q == p:
if right and up:
return 1
elif not right and up:
return 2
else:
return 0
elif height + q < p:
height += q
right = not right
else:
height += q
height %= p
right = not right
up = not up | mirror-reflection | Python solution using directions | ToORu124124 | 2 | 205 | mirror reflection | 858 | 0.633 | Medium | 13,948 |
https://leetcode.com/problems/mirror-reflection/discuss/2376193/Python-Simple-and-Easy-Solution | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
while p%2 == 0 and q%2 == 0:
p = p/2
q = q/2
if p%2 == 0 and q%2 != 0:
return 2
elif p%2 != 0 and q%2 != 0:
return 1
return 0 | mirror-reflection | Python - Simple and Easy Solution | dayaniravi123 | 1 | 117 | mirror reflection | 858 | 0.633 | Medium | 13,949 |
https://leetcode.com/problems/mirror-reflection/discuss/2383445/Python-Solution-with-using-math | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
m, n = 1, 1
while p * m != q * n:
n += 1
m = n * q // p
"""
n - odd = > number of reflection - even = > right side (0 or 1)
"""
if m % 2 == 0 and n % 2 != 0:
return 0
if m % 2 != 0 and n % 2 != 0:
return 1
if m % 2 != 0 and n % 2 == 0:
return 2
return -1 | mirror-reflection | [Python] Solution with using math | maosipov11 | 0 | 8 | mirror reflection | 858 | 0.633 | Medium | 13,950 |
https://leetcode.com/problems/mirror-reflection/discuss/2380266/Fast-1-Line-Solution-(And-more-understandable-expanded-solution) | class Solution:
def mirrorReflection(self, length: int, dist: int) -> int:
return (lcm(length, dist) // length % 2) * ((lcm(length, dist) // dist - 1) % 2 + 1) | mirror-reflection | Fast 1 Line Solution (And more understandable expanded solution) | RobbyRivenbark | 0 | 38 | mirror reflection | 858 | 0.633 | Medium | 13,951 |
https://leetcode.com/problems/mirror-reflection/discuss/2380266/Fast-1-Line-Solution-(And-more-understandable-expanded-solution) | class Solution:
def mirrorReflection(self, length: int, dist: int) -> int:
common = 0
bounces = -1
while common < length or common % length != 0 :
common += dist
bounces += 1
cycles = common // length
if cycles % 2 == 0 :
return 0
return bounces % 2 + 1 | mirror-reflection | Fast 1 Line Solution (And more understandable expanded solution) | RobbyRivenbark | 0 | 38 | mirror reflection | 858 | 0.633 | Medium | 13,952 |
https://leetcode.com/problems/mirror-reflection/discuss/2380144/Easy-python-solution-or-Mirror-Reflection | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
if p % 2 == 0 and q % 2 != 0:
return 2
elif p % 2 != 0 and q % 2 == 0:
return 0
elif p % 2 != 0 and q % 2 != 0:
return 1
else:
if p == q:
return 1
else:
return self.mirrorReflection(p/2,q/2) | mirror-reflection | Easy python solution | Mirror Reflection | nishanrahman1994 | 0 | 15 | mirror reflection | 858 | 0.633 | Medium | 13,953 |
https://leetcode.com/problems/mirror-reflection/discuss/2378735/Python-3-Clear-solution | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
# x, y - first integer coordinates of ray
gcd = self._gcd(p, q)
x = p // gcd
y = q // gcd
up_flip = (y % 2 == 0)
right_flip = (x % 2 == 0)
if up_flip and right_flip:
raise RuntimeError('ray returned to the starting point')
if up_flip:
return 0
if right_flip:
return 2
return 1
def _gcd(self, a, b):
if a > b:
a, b = b, a
while b % a != 0:
tmp = a
a = b % a
b = tmp
return a | mirror-reflection | [Python 3] Clear solution | Deimvis | 0 | 38 | mirror reflection | 858 | 0.633 | Medium | 13,954 |
https://leetcode.com/problems/mirror-reflection/discuss/2377728/GolangPython-Solution | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
corners = {(0,1):0,
(p,1):1,
(p,0):2}
i = 0
j = 0
while True:
i+=q
j+=1
i = i % (2*p)
j = j % 2
if (i,j) in corners:
return corners[(i,j)] | mirror-reflection | Golang/Python Solution | vtalantsev | 0 | 23 | mirror reflection | 858 | 0.633 | Medium | 13,955 |
https://leetcode.com/problems/mirror-reflection/discuss/2377728/GolangPython-Solution | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
corners = {(0,1):0,
(p,1):1,
(0,0):2,
(p,0):2}
lcm = (p * q) // math.gcd(p , q) # Least common multiple
j = (lcm // q) % 2
i = lcm % (2*p)
return corners[(i,j)] | mirror-reflection | Golang/Python Solution | vtalantsev | 0 | 23 | mirror reflection | 858 | 0.633 | Medium | 13,956 |
https://leetcode.com/problems/mirror-reflection/discuss/2377397/Python-Intuitive-Solution | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
l = lcm(p,q)
if l//p % 2 == 0:
return 0
else:
return 2 if l//q %2 == 0 else 1 | mirror-reflection | Python Intuitive Solution | harsh30199 | 0 | 4 | mirror reflection | 858 | 0.633 | Medium | 13,957 |
https://leetcode.com/problems/mirror-reflection/discuss/2377224/Python-Fast-solution-(with-explanations) | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
reducedP, reducedQ = p, q
while True:
reducedPMod2, reducedQMod2 = reducedP % 2, reducedQ % 2
if reducedPMod2 == 0:
if reducedQMod2 == 0:
reducedP >>= 1
reducedQ >>= 1
else:
return 2
elif reducedQMod2 == 0:
return 0
else:
return 1 | mirror-reflection | [Python] Fast solution (with explanations) | RegInt | 0 | 24 | mirror reflection | 858 | 0.633 | Medium | 13,958 |
https://leetcode.com/problems/mirror-reflection/discuss/2376890/%22python%22-simple-solution-for-you-%3A) | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
ext = q
reflection = p
while ext % 2 == 0 and reflection % 2 == 0:
ext /= 2
reflection /= 2
if ext % 2 == 0 and reflection % 2 != 0: return 0
if ext % 2 == 1 and reflection % 2 == 0: return 2
if ext % 2 == 1 and reflection % 2 != 0: return 1
return -1 | mirror-reflection | "python" simple solution for you :) | anandchauhan8791 | 0 | 23 | mirror reflection | 858 | 0.633 | Medium | 13,959 |
https://leetcode.com/problems/mirror-reflection/discuss/940454/Python3-Math-log(MN) | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
if q == 0: return 0 # edge case
g = gcd(p, q)
p, q = p//g, q//g
if p&1 and q&1: return 1
elif p&1 and not q&1: return 0
elif not p&1 and q&1: return 2 | mirror-reflection | [Python3] Math log(MN) | ye15 | 0 | 67 | mirror reflection | 858 | 0.633 | Medium | 13,960 |
https://leetcode.com/problems/mirror-reflection/discuss/940454/Python3-Math-log(MN) | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
eps = 1e-5
x = y = 0
dx, dy = p, q
while True:
if abs(x-p) + abs(y-0) < eps: return 0
if abs(x-p) + abs(y-p) < eps: return 1
if abs(x-0) + abs(y-p) < eps: return 2
xx = x + dx
yy = y + dy
if not 0 <= xx <= p:
xx = max(0, min(p, xx))
yy = y + dy/dx*(xx - x)
if not 0 <= yy <= p:
yy = max(0, min(p, yy))
xx = x + dx/dy*(yy - y)
x, y = xx, yy
if xx in (0, p): dx *= -1
if yy in (0, p): dy *= -1 | mirror-reflection | [Python3] Math log(MN) | ye15 | 0 | 67 | mirror reflection | 858 | 0.633 | Medium | 13,961 |
https://leetcode.com/problems/mirror-reflection/discuss/939149/Mirror-Reflection-or-Python3-One-liner | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
return abs(~(not((mul * p // q) % 2))) if (mul := q // math.gcd(p, q)) % 2 else 0 | mirror-reflection | Mirror Reflection | Python3 One-liner | hangyu1130 | 0 | 62 | mirror reflection | 858 | 0.633 | Medium | 13,962 |
https://leetcode.com/problems/mirror-reflection/discuss/388427/Solution-in-Python-3-(two-lines) | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
g = math.gcd(p,q)
return 2 if not p//g % 2 else q//g % 2
- Junaid Mansuri
(LeetCode ID)@hotmail.com | mirror-reflection | Solution in Python 3 (two lines) | junaidmansuri | 0 | 316 | mirror reflection | 858 | 0.633 | Medium | 13,963 |
https://leetcode.com/problems/buddy-strings/discuss/2790774/Python-oror-Beginner-Friendly-oror-98-faster-oror-O(n) | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
freq1=[0]*26
freq2=[0]*26
diff =0
if(len(s)!=len(goal)):
return False
for i in range(len(s)):
if(s[i]!=goal[i]):
diff+=1
freq1[ord(s[i])-ord('a')]+=1
freq2[ord(goal[i])-ord('a')]+=1
unique= True
for idx in range(len(freq1)):
if(freq1[idx]!=freq2[idx]):
return False
if(freq1[idx]>1):
unique = False
if(diff==2 or (unique==False and diff==0)):
return True | buddy-strings | Python || Beginner Friendly || 98% faster || O(n) | hasan2599 | 1 | 176 | buddy strings | 859 | 0.291 | Easy | 13,964 |
https://leetcode.com/problems/buddy-strings/discuss/2186221/Python3-O(n)-oror-O(26)-Runtime%3A-40ms-78.04-memory%3A-14.2mb-60.39 | class Solution:
# O(n) || O(26)
# Runtime: 40ms 78.04% memory: 14.2mb 60.39%
def buddyStrings(self, string: str, goal: str) -> bool:
left, right = 0, len(string) - 1
if len(string) != len(goal):
return False
if string == goal and len(set(string)) < len(string):
return True
difference = []
for i in range(len(string)):
if string[i] != goal[i]:
difference.append((string[i], goal[i]))
if len(difference) == 2 and difference[0] == difference[-1][::-1]:
return True
return False | buddy-strings | Python3 O(n) || O(26) # Runtime: 40ms 78.04% memory: 14.2mb 60.39% | arshergon | 1 | 148 | buddy strings | 859 | 0.291 | Easy | 13,965 |
https://leetcode.com/problems/buddy-strings/discuss/2123105/Easy-to-understand | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal): return False
if s == goal and len(set(s)) < len(goal): return True
diff = [(a, b) for a, b in zip(s, goal) if a != b]
return len(diff) == 2 and diff[0] == diff[1][::-1] | buddy-strings | Easy to understand | writemeom | 1 | 168 | buddy strings | 859 | 0.291 | Easy | 13,966 |
https://leetcode.com/problems/buddy-strings/discuss/1777302/Python-Solution-or-O-(n) | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
index =[]
if len(s)==1:
return False
if s==goal and len(set(s))<len(s):
return True;
for i in range(len(s)):
if s[i]!=goal[i]:
index.append(i)
if(len(index)!=2):
return False;
new_s = list(s)
swap1 = new_s[index[0]]
swap2 = new_s[index[1]]
new_s[index[0]] = swap2
new_s[index[1]] = swap1
new_s = ''.join(new_s)
if new_s==goal:
return True
else:
return False | buddy-strings | Python Solution | O (n) | pkprasad1996 | 1 | 175 | buddy strings | 859 | 0.291 | Easy | 13,967 |
https://leetcode.com/problems/buddy-strings/discuss/1501870/Easy-well-commented-Python-solution | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A)!=len(B) or set(A)!=set(B):
return False
if A==B: #must have atleast 1 rep char
return len(A)!=len(set(A))
#A and B now same length, lets swap
firstMissMatch=0
flagOK=0
for a,b in zip(A,B):
if a==b: continue #if letters are qual just continue
if not firstMissMatch: #if this is the firstMistMatch, flip firstMissMatch flap to 1 and store the chars
swapA,swapB=a,b
firstMissMatch=1
elif flagOK==0: #i.e: this is the 2nd mismatch, need to check if the chars to be swapped are equal to the previous mismatch
flagOK=1 if a==swapB and b==swapA else 2
else:
return False #meaning more than 1 mismatch appeared
return flagOK==1 #if flag=0 (no swap) or flag=2 (swap but letters dont match i.e: A=abcaa and B=abcbb) return False | buddy-strings | Easy, well commented Python 🐍 solution | InjySarhan | 1 | 221 | buddy strings | 859 | 0.291 | Easy | 13,968 |
https://leetcode.com/problems/buddy-strings/discuss/1277027/Easy-Python-Solution(98.13) | class Solution:
def buddyStrings(self, a: str, b: str) -> bool:
if(len(a)!=len(b) or set(a)!=set(b)):
return False
if a==b:
return False if len(set(a))==len(a) else True
c=0
a=list(a)
for i in range(len(a)):
if(a[i]==b[i]):
continue
elif(a[i]!=b[i]) and c==0:
s=i
c+=1
else:
a[i],a[s]=a[s],a[i]
break
return "".join(a)==b and c==1 | buddy-strings | Easy Python Solution(98.13%) | Sneh17029 | 1 | 516 | buddy strings | 859 | 0.291 | Easy | 13,969 |
https://leetcode.com/problems/buddy-strings/discuss/2719709/Python-Simple-O(N)-Solution | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if (len(s) != len(goal)):
return False
if (len(s) <= 1):
return False
if (s == goal) and len(set(s)) < len(s):
return True
diff = []
for i in range(len(s)):
if s[i] != goal[i]:
diff.append(i)
if len(diff) != 2:
return False
return s[diff[0]] == goal[diff[1]] and s[diff[1]] == goal[diff[0]] | buddy-strings | Python Simple O(N) Solution | wyatt-h | 0 | 16 | buddy strings | 859 | 0.291 | Easy | 13,970 |
https://leetcode.com/problems/buddy-strings/discuss/2619817/python-3-soulution-explained | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
n1=len(s)
n2=len(goal)
if n1!=n2: #if length is not equal we cannot make them the same with interchange
return False
d=defaultdict(list)
mx =0 #max count of individual
cnt=defaultdict(int)
for i in range(n1):
cnt[s[i]]+=1
if cnt[s[i]]>mx:
mx=cnt[s[i]] # maximum times acharacter occurs in s
d[i]=[s[i],goal[i]] #store value of both strings at an index
count=0
dif=[]
for k in d:
a=d[k][0] #letter at index k of s
b=d[k][1] #letter at index k of s
if a!=b:
count+=1
dif.append(k)
if count>2: # only one interchange is allowed
return False
if count==1:
return False #one index at has unmatched value , can never be interchanged
if count==0:
if mx >=2: #s='aa' goal='aa'
return True
return False #s='ab' goal='ab'
if d[dif[0]][0]==d[dif[1]][1] and d[dif[1]][0]==d[dif[0]][1]: #if 2 values are at wrong index check if there interchange would make the strings same
return True
return False | buddy-strings | python 3 soulution explained | abhayCodes | 0 | 34 | buddy strings | 859 | 0.291 | Easy | 13,971 |
https://leetcode.com/problems/buddy-strings/discuss/2424897/Python3-Solution-oror-If-Loops-oror-98-Fast-oror-Understandable | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s)!=len(goal):
return False
if s==goal:
return len(s)-len(set(s))>=1
new=[]
for i in range(len(s)):
if s[i]!=goal[i]:
new.append(i)
if len(new)>2:
return False
if len(new)!=2:
return False
if s[new[0]]==goal[new[1]] and s[new[1]]==goal[new[0]]:
return True
return False | buddy-strings | Python3 Solution || If Loops || 98% Fast || Understandable | shashank_shashi | 0 | 73 | buddy strings | 859 | 0.291 | Easy | 13,972 |
https://leetcode.com/problems/buddy-strings/discuss/2319827/Python-easy-explanation | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
c=0
l=len(s)
if len(goal)!=l: # len of s and goal shall be same
return False
set_s=set()
set_g=set()
for i in range(l):
if s[i]!=goal[i]:
set_s.add(goal[i])
set_g.add(s[i])
c+=1
if (c>2) | (set_s!=set_g): # check for more than 2 mismatches
return False
if (c==0) & (l==len(set(s))): # if there is no mismatch, check if there are repeated characters in s, repeated characters can be used for swapping
return False
return True | buddy-strings | Python easy explanation | sunakshi132 | 0 | 128 | buddy strings | 859 | 0.291 | Easy | 13,973 |
https://leetcode.com/problems/buddy-strings/discuss/2143733/Short-O(n)O(n) | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
hs = set(s)
d = [i for i in range(len(s)) if s[i] != goal[i]]
return len(d) == 0 and len(hs) < len(s) \
or len(d) == 2 and s[d[0]] == goal[d[1]] and s[d[1]] == goal[d[0]] | buddy-strings | Short O(n)/O(n) | dima62 | 0 | 81 | buddy strings | 859 | 0.291 | Easy | 13,974 |
https://leetcode.com/problems/buddy-strings/discuss/2107100/python-3-oror-simple-solution-oror-O(n)O(1) | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
if s == goal:
return len(goal) != len(set(goal))
different = []
for i, (c1, c2) in enumerate(zip(s, goal)):
if c1 != c2:
different.append(i)
if len(different) > 2:
return False
if len(different) == 1:
return False
i, j = different
return s[i] == goal[j] and s[j] == goal[i] | buddy-strings | python 3 || simple solution || O(n)/O(1) | dereky4 | 0 | 143 | buddy strings | 859 | 0.291 | Easy | 13,975 |
https://leetcode.com/problems/buddy-strings/discuss/1906686/Python3-or-O(n)-Space%2BTime | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
diff=0
l=[]
n=len(s)
k=len(goal)
if n!=k:
return False
hmap={}
for i in range(n):
if s[i]!=goal[i]:
diff+=1
l.append(i)
if s[i] not in hmap:
hmap[s[i]]=1
else:
hmap[s[i]]+=1
if diff==0:
for j in hmap.values():
if j>1:
return True
return False
elif diff==2:
ind1,ind2=l
if s[ind1]==goal[ind2] and s[ind2]==goal[ind1]:
return True
else:
return False
else:
return False | buddy-strings | [Python3] | O(n) Space+Time | swapnilsingh421 | 0 | 36 | buddy strings | 859 | 0.291 | Easy | 13,976 |
https://leetcode.com/problems/buddy-strings/discuss/1339909/Just-store-all-the-mismatches-in-a-list... | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
# if they are equal, at least one char has fre > 1
if s == goal: return max(Counter(s).values()) > 1
mismatch = list() # store the pairs which are mismatched in a list, [(a,b) , (b,a)]
res = 0
if len(s) != len(goal): return False
for sc,gc in zip(s,goal):
if sc != gc:
mismatch.append([sc,gc]) # better to short circuit cause O(N) space rn
if len(mismatch) != 2 : return False # nest him for O(1)
if mismatch[0] == mismatch[1][::-1]:
return True
# otherwise if they are unequal cant do anything
if s != goal: return False | buddy-strings | Just store all the mismatches in a list... | yozaam | 0 | 89 | buddy strings | 859 | 0.291 | Easy | 13,977 |
https://leetcode.com/problems/buddy-strings/discuss/1292799/Python%3A-Break-down-in-3-subproblems-and-solving-each-one. | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
# Case 1. Impossible to swap
if len(s) != len(goal): return False
# Case 2. Strings equal, check if one char dup
if s == goal: return len(set(s)) < len(s)
# Case 3. Strings not equal, find differences
else:
diff = [] # Keeping track of the places where chars are different
for i, char in enumerate(goal):
if char != s[i]: diff.append(i) # record difference
if len(diff) != 2: return False # if not exactly one swap then we failed condition
else: # otherwise just compare the swap
l_s = list(s) #strings are immutable so I created a list
l_s[diff[0]] = s[diff[1]] # Swap first mismatching char with the last one
l_s[diff[1]] = s[diff[0]] # Swap last mismatching char with the first one
return ''.join(l_s) == goal # Return if the result is equal | buddy-strings | Python: Break down in 3 subproblems & solving each one. | antonmdv | 0 | 114 | buddy strings | 859 | 0.291 | Easy | 13,978 |
https://leetcode.com/problems/buddy-strings/discuss/972676/Python-Simple | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
# If lenghts are not equal, they are not buddy, as we cannot add chars
if len(A) != len(B):
return False
mismatches = list()
for i in range(0, len(A)):
# Early exit in case we already have violated constraint.
if len(mismatches) > 2:
return False
if A[i] != B[i]:
mismatches.append((A[i], B[i]))
if len(mismatches) == 2:
# Make sure revert of second match first or can also be vice versa.
return mismatches[0] == mismatches[1][::-1]
if len(mismatches) == 0:
# Make sure there are duplicates if arrays are exactly same.
return len(A) - len(set(A)) != 0
return False | buddy-strings | Python Simple | shruti98932 | 0 | 201 | buddy strings | 859 | 0.291 | Easy | 13,979 |
https://leetcode.com/problems/buddy-strings/discuss/759491/Python-3-Simple-Solution.-Beats-98.86 | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
a_mis_loc = []
for i in range(len(A)):
if A[i] != B[i]:
a_mis_loc.append(i)
if len(a_mis_loc) == 2:
A = list(A)
A[a_mis_loc[0]], A[a_mis_loc[1]] = A[a_mis_loc[1]], A[a_mis_loc[0]]
A = ''.join(A)
if A == B:
return True
elif len(a_mis_loc) == 0 and A == B and len(A) > len(set(A)):
return True
else:
return False | buddy-strings | Python 3 Simple Solution. Beats 98.86% | Renegade9819 | 0 | 244 | buddy strings | 859 | 0.291 | Easy | 13,980 |
https://leetcode.com/problems/buddy-strings/discuss/456019/Python3-super-simple-solution-using-a-hash-table-and-a-for()-loop | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
if len(A) != len(B):
return False
ht = {}
for i in range(len(A)):
if A[i] != B[i]:
ht[i] = A[i]
if len(ht) == 2:
i,j=ht.keys()
A = list(A)
A[i],A[j]=A[j],A[i]
return "".join(A) == B
elif len(ht) == 0 and A == B and len(A) > len(set(A)):
return True
else:
return False | buddy-strings | Python3 super simple solution using a hash table and a for() loop | jb07 | 0 | 168 | buddy strings | 859 | 0.291 | Easy | 13,981 |
https://leetcode.com/problems/buddy-strings/discuss/381785/Solution-in-Python-3-(beats-~98)-(six-lines) | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
C, A, B = [i for i in range(len(A)) if A[i] != B[i]], list(A), list(B)
if not C and len(A) == len(B):
for i in A:
if A.count(i) > 1: return True
elif len(C) == 2 and A[C[0]] == B[C[1]] and A[C[1]] == B[C[0]]: return True
return False
- Junaid Mansuri
(LeetCode ID)@hotmail.com | buddy-strings | Solution in Python 3 (beats ~98%) (six lines) | junaidmansuri | 0 | 632 | buddy strings | 859 | 0.291 | Easy | 13,982 |
https://leetcode.com/problems/buddy-strings/discuss/301833/Python3-Two-pointers | class Solution:
def buddyStrings(self, A: str, B: str) -> bool:
a=list(A)
b=list(B)
if len(A)!=len(B):
return False
if A==B and len(set(A))==len(A):
return False
start=0
pointer=start+1
while start<len(A):
if A[start]==B[start]:
start+=1
else:
while A[start]!=B[pointer] and pointer<len(A)-1:
pointer+=1
if A[start]==B[pointer] and B[start]==A[pointer]:
a[start],a[pointer]=a[pointer],a[start]
break
return a==b | buddy-strings | Python3 Two pointers | JasperZhou | 0 | 203 | buddy strings | 859 | 0.291 | Easy | 13,983 |
https://leetcode.com/problems/buddy-strings/discuss/1275559/Python3-solution-memory-usage-beats-90-users | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
l = []
for i in range(len(s)):
if s[i] != goal[i]:
l.append(i)
return (len(l) == 2 and s[l[0]] == goal[l[1]] and s[l[1]] == goal[l[0]]) or (len(l) == 0 and max(Counter(s).values()) > 1) | buddy-strings | Python3 solution memory usage beats 90% users | EklavyaJoshi | -1 | 34 | buddy strings | 859 | 0.291 | Easy | 13,984 |
https://leetcode.com/problems/lemonade-change/discuss/1260496/Python-3-Easy-to-understand-Better-than-95 | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
change5=0
change10=0
change20=0
for i in range(len(bills)):
if bills[i]==5:
change5+=1
elif bills[i]==10:
change10+=1
change5-=1
elif bills[i]==20:
if change10>0 :
change5-=1
change10-=1
else:
change5-=3
change20+=1
if change5<0 or change10<0 or change20<0:
return False
return True | lemonade-change | Python 3 Easy-to-understand Better than 95% | mk_mohtashim | 4 | 447 | lemonade change | 860 | 0.528 | Easy | 13,985 |
https://leetcode.com/problems/lemonade-change/discuss/2187554/Python3-O(n)-oror-O(1)-Runtime%3A-1159ms-49.65-Memory%3A-18mb-49.96 | class Solution:
# O(n) || O(1)
# Runtime: 1159ms 49.65% Memory: 18mb 49.96%
def lemonadeChange(self, bills: List[int]) -> bool:
fiveBills, tenBills = 0, 0
for i in bills:
if i == 5:
fiveBills += 1
elif i == 10:
tenBills += 1
fiveBills -= 1
elif tenBills > 0:
tenBills -= 1
fiveBills -= 1
else:
fiveBills -= 3
if fiveBills < 0:
return False
return True | lemonade-change | Python3 O(n) || O(1) # Runtime: 1159ms 49.65% Memory: 18mb 49.96% | arshergon | 2 | 156 | lemonade change | 860 | 0.528 | Easy | 13,986 |
https://leetcode.com/problems/lemonade-change/discuss/1171648/Python3-simple-solution-using-two-approaches | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
d = {5:0,10:0,20:0}
for i in range(len(bills)):
if bills[i] == 5:
d[5] += 1
if bills[i] == 10:
if d[5] >= 1:
d[5] -= 1
d[10] += 1
else:
return False
if bills[i] == 20:
if (d[5] >= 1 and d[10] >= 1):
d[5] -= 1
d[10] -= 1
elif d[5] >= 3:
d[5] -= 3
else:
return False
return True | lemonade-change | Python3 simple solution using two approaches | EklavyaJoshi | 2 | 144 | lemonade change | 860 | 0.528 | Easy | 13,987 |
https://leetcode.com/problems/lemonade-change/discuss/1171648/Python3-simple-solution-using-two-approaches | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
_5 = 0
_10 = 0
for i in bills:
if i == 5:
_5 += 1
elif i == 10:
if _5 >= 1:
_5 -= 1
_10 += 1
else:
return False
else:
if _5 >= 1 and _10 >= 1:
_5 -= 1
_10 -= 1
elif _5 >= 3:
_5 -= 3
else:
return False
return True | lemonade-change | Python3 simple solution using two approaches | EklavyaJoshi | 2 | 144 | lemonade change | 860 | 0.528 | Easy | 13,988 |
https://leetcode.com/problems/lemonade-change/discuss/382679/Solution-in-Python-3 | class Solution:
def lemonadeChange(self, b: List[int]) -> bool:
L, B = len(b), {5:0, 10:0, 20:0}
for i in range(L):
if b[i] == 10:
if B[5] == 0: return False
else: B[5] -= 1
elif b[i] == 20:
if B[10] != 0 and B[5] != 0: B[5], B[10] = B[5] - 1, B[10] - 1
elif B[5] >= 3: B[5] -= 3
else: return False
B[b[i]] += 1
return True
- Junaid Mansuri
(LeetCode ID)@hotmail.com | lemonade-change | Solution in Python 3 | junaidmansuri | 1 | 319 | lemonade change | 860 | 0.528 | Easy | 13,989 |
https://leetcode.com/problems/lemonade-change/discuss/2828971/PYTHON3-BEAT-90-EASY-TO-UNDERSTAND | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
count_5=0
count_10=0
for i in range(0,len(bills)):
if count_5<0 or count_10<0:
return False
if bills[i]==5:
count_5+=1
elif bills[i]==10:
count_10+=1
count_5-=1
elif bills[i]==20 and count_10>0:
count_10-=1
count_5-=1
elif bills[i]==20 and count_10==0:
count_5-=3
if count_5<0 or count_10<0:
return False
return True | lemonade-change | PYTHON3 - BEAT 90% - EASY TO UNDERSTAND | onggiaphuoc2004 | 0 | 3 | lemonade change | 860 | 0.528 | Easy | 13,990 |
https://leetcode.com/problems/lemonade-change/discuss/2760488/Python-or-Simple-greedy-solution-or-O(n) | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
change = {5: 0, 10: 0}
for b in bills:
if b == 5:
change[5] += 1
elif b == 10 and change[5] > 0:
change[5] -= 1
change[10] += 1
elif b == 20:
if change[5] > 0 and change[10] > 0:
change[5] -= 1
change[10] -= 1
elif change[5] > 2 and change[10] == 0:
change[5] -= 3
else:
return False
else:
return False
return True | lemonade-change | Python | Simple greedy solution | O(n) | LordVader1 | 0 | 8 | lemonade change | 860 | 0.528 | Easy | 13,991 |
https://leetcode.com/problems/lemonade-change/discuss/2685389/Lemonade-Change-or-Full-explaination-with-comments-or-Python-or-100-efficient-solution | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
# we consider all notes here
#l[0] stores $5 notes
#l[1] stores $10 notes
#l[2] stores $20 notes
l=[0]*3
for i in bills:
if i==5: # if customer gives $5 note
l[0]+=1 # then l[0]+=1 (increase the no of $5 notes)
elif i==10: # if customer gives $10 note then seller has to return total $5
l[1]+=1 # then l[1]+=1 (increase the no of $10 notes)
if l[0]>=1: # check if seller has $5 note to return
l[0]-=1 # then l[0]-=1 (decrease the no of $5 notes)
else:
return False # otherwise return false
elif i==20: # if customer gives $20 note then seller has to return total $15
l[2]+=1 # then l[2]+=1 (increase the no of $20 notes)
# total 2 combination possible :
# 1 combination $10 + $5 = $15
# 2 combination $5 + $5 + $5 = $15
if l[1]>=1 and l[0]>=1: # 1 combination
l[1]-=1 # decrease 1 $10 note
l[0]-=1 # decrease 1 $5 note ($10 + $5 = $15)
elif l[0]>=3: # 2 combination $5 + $5 + $5 = $15
l[0]-=3 # decrease 3 $5 note ($5 + $5 + $5 = $15)
else:
return False # otherwise return false
return True | lemonade-change | Lemonade Change | Full explaination with comments | Python | 100% efficient solution | saptarishimondal | 0 | 4 | lemonade change | 860 | 0.528 | Easy | 13,992 |
https://leetcode.com/problems/lemonade-change/discuss/2406447/Python-97.19-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Greedy | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
count5 = 0 # taking counter for $5
count10 = 0 # taking counter for $10
for b in bills: # treversing the list of bills.
if b == 5:
count5+=1 # if the bill is 5, incresing the 5 counter.
elif b == 10:
if count5 == 0: # if the bill is 10 & we dont have change to return, then its false.
return False
count10+=1 # increasing the 10 counter
count5-=1 # decreasing 5 counter as we`ll give 5 as change.
else: # if the bill is of $20
if (count5>=1 and count10>=1):# checking if we have enough change to return
count5-=1 # if its a $20 , then $5 as change and
count10-=1 # one $10
elif count5>=3: # fi we dont have $10 as change, though we have three $3.
count5-=3 # decresing the $3 counter.
else:
return False
return True
```
***Found helpful, Do upvote !!*** | lemonade-change | Python 97.19% faster | Simplest solution with explanation | Beg to Adv | Greedy | rlakshay14 | 0 | 103 | lemonade change | 860 | 0.528 | Easy | 13,993 |
https://leetcode.com/problems/lemonade-change/discuss/2352179/Python-straight-forward | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
change = {5:0,10:0}
for i in bills:
if i==5:
change[5]+=1
elif i==10:
if change[5]>0:
change[5]-=1
change[10]+=1
else:
return False
else:
if (change[10]>0) & (change[5]>0):
change[10]-=1
change[5]-=1
elif change[5]>=3:
change[5]-=3
else:
return False
return True | lemonade-change | Python straight forward | sunakshi132 | 0 | 48 | lemonade change | 860 | 0.528 | Easy | 13,994 |
https://leetcode.com/problems/lemonade-change/discuss/2161802/easy-understanding-solution-using-dictionaries | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
d={}
d[5]=0
d[10]=0
d[20]=0
for i in bills:
print(d)
if i==5:
d[5]+=1
elif i==10:
d[10]+=1
if d[5]>=1:
d[5]-=1
else:
return 0
else:
if d[5]>=3 and d[10]<1:
d[5]-=3
elif d[5]>=1 and d[10]>=1:
d[10]-=1
d[5]-=1
else:
return 0
return 1 | lemonade-change | easy understanding solution using dictionaries | captain_sathvik | 0 | 31 | lemonade change | 860 | 0.528 | Easy | 13,995 |
https://leetcode.com/problems/lemonade-change/discuss/1834287/Simple-Python-Solution-oror-90-Faster-oror-Memory-less-than-95 | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five=0 ; ten=0
for i in range(len(bills)):
if bills[i]==5: five+=1
elif bills[i]==10: ten+=1 ; five-=1
elif ten>0: five-=1 ; ten-=1
else: five-=3
if five<0: return False
return True | lemonade-change | Simple Python Solution || 90% Faster || Memory less than 95% | Taha-C | 0 | 93 | lemonade change | 860 | 0.528 | Easy | 13,996 |
https://leetcode.com/problems/lemonade-change/discuss/1169310/Python3-Greedy-Solution-Intuition | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
cash, cost, hmap = 0, 5, {5:0, 10:0, 20:0}
for i, c in enumerate(bills):
if c == cost:
hmap[c] += 1
elif c > cost:
change = c - cost
# To give change, we have to greedily choose the denominations
hmap = {k:v for k, v in sorted(hmap.items(), key=lambda x:x[0], reverse=True)}
for k, v in hmap.items():
if change and v > 0:
q, r = divmod(change, k)
# Also here, we can only account for what we have so using min() - greedy intuiton
min_take = min(v, q)
hmap[k] -= min_take
change -= min_take * k
# Check if change can be given, then accept incoming bill
if change == 0:
hmap[c] += 1
else:
return False
return True | lemonade-change | Python3 Greedy Solution / Intuition | cppygod | 0 | 105 | lemonade change | 860 | 0.528 | Easy | 13,997 |
https://leetcode.com/problems/lemonade-change/discuss/1140460/Simple-Python3-Solution-92.5-faster | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
keep = {5:0, 10:0} #dictionary representing count of $5 and $10 bills
for bill in bills:
if bill==5:
keep[5]+=1 #No change to give, just increase the count of $5 bills elif bill==10 and keep[5]==0: return False #A $5 bill to be given, but no $5 bill in keep elif bill==10 and keep[5]>0: keep[5]-=1 #A $5 bill can be given, so decrease the count of $5 bills keep[10]+=1 #Got a $10 bill, increase the count of $10 bills elif bill==20 and keep[5]>=1 and keep[10]>=1: keep[5]-=1 #If we have a $10 bill and $5 bill, we use them at first keep[10]-=1 #Decrease the counts of $10 bills and $5 bills by one elif bill==20 and keep[5]>=3: keep[5]-=3 #If we don't have any $10 bills, we have to use 3 $5 bills #Decrease the count of $5 bills by three
else:
return False #Not enough bills to give change, return False
#print(keep[5], keep[10])
return True #All customers got change, so return True | lemonade-change | Simple Python3 Solution, 92.5% faster | bPapan | 0 | 70 | lemonade change | 860 | 0.528 | Easy | 13,998 |
https://leetcode.com/problems/lemonade-change/discuss/543437/Python-easy-solution-O(n)-120-ms-12MB-O(n) | class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
previous_5 = 0
previous_10 = 0
price = 5
for bill in bills:
if bill - price == 5:
previous_5 -= 1
previous_10 += 1
elif bill - price == 15:
previous_5 -= 1
if previous_10 > 0:
previous_10 -= 1
else:
previous_5 -= 2
else:
previous_5 += 1
if previous_5 < 0:
return False
return True | lemonade-change | Python easy solution O(n) 120 ms, 12MB, O(n) | hemina | 0 | 213 | lemonade change | 860 | 0.528 | Easy | 13,999 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.