post_href
stringlengths 57
213
| python_solutions
stringlengths 71
22.3k
| slug
stringlengths 3
77
| post_title
stringlengths 1
100
| user
stringlengths 3
29
| upvotes
int64 -20
1.2k
| views
int64 0
60.9k
| problem_title
stringlengths 3
77
| number
int64 1
2.48k
| acceptance
float64 0.14
0.91
| difficulty
stringclasses 3
values | __index_level_0__
int64 0
34k
|
|---|---|---|---|---|---|---|---|---|---|---|---|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2785917/Easy-to-understand-sort-and-counter-solution
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed) % 2 != 0:
return []
countDict = collections.Counter(changed)
numZeros = countDict[0]
if numZeros:
if numZeros % 2 != 0:
return []
del countDict[0]
result = [0]* (numZeros//2)
keyValues = list(countDict.keys())
keyValues.sort()
for i in range(len(keyValues)):
key = keyValues[i]
if countDict[key]:
doubleKey = 2*key
if countDict[doubleKey] >= countDict[key]:
result += [key]*countDict[key]
countDict[doubleKey] -= countDict[key]
countDict[key] = 0
else:
return []
for key in countDict:
if countDict[key] != 0:
return []
return result
|
find-original-array-from-doubled-array
|
Easy to understand - sort & counter solution
|
TheCodeBoss
| 0
| 3
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,000
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2581911/Python-or-O(n)-or-Easy-To-Understand
|
class Solution:
def findOriginalArray(self, changed):
# Time Complexity: O(n log n)
# Space Complexity: O(n)
changed.sort()
que=deque([])
output=[]
for i in changed:
if que and que[0]==i:
que.popleft()
else:
que.append(i*2)
output.append(i)
if que: return []
return output
|
find-original-array-from-doubled-array
|
Python | O(n) | Easy To Understand
|
varun21vaidya
| 0
| 19
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,001
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2580335/SLOWER-OR-SLOWEST-BUT-EASIER-APPROCH
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed)%2!=0: return []
freq=[0]*100001
for i in changed: freq[i]+=1
ans=[]
for j in range(100001):
while j*2<100001 and freq[j]>0 and freq[j*2]>0:
ans.append(j)
freq[j]-=1
freq[j*2]-=1
for k in freq:
if k!=0: return []
return ans
|
find-original-array-from-doubled-array
|
SLOWER OR SLOWEST BUT EASIER APPROCH
|
DG-Problemsolver
| 0
| 16
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,002
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2580233/Python-3-or-Easy-to-understand
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed)%2!=0:
return []
has={}
for i in changed:
if i in has:
has[i]+=1
else:
has[i]=1
if 0 in has and has[0]%2!=0:
return []
changed.sort()
ans=[]
for i in range(len(changed)-1,-1,-1):
if changed[i]%2==0 and has[changed[i]]>0 and changed[i]//2 in has and has[changed[i]//2]>0:
has[changed[i]//2]-=1
has[changed[i]]-=1
ans.append(changed[i]//2)
#print(changed[i],changed[i]//2)
return ans if len(ans)==len(changed)//2 else []
|
find-original-array-from-doubled-array
|
Python 3 | Easy to understand
|
RickSanchez101
| 0
| 26
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,003
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2579974/Python-solution
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed) % 2:
return []
res = []
seen = {}
changed.sort(reverse=True)
for num in changed:
if num * 2 in seen:
res.append(num)
if seen[num*2] == 1:
del seen[num*2]
else:
seen[num*2] -= 1
else:
seen[num] = seen.get(num, 0) + 1
return res if len(res) == len(changed) // 2 else []
|
find-original-array-from-doubled-array
|
Python solution
|
Mark5013
| 0
| 12
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,004
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2579641/O(nlogn)-using-heuristic-with-sorting-%2B-binary-searching
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
a = sorted(changed)
print(changed)
ans = []
while len(a)>1:
print("+ ", a, ans)
u = a.pop(0)
i = bisect_left(a, 2*u)
if i>=len(a) or a[i] != 2*u:
ans = []
break
else:
ans.append(u)
a.pop(i)
print(a, ans)
if len(a)>0:
ans = []
print("ans:", ans)
print("=" * 20, "\n")
return ans
print = lambda *a, **aa: ()
|
find-original-array-from-doubled-array
|
O(nlogn) using heuristic with sorting + binary searching
|
dntai
| 0
| 9
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,005
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2579190/Python3-Linear-Time-Dictionary-Solution-O(n)-Time-O(n)-Space
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
# quick check
if len(changed) % 2 == 1:
return []
h = Counter(changed)
res = []
# loop below has issues because y = y + y when y = 0
if h[0] % 2 == 1:
return []
else:
res.extend([0] * (h[0] // 2))
h[0] = 0
for x in changed:
# if x is the start of a sequence x, 2x, 4x, etc
if h[x] > 0 and (x % 2 == 1 or (x//2 not in h or h[x//2] == 0)):
y = x
while y in h:
if h[y] > h[y+y]:
return []
elif h[y] > 0:
res.extend([y] * h[y])
h[y+y] -= h[y]
h[y] = 0
y = y + y
return res
|
find-original-array-from-doubled-array
|
[Python3] Linear Time Dictionary Solution - O(n) Time, O(n) Space
|
rt500
| 0
| 28
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,006
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2578442/GolangPython-O(N*log(N))-time-or-O(N)-space
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
changed.sort()
counter = {}
for value in changed:
if value not in counter:
counter[value] = 0
counter[value] +=1
output = []
for value in changed:
if value in counter and counter[value] > 0:
counter[value]-=1
double_value = value*2
if double_value in counter and counter[double_value] > 0:
counter[double_value]-=1
output.append(value)
else:
return []
return output
|
find-original-array-from-doubled-array
|
Golang/Python O(N*log(N)) time | O(N) space
|
vtalantsev
| 0
| 17
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,007
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2578172/Python-Solution-with-Dictionary
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
d = {}
if len(changed)%2 == 1:
return []
changed.sort()
ans = []
for i in range(len(changed)):
if changed[i]%2 == 0 and changed[i]//2 in d:
ans.append(changed[i]//2)
d[changed[i]//2] -= 1
if d[changed[i]//2] == 0:
del d[changed[i]//2]
else:
d[changed[i]] = d.get(changed[i],0)+1
return ans if len(ans) == len(changed)//2 else []
|
find-original-array-from-doubled-array
|
Python Solution with Dictionary
|
a_dityamishra
| 0
| 14
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,008
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2578134/Python-Hashmap-Easy-Solution-Well-Explained
|
class Solution:
# Hashmap
# The basic intuition would be to take up 3 arrays
# After sorting the array keep putting elements into 1st array if 2 * num is not seen yet
# this is slow because taking 3 lists with their operations of insert and delete and multiple common elements can be present
# Using a counter can solve this as you decrease the counter in 1 step for both the key and the 2 * key value without the extra operations taking much time
def findOriginalArray(self, changed: List[int]) -> List[int]:
n = len(changed)
if n & 1: return []
blist = [0] * (n >> 1)
changed.sort()
count = Counter(changed)
it = 0
for num in changed:
check = num << 1
if count[num] < 1: continue
count[num] -= 1
if check in count and count[check] > 0:
blist[it] = (num)
count[check] -= 1
it += 1
else: return []
return blist
|
find-original-array-from-doubled-array
|
Python Hashmap Easy Solution Well Explained
|
shiv-codes
| 0
| 14
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,009
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2578051/Python-O(nlogn)-using-sorting-and-queue
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
n = len(changed)
if n % 2 != 0: return []
result = []
changed.sort()
queue = deque()
for i in changed[::-1]:
if queue and i*2 == queue[0]:
result.append(i)
queue.popleft()
else:
queue.append(i)
return result if len(result) == n//2 else []
|
find-original-array-from-doubled-array
|
Python O(nlogn) using sorting and queue
|
rjnkokre
| 0
| 7
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,010
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2578051/Python-O(nlogn)-using-sorting-and-queue
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
n = len(changed)
if n % 2 != 0: return []
result = []
changed.sort()
queue = deque()
for i in changed:
if queue and i/2 == queue[0]:
result.append(i/2)
queue.popleft()
else:
queue.append(i)
return result if len(result) == n//2 else []
|
find-original-array-from-doubled-array
|
Python O(nlogn) using sorting and queue
|
rjnkokre
| 0
| 7
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,011
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2577892/Python-Solution-or-Brute-Force-greater-Optimized
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed)%2!=0:
return []
n=len(changed)
# Brute Force
# changed.sort()
# count=0
# ans=[]
# for i in range(n):
# if changed[i]!=-1:
# for j in range(i+1, n):
# # print(changed[i], changed[j])
# if changed[i]*2==changed[j]:
# count+=1
# ans.append(changed[i])
# changed[j]=-1
# break
# # print(changed)
# # print(ans)
# if count==n//2:
# return ans
# return []
# Optimised
changed.sort()
ans=[]
d={}
for i in range(n):
if changed[i] in d:
d[changed[i]]+=1
else:
d[changed[i]]=1
# print(d)
for change in changed:
if d[change]>0:
d[change]-=1
if change*2 in d and d[change*2]>0:
d[change*2]-=1
ans.append(change)
else:
# print(d)
return []
return ans
|
find-original-array-from-doubled-array
|
Python Solution | Brute Force --> Optimized
|
Siddharth_singh
| 0
| 14
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,012
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2577810/Python3-Runtime%3A-1268-ms-faster-than-100-or-Memory%3A-29.1-MB-less-than-99.58
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
count = Counter(changed)
if count[0] % 2:
return []
for num in sorted(count):
if count[num] > count[2*num]:
return []
count[2*num] -= count[num] if num else count[0]//2
return list(count.elements())
|
find-original-array-from-doubled-array
|
[Python3] Runtime: 1268 ms, faster than 100% | Memory: 29.1 MB, less than 99.58%
|
anubhabishere
| 0
| 82
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,013
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2577694/Python3-oror-TC%3A-O(nLogn)-oror-Sort-%2B-Dictionary
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed) % 2 != 0:
return []
res = []
freq = collections.Counter(changed)
changed.sort()
for val in changed:
dob = val * 2
if val in freq and dob in freq:
if freq[val] > 1:
freq[val] -= 1
else:
del freq[val]
if freq[dob] > 1:
freq[dob] -= 1
else:
del freq[dob]
res.append(val)
return [] if freq else res
|
find-original-array-from-doubled-array
|
Python3 || TC: O(nLogn) || Sort + Dictionary
|
s_m_d_29
| 0
| 17
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,014
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2577612/Python-Accepted
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
c = Counter(changed)
zeros, m = divmod(c[0], 2)
if m: return []
ans = [0]*zeros
for n in sorted(c.keys()):
if c[n] > c[2*n]: return []
c[2*n]-= c[n]
ans.extend([n]*c[n])
return ans
|
find-original-array-from-doubled-array
|
Python Accepted
|
Khacker
| 0
| 16
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,015
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2577447/Python-or-Sort-and-Hash-Table-or-Easy-to-Understand-or-With-Explanation
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
# the logic is easy
# use a dictionary to store the num while traversing the changed array
# trick: sort the array first, then the incoming num is definitely greater the the stored nums in dic
if len(changed) % 2 == 1:
return []
result = []
dic = defaultdict(int)
changed.sort()
for num in changed:
if num / 2 in dic:
dic[num / 2] -= 1
result.append(int(num / 2))
if dic[num / 2] == 0:
del dic[num / 2]
else:
dic[num] += 1
return result if not dic else []
|
find-original-array-from-doubled-array
|
Python | Sort & Hash Table | Easy to Understand | With Explanation
|
Mikey98
| 0
| 34
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,016
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/2323728/Python3-Fast-and-Cheap-Solution-%2B-Explanation-(No-hashmap)
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed) & 1: return [] #odd number of elements
changed.sort() #O(nlgn)
#result is the returned array if successful, halves is a
#queue of numbers for which we MUST find double of within
#changed
result, halves = [], deque()
for i in changed:
if not halves: #queue is empty
halves.append(i)
else:
if i == halves[0] * 2:
#we found a match
result.append(halves.popleft())
elif i < halves[0] * 2:
#add another half to the queue
halves.append(i)
else:
#we've gone too far and will never find a
#match for the current front of the queue
return []
#the queue should be empty if it's a doubled array
return result if not halves else []
|
find-original-array-from-doubled-array
|
Python3 Fast & Cheap Solution + Explanation (No hashmap)
|
apometta
| 0
| 78
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,017
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1997712/Python-or-Counter
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
if len(changed)%2!=0:
return []
sm=sum(changed)
if sm%3!=0:
return []
tomake=sm//3 #x+2x=3x means divisible by 3
changed.sort()
ans=[]
ctr=Counter(changed)
for n in changed:
if ctr[n]>0 and ctr[2*n]>0:
ctr[n]-=1
ctr[2*n]-=1
ans.append(n)
if sum(ans)==tomake:
return ans
return []
|
find-original-array-from-doubled-array
|
Python | Counter
|
heckt27
| 0
| 76
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,018
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1660782/python-solution-using-sort
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
n = len(changed)
if n % 2 != 0:
return []
changed.sort()
# [1,6,4,8,3,2] -> [1,2,3,4,6,8]
counts = defaultdict(int)
for c in changed:
counts[c] += 1
original = []
idx = n-1
while idx >= 0:
num = changed[idx]
if counts[num] == 0:
idx -= 1
elif num % 2 != 0:
return []
else: #
counts[num] -= 1
counts[num//2] -=1
idx -= 1
original.append(num//2)
if len(original) == n//2:
return original
else:
return []
|
find-original-array-from-doubled-array
|
python solution using sort
|
byuns9334
| 0
| 271
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,019
|
https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1557454/Python3-Greedy-Time%3A-O(n-log-n)-and-Space%3A-O(n)
|
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
# first check if array is even
# create counter map
# sort the array and iterate from beginning by crossing off doubled value
# Time: O(n log n)
# Space: O(n)
if len(changed) % 2 != 0:
return []
counter = defaultdict(int)
for val in changed:
counter[val] += 1
changed.sort()
ans = []
for val in changed:
if val in counter and counter[val] != 0:
if val*2 not in counter or counter[val*2] == 0:
return []
counter[val] -= 1
counter[val*2] -= 1
ans.append(val)
return ans
|
find-original-array-from-doubled-array
|
[Python3] Greedy - Time: O(n log n) & Space: O(n)
|
jae2021
| 0
| 80
|
find original array from doubled array
| 2,007
| 0.409
|
Medium
| 28,020
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1485339/Python-Solution-Maximum-Earnings-from-Taxi
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
d = {}
for start,end,tip in rides:
if end not in d:
d[end] =[[start,tip]]
else:
d[end].append([start,tip])
dp = [0]*(n+1)
dp[0] = 0
for i in range(1,n+1):
dp[i] = dp[i-1]
if i in d:
temp_profit = 0
for start,tip in d[i]:
if (i-start)+tip+dp[start] > temp_profit:
temp_profit = i-start+tip+dp[start]
dp[i] = max(dp[i],temp_profit)
return dp[-1]
|
maximum-earnings-from-taxi
|
[Python] Solution - Maximum Earnings from Taxi
|
SaSha59
| 2
| 2,100
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,021
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1471590/Python3-dp
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
mp = {}
for start, end, tip in rides:
mp.setdefault(start, []).append((end, tip))
@cache
def fn(x):
"""Return max earning at x."""
if x == n: return 0
ans = fn(x+1)
for xx, tip in mp.get(x, []):
ans = max(ans, xx - x + tip + fn(xx))
return ans
return fn(1)
|
maximum-earnings-from-taxi
|
[Python3] dp
|
ye15
| 2
| 178
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,022
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1471590/Python3-dp
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
mp = {}
for start, end, tip in rides:
mp.setdefault(start, []).append((end, tip))
dp = [0]*(n+1)
for x in range(n-1, 0, -1):
dp[x] = dp[x+1]
for xx, tip in mp.get(x, []):
dp[x] = max(dp[x], xx - x + tip + dp[xx])
return dp[1]
|
maximum-earnings-from-taxi
|
[Python3] dp
|
ye15
| 2
| 178
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,023
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1470927/Greedy-Approach-oror-Clean-and-Concise-Code-oror-Well-Explained
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
rides.sort()
for ele in rides:
ele[2] += ele[1]-ele[0]
cp,mp = 0,0 # Current_profit, Max_profit
heap=[]
for s,e,p in rides:
while heap and heap[0][0]<=s:
et,tmp = heapq.heappop(heap)
cp = max(cp,tmp)
heapq.heappush(heap,(e,cp+p))
mp = max(mp,cp+p)
return mp
|
maximum-earnings-from-taxi
|
🐍 Greedy Approach || Clean & Concise Code || Well-Explained 📌📌
|
abhi9Rai
| 1
| 239
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,024
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1470927/Greedy-Approach-oror-Clean-and-Concise-Code-oror-Well-Explained
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
mapping = defaultdict(list)
for s, e, t in rides:
mapping[s].append([e, e - s + t]) # [end, dollar]
dp = [0] * (n + 1)
for i in range(n - 1, 0, -1):
for e, d in mapping[i]:
dp[i] = max(dp[i], dp[e] + d)
dp[i] = max(dp[i], dp[i + 1])
return dp[1]
|
maximum-earnings-from-taxi
|
🐍 Greedy Approach || Clean & Concise Code || Well-Explained 📌📌
|
abhi9Rai
| 1
| 239
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,025
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/2802924/Python-(Simple-Dynamic-Programming)
|
class Solution:
def maxTaxiEarnings(self, n, rides):
dict1 = defaultdict(list)
for s,e,t in rides:
dict1[e].append((s,e-s+t))
dp = [0]*(n+1)
for i in range(1,n+1):
dp[i] = dp[i-1]
for s,a in dict1[i]:
dp[i] = max(dp[i],dp[s] + a)
return dp[-1]
|
maximum-earnings-from-taxi
|
Python (Simple Dynamic Programming)
|
rnotappl
| 0
| 4
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,026
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1790532/Python3-DP-or-O(N%2BMlogM)-or-Explained-or-Beat-92.98
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
# Main Idea: DP
# Time Complexity: O(N+MlogM)
# Space Complexity: O(N)
# where N is `n` and M is the size of `rides`
# First, we sort `rides` by their `end_i`
rides = sorted(rides, key=lambda x: x[1])
rides = [(ride[0], ride[1], ride[1] - ride[0] + ride[2]) for ride in rides]
# Create a list for DP purposes
dp = [0 for _ in range(n+1)]
prev_res = 0
for s, e, m in rides:
# Fill the paths
index = e
while index >= 0 and dp[index] == 0:
dp[index] = prev_res
index -= 1
# Use DP to derive the most money we can earn prior to (including) the position `e`
# We compare two cases: take or not take the current passenger
dp[e] = max(dp[s]+m, dp[e])
prev_res = dp[e]
return dp[e]
|
maximum-earnings-from-taxi
|
[Python3] DP | O(N+MlogM) | Explained | Beat 92.98%
|
jackconvolution
| 0
| 137
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,027
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1471056/TLE-Bottom-Up-DP-greater-Optimized-Bottom-Up-DP-(python)
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
dp = [0]*(n+1)
for i in range(len(dp)):
for r in rides:
if r[1] <= i: # check if we've hit trips end point yet, then decide to take or not
trip_val = r[1] - r[0] + r[2]
dp[i] = max(trip_val + dp[r[0]], dp[i])
else: # if we dont take the trip
dp[i] = max(dp[i], dp[i-1])
return dp[-1]
|
maximum-earnings-from-taxi
|
TLE Bottom-Up DP -> Optimized Bottom-Up DP (python)
|
dimucc
| 0
| 151
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,028
|
https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1470862/Python-DP-solution.-Easy-to-understand-and-clean
|
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
rides_from_start = defaultdict(list)
for start, end, tip in rides:
rides_from_start[start].append((end, tip))
@cache
def recursive(actual_position):
if actual_position == n: # We are at the end
return 0
elif actual_position in rides_from_start:
maximum = 0
# take any of the rides starting at actual_position
for end, tip in rides_from_start[actual_position]:
maximum = max(maximum, end - actual_position + tip + recursive(end))
# dont take the ride and check the next position
maximum = max(maximum, recursive(actual_position + 1))
return maximum
else:
# check the next position
return recursive(actual_position+1)
return recursive(0)
|
maximum-earnings-from-taxi
|
[Python] DP solution. Easy to understand and clean
|
asbefu
| -1
| 169
|
maximum earnings from taxi
| 2,008
| 0.432
|
Medium
| 28,029
|
https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1471593/Python3-sliding-window
|
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
nums = sorted(set(nums))
ans = ii = 0
for i, x in enumerate(nums):
if x - nums[ii] >= n: ii += 1
ans = max(ans, i - ii + 1)
return n - ans
|
minimum-number-of-operations-to-make-array-continuous
|
[Python3] sliding window
|
ye15
| 5
| 218
|
minimum number of operations to make array continuous
| 2,009
| 0.458
|
Hard
| 28,030
|
https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1470979/Python-2-Solutions-Binary-search-(without-bisect)-and-brute-force
|
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
nums = sorted(set(nums))
answer = float("+inf")
for i, start in enumerate(nums):
search = start + n - 1 # number to search
start, end = 0, len(nums)-1
while start <= end:
mid = start + (end - start) // 2
if nums[mid] <= search:
idx = mid
start = mid + 1
else:
end = mid - 1
changes = idx - i + 1
answer = min(answer, n - changes)
return answer
|
minimum-number-of-operations-to-make-array-continuous
|
[Python] 2 Solutions Binary search (without bisect) and brute force
|
asbefu
| 1
| 114
|
minimum number of operations to make array continuous
| 2,009
| 0.458
|
Hard
| 28,031
|
https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1470979/Python-2-Solutions-Binary-search-(without-bisect)-and-brute-force
|
class Solution:
def minOperations(self, nums: List[int]) -> int:
answer = float("+inf")
for i in range(len(nums)):
minimum = nums[i]
used = set()
total = 0
for j in range(len(nums)):
if minimum <= nums[j] <= minimum + len(nums) - 1:
if nums[j] in used:
total += 1
else:
used.add(nums[j])
else:
total += 1
answer = min(answer, total)
return answer
|
minimum-number-of-operations-to-make-array-continuous
|
[Python] 2 Solutions Binary search (without bisect) and brute force
|
asbefu
| 1
| 114
|
minimum number of operations to make array continuous
| 2,009
| 0.458
|
Hard
| 28,032
|
https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1475303/Well-Written-and-Explained-oror-Simple-oror-96-faster
|
class Solution:
def minOperations(self, nums: List[int]) -> int:
n=len(nums)
nums = sorted(set(nums))
res = n
for i,st in enumerate(nums):
end = st+n-1
ind = bisect.bisect_right(nums,end)
unq_len = ind-i
res = min(res,n-unq_len)
return res
|
minimum-number-of-operations-to-make-array-continuous
|
📌📌 Well-Written and Explained || Simple || 96% faster 🐍
|
abhi9Rai
| 0
| 143
|
minimum number of operations to make array continuous
| 2,009
| 0.458
|
Hard
| 28,033
|
https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1471253/Python-3-Prefix-Sum-%2B-Binary-Search
|
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
ans = n
nums.sort()
cnt = Counter(nums)
# build key for repeated occurance
repeat = sorted(k for k in cnt if cnt[k] > 1)
# build prefix sum for repeated occurance need to be changed
repeat_change = list(accumulate([cnt[x] - 1 for x in repeat], initial=0))
for i in range(n):
# numbers left side all need to be changed
left = i
# numbers right side all need to be changed
loc = bisect.bisect(nums, nums[i] + n - 1)
right = n - loc
# calculate occurance of repeated number within [nums[i], nums[i] + n - 1]
repeat_l = bisect.bisect_left(repeat, nums[i])
repeat_r = bisect.bisect(repeat, nums[i] + n - 1)
ans = min(ans, left + right + repeat_change[repeat_r] - repeat_change[repeat_l])
return ans
|
minimum-number-of-operations-to-make-array-continuous
|
[Python 3] Prefix Sum + Binary Search
|
chestnut890123
| 0
| 86
|
minimum number of operations to make array continuous
| 2,009
| 0.458
|
Hard
| 28,034
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1472568/Python3-A-Simple-Solution-and-A-One-Line-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for o in operations:
if '+' in o:
x += 1
else:
x -= 1
return x
|
final-value-of-variable-after-performing-operations
|
[Python3] A Simple Solution and A One Line Solution
|
terrencetang
| 18
| 1,800
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,035
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1472568/Python3-A-Simple-Solution-and-A-One-Line-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if '+' in o else -1 for o in operations)
|
final-value-of-variable-after-performing-operations
|
[Python3] A Simple Solution and A One Line Solution
|
terrencetang
| 18
| 1,800
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,036
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1472879/Python-one-liner
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum(1 if '+' in op else -1 for op in operations)
|
final-value-of-variable-after-performing-operations
|
Python one-liner
|
blue_sky5
| 4
| 253
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,037
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2079406/Simple-Python-Soluution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x=0
for i in operations:
if(i=="X--" or i=="--X"):
x-=1
else:
x+=1
return x
|
final-value-of-variable-after-performing-operations
|
Simple Python Soluution
|
tusharkhanna575
| 3
| 343
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,038
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1548411/EASY-AND-SIMPLE-SOLN-(faster-than-91)
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for i in range(len(operations)):
if operations[i] == "++X" or operations[i] == "X++": x += 1
else: x -=1
return x
|
final-value-of-variable-after-performing-operations
|
EASY AND SIMPLE SOLN (faster than 91%)
|
anandanshul001
| 3
| 233
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,039
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1485582/Python-Simple-Line-faster-than-92.29
|
class Solution:
def finalValueAfterOperations(self, operations: list) -> int:
return sum([1 if "+" in op else -1 for op in operations ])
|
final-value-of-variable-after-performing-operations
|
Python Simple Line faster than 92.29%
|
1_d99
| 2
| 282
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,040
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2342727/C%2B%2BPython-O(N)-Solution-faster-than-91-submission
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
X=0
for o in operations:
if "+" in o:
X=X+1
else:
X=X-1
return X
|
final-value-of-variable-after-performing-operations
|
C++/Python O(N) Solution faster than 91% submission
|
arpit3043
| 1
| 106
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,041
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1703545/2011.-Final-Value-of-Variable-X%2B%2B-X-
|
class Solution(object):
def finalValueAfterOperations(self, operations):
"""
:type operations: List[str]
:rtype: int
"""
rValue = 0
for operation in operations:
if operation[1] == '+': # if the operation is X++ or ++X
rValue += 1
else: # if the operation is X-- or --X
rValue = rValue-1
return rValue
|
final-value-of-variable-after-performing-operations
|
2011. Final Value of Variable X++ / X--
|
ankit61d
| 1
| 103
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,042
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1593243/Very-fast-Python-Code-(4-lines)
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for val in operations:
x += 1 if "++" in val else -1
return x
|
final-value-of-variable-after-performing-operations
|
Very fast Python Code (4 lines)
|
Vladislav875
| 1
| 208
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,043
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1481162/1-line-solution-in-Python
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum("++" in op or -1 for op in operations)
|
final-value-of-variable-after-performing-operations
|
1-line solution in Python
|
mousun224
| 1
| 108
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,044
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2839374/Two-pointer-easy-python-solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
result = 0
l = 0
r = len(operations) - 1
mapper = lambda x: 1 if x in {"X++", "++X"} else -1
while l < r:
result += mapper(operations[l]) + mapper(operations[r])
l += 1
r -= 1
if len(operations) %2:
result += mapper(operations[l])
return result
|
final-value-of-variable-after-performing-operations
|
Two pointer easy python solution
|
Charan_coder
| 0
| 1
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,045
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2822029/One-line-code-in-Python
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
return sum ([1 if k in ("X++", "++X") else -1 for k in operations] )
|
final-value-of-variable-after-performing-operations
|
One line code in Python
|
DNST
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,046
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2815447/Fastest-and-Simplest-Solution-Python
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for i in operations:
if i == "++X" or i == "X++":
x += 1
else:
x -= 1
return x
|
final-value-of-variable-after-performing-operations
|
Fastest and Simplest Solution - Python
|
PranavBhatt
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,047
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2815311/Easiest-way-python
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x=0
for i in operations:
if "+" in i:
x=x+1
else:
x=x-1
return x
|
final-value-of-variable-after-performing-operations
|
Easiest way python
|
nishithakonuganti
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,048
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2814269/Simple-Python-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
increament = operations.count("X++") + operations.count("++X")
decreament = operations.count("X--") + operations.count("--X")
return increament - decreament
|
final-value-of-variable-after-performing-operations
|
Simple Python Solution
|
Shagun_Mittal
| 0
| 3
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,049
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2804315/PYTHON3-BEST
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for i in operations:
if '+' in i:
x += 1
else:
x -= 1
return x
|
final-value-of-variable-after-performing-operations
|
PYTHON3 BEST
|
Gurugubelli_Anil
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,050
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2797305/Python-Easy-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
res=0
for operation in operations:
if operation=="++X" or operation=="X++":
res+=1
else:
res-=1
return res
|
final-value-of-variable-after-performing-operations
|
Python Easy Solution
|
sbhupender68
| 0
| 1
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,051
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2793058/simple-python-solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
result= 0
for i in operations:
if "+" in i:
result += 1
elif "-" in i:
result -= 1
return result
|
final-value-of-variable-after-performing-operations
|
simple python solution
|
ft3793
| 0
| 1
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,052
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2743651/Fastest-Python-Codeoror98.39-Fasteroror3-Lines-Code
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
a=operations.count('--X')
b=operations.count('X--')
return (a+b)*(-1)+(len(operations)-(a+b))*(1)
|
final-value-of-variable-after-performing-operations
|
Fastest Python Code||98.39% Faster||3 Lines Code
|
sowmika_chaluvadi
| 0
| 4
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,053
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2743045/1-Line-Solution-Python-(3-Types-of-Approaches-Shown)
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x=0
# Naive Approach
for operation in operations:
if operation =="--X" or operation =="X--":
x-=1
elif operation == "X++" or operation == "++X" :
x = x + 1
else:
x=x
return x
|
final-value-of-variable-after-performing-operations
|
1 Line Solution - Python (3 Types of Approaches Shown)
|
avs-abhishek123
| 0
| 3
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,054
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2743045/1-Line-Solution-Python-(3-Types-of-Approaches-Shown)
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x=0
# 2 lines Approach
for operation in operations:
x = x-1 if (operation =="--X" or operation =="X--") else (x+1 if (operation == "X++" or operation == "++X") else x)
return x
|
final-value-of-variable-after-performing-operations
|
1 Line Solution - Python (3 Types of Approaches Shown)
|
avs-abhishek123
| 0
| 3
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,055
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2743045/1-Line-Solution-Python-(3-Types-of-Approaches-Shown)
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x=0
# 1 lines Approach
x = sum([ (x-1 if (operation =="--X" or operation =="X--") else (x+1 if (operation == "X++" or operation == "++X")else x)) for operation in operations ])
return x
|
final-value-of-variable-after-performing-operations
|
1 Line Solution - Python (3 Types of Approaches Shown)
|
avs-abhishek123
| 0
| 3
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,056
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2742666/Final-Value-of-Variable-After-Performing-Operations-Naive-Approach
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x= 0
for operation in operations:
if operation =="--X" or operation =="X--":
x-=1
elif operation == "X++" or operation == "++X" :
x = x + 1
else:
x=x
return x
|
final-value-of-variable-after-performing-operations
|
Final Value of Variable After Performing Operations - Naive Approach
|
avs-abhishek123
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,057
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2720395/Python-simple-solution-using-%22if%22
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
count = 0
for i in operations:
if i == "X--" or i == "--X":
count -= 1
elif i == "++X" or i == "X++":
count += 1
return count
|
final-value-of-variable-after-performing-operations
|
Python simple solution using "if"
|
maitrunghieu2287
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,058
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2691899/Python-with-minimal-code-two-examples
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
result = 0
for value in operations:
# The middle value is either + or - (X++ or ++X are both + at index 1)
result += 1 if value[1] == '+' else -1
return result
|
final-value-of-variable-after-performing-operations
|
Python with minimal code, two examples
|
user0564U
| 0
| 4
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,059
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2691899/Python-with-minimal-code-two-examples
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
# One line sum/generator, where True will sum to 1
return sum(i[1] == '+' or -1 for i in operations)
|
final-value-of-variable-after-performing-operations
|
Python with minimal code, two examples
|
user0564U
| 0
| 4
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,060
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2671457/Python-fast-and-simple
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
ans = 0
for o in operations:
if o[0] == "+" or o[-1] == "+":
ans += 1
elif o[0] == "-" or o[-1] == "-":
ans -= 1
return ans
|
final-value-of-variable-after-performing-operations
|
Python fast and simple
|
phantran197
| 0
| 5
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,061
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2650234/2-lines-simple-solution-O(1)-or-Python3
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = operations.count("X++") + operations.count("++X") - operations.count("X--") - operations.count("--X")
return x
|
final-value-of-variable-after-performing-operations
|
2 lines simple solution O(1) | Python3
|
landigf
| 0
| 4
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,062
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2646306/Super-Easy-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
count = 0
for s in operations:
if s == "--X" or s == "X--":
count -= 1
if s == "X++" or s == "++X":
count += 1
return count
|
final-value-of-variable-after-performing-operations
|
Super Easy Solution
|
mdfaisalabdullah
| 0
| 2
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,063
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2640172/Python-3-Counter-Beats-94
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
c = Counter(chain.from_iterable(operations))
return (c['+'] - c['-']) >> 1
|
final-value-of-variable-after-performing-operations
|
Python 3 Counter Beats 94%
|
godshiva
| 0
| 1
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,064
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2578938/Python-using-set
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
positive = {"X++", "++X"}
res = 0
for operation in operations:
if operation in positive:
res += 1
else:
res -= 1
return res
|
final-value-of-variable-after-performing-operations
|
Python using set
|
Vigneswar_A
| 0
| 22
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,065
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2555490/2-simple-python-solutions
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
X = 0
count_minus = operations.count("--X")
count_minus += operations.count("X--")
count_plus = operations.count("++X")
count_plus += operations.count("X++")
print(count_plus)
X -= (1*count_minus)
X += (1*count_plus)
return X
X = 0
inde = 0
plus = ["--X", "X--"]
while inde < len(operations):
if operations[inde] in plus:
X -= 1
inde += 1
else:
X += 1
inde += 1
return X
|
final-value-of-variable-after-performing-operations
|
2 simple python solutions
|
maschwartz5006
| 0
| 35
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,066
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2515200/My-python-solution
|
class Solution(object):
def finalValueAfterOperations(self, operations):
"""
:type operations: List[str]
:rtype: int
"""
val = 0
for i in operations:
if i == '--X' or i == 'X--':
val -=1
else:
val +=1
return val
|
final-value-of-variable-after-performing-operations
|
My python solution
|
savvy_phukan
| 0
| 53
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,067
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2453621/Python3-Solution-with-using-check-1-index
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
res = 0
for op in operations:
if op[1] == '-':
res -= 1
else:
res += 1
return res
|
final-value-of-variable-after-performing-operations
|
[Python3] Solution with using check 1 index
|
maosipov11
| 0
| 24
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,068
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2436708/Python-3-with-easily-readable-one-liner
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
'''1-liner w list comprehension'''
return sum([1 if op in ("++X", "X++") else -1 for op in operations])
|
final-value-of-variable-after-performing-operations
|
Python 3, with easily-readable one-liner
|
romejj
| 0
| 56
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,069
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2398591/Simple-python-code-with-explanation
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
#let the ans-> variable be 0
ans = 0
#iterate over the elements in list
for i in operations:
#if the element is "--X" or "X--"
if i in ["--X","X--"]:
#decrease the value of ans by 1
ans = ans - 1
#if the element is "++X" or "X++"
else:
#increase the value of ans by 1
ans = ans + 1
#return the value stored in ans variable
return ans
|
final-value-of-variable-after-performing-operations
|
Simple python code with explanation
|
thomanani
| 0
| 100
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,070
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2386064/No-if-else-or-switch-statements-Python-or-Faster-than-90
|
class Solution:
def add(self, x):
return x + 1
def sub(self, x):
return x - 1
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
d = {
'++X': self.add,
'X++': self.add,
'X--': self.sub,
'--X': self.sub
}
for op in operations:
x = d[op](x)
return x
|
final-value-of-variable-after-performing-operations
|
No if else | switch statements Python | Faster than 90%
|
prameshbajra
| 0
| 59
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,071
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2366588/Straightforward-Python3-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
value = 0
for op in operations:
if (op[1] == '+'):
value += 1
else:
value -= 1
return value
|
final-value-of-variable-after-performing-operations
|
Straightforward Python3 Solution ✅🐍
|
qing306037
| 0
| 55
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,072
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2351195/Faster-then-Buzz-Lightyear
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x= 0
for op in operations:
if op in ["--X","X--"]:
x -= 1
else:
x += 1
print(op,x)
return x
|
final-value-of-variable-after-performing-operations
|
Faster then Buzz Lightyear
|
RohanRob
| 0
| 35
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,073
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2290709/python3-oror-easy-solution-oror-O(N)
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
result=0
for i in operations:
if i[1]=='+':
result+=1
else:
result-=1
return result
|
final-value-of-variable-after-performing-operations
|
python3 || easy solution || O(N)
|
_soninirav
| 0
| 37
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,074
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2282725/Simple-Python-solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
n = 0
for i in range(len(operations)):
if operations[i] == "++X" or operations[i] == "X++":
n+=1
elif operations[i] == "--X" or operations[i] == "X--":
n-=1
return n
|
final-value-of-variable-after-performing-operations
|
Simple Python solution
|
anazzy
| 0
| 42
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,075
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2263347/3-simple-steps-using-Python
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
res = 0
for i in operations:
if i[0] == '-' or i[-1] == '-':
res -= 1
else:
res += 1
return res
|
final-value-of-variable-after-performing-operations
|
3 simple steps using Python
|
ankurbhambri
| 0
| 31
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,076
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2209090/Simple-Python-Solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
value = 0
for i in operations:
if(i == '++X' or i == 'X++'):
value += 1
else:
value -= 1
return value
|
final-value-of-variable-after-performing-operations
|
Simple Python Solution
|
kaus_rai
| 0
| 66
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,077
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2208181/FASTER-than-95-oror-EASY-SOLUTION-using-if-else
|
'''class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
initial=0
for i in operations:
if i=="--X" or i=="X--":
initial=initial-1
else:
initial=initial+1
return initial
print(finalValueAfterOperations(operations))'''
|
final-value-of-variable-after-performing-operations
|
FASTER than 95% || EASY SOLUTION using if-else
|
keertika27
| 0
| 76
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,078
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2196650/Easy-solution-using-a-dictionary
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
ops = {
'++X': 1,
'X++': 1,
'--X': -1,
'X--': -1
}
return sum([ops[op] for op in operations])
|
final-value-of-variable-after-performing-operations
|
Easy solution using a dictionary
|
Simzalabim
| 0
| 19
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,079
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2163988/iterative
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
# keep result starting at 0
# iterate each operatin
# if the operation contains - decrement res otherwise increment res
# return result after iteration
# Time O(N) SpaceL O(1)
res = 0
for oper in operations:
if '-' in oper:
res -= 1
else:
res += 1
return res
|
final-value-of-variable-after-performing-operations
|
iterative
|
andrewnerdimo
| 0
| 25
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,080
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2102771/Very-Short-solution-and-easy-to-understand
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
n=0
for i in operations:
if i== "X++" or i== "++X":
n+=1
else:
n-=1
return n
|
final-value-of-variable-after-performing-operations
|
Very Short solution and easy to understand
|
T1n1_B0x1
| 0
| 89
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,081
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2030675/Runtime%3A-34-ms-87.79
|
class Solution(object):
def finalValueAfterOperations(self, operations):
"""
:type operations: List[str]
:rtype: int
"""
X = 0
for operation in operations:
if operation == '++X' or operation == 'X++':
X = X + 1
elif operation == '--X' or operation == 'X--':
X = X - 1
return X
|
final-value-of-variable-after-performing-operations
|
Runtime: 34 ms 87.79% ට වඩා වේගවත්
|
akilaocj
| 0
| 62
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,082
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/2013084/Python3-using-for-and-if-else
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
value = 0;
for i in range(len(operations)):
operator = operations[i]
if operator == '++X' or operator == 'X++':
value += 1
else:
value -= 1
return value
|
final-value-of-variable-after-performing-operations
|
[Python3] using for and if else
|
Shiyinq
| 0
| 66
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,083
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1989166/java-python-easy-and-fast
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for s in operations :
if s[1] == '+' : x += 1
else : x -= 1
return x
|
final-value-of-variable-after-performing-operations
|
java, python - easy & fast
|
ZX007java
| 0
| 87
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,084
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1957596/Python3-Simple-solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
ans = 0
for operation in operations:
ans = ans + 1 if operation in ["++X","X++"] else ans-1
return ans
|
final-value-of-variable-after-performing-operations
|
Python3 Simple solution
|
firefist07
| 0
| 66
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,085
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1950513/Beginner-friendly-solution-oror-python3
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
result = 0
for i in operations:
if i == '--X' or i == 'X--':
result -= 1
else:
result += 1
return result
|
final-value-of-variable-after-performing-operations
|
Beginner friendly solution || python3
|
ApacheRosePeacock
| 0
| 47
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,086
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1936819/Python-Solution-%2B-One-Liner!
|
class Solution:
def finalValueAfterOperations(self, operations):
x = 0
for op in operations:
if "++" in op: x += 1
elif "--" in op: x -= 1
else: raise Exception("Invalid operation")
return x
|
final-value-of-variable-after-performing-operations
|
Python - Solution + One-Liner!
|
domthedeveloper
| 0
| 78
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,087
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1936819/Python-Solution-%2B-One-Liner!
|
class Solution:
def finalValueAfterOperations(self, operations):
return sum("++" in op or -1 for op in operations)
|
final-value-of-variable-after-performing-operations
|
Python - Solution + One-Liner!
|
domthedeveloper
| 0
| 78
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,088
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1932535/Python-solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
X=0
for i in operations:
X= X+1 if i in ["++X","X++"] else X-1
return X
|
final-value-of-variable-after-performing-operations
|
Python solution
|
Swamy54
| 0
| 27
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,089
|
https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1932535/Python-solution
|
class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
X=0
for i in operations:
X= X+1 if i[1]=="+" else X-1
return X
|
final-value-of-variable-after-performing-operations
|
Python solution
|
Swamy54
| 0
| 27
|
final value of variable after performing operations
| 2,011
| 0.888
|
Easy
| 28,090
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1477177/Python3-or-Brute-Force-(TLE)-and-O(n)-solution-with-explanation-or-86ile-runtime
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
beauty=[0]*len(nums)
for i in range(1,len(nums)-1):
leftarr=nums[:i]
rightarr=nums[i+1:]
if(max(leftarr)<nums[i] and min(rightarr)>nums[i]):
beauty[i]=2
elif(nums[i-1]<nums[i] and nums[i+1]>nums[i]):
beauty[i]=1
else:
beauty[i]=0
return sum(beauty)
|
sum-of-beauty-in-the-array
|
Python3 | Brute Force (TLE) and O(n) solution with explanation | 86%ile runtime
|
aaditya47
| 1
| 54
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,091
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1477177/Python3-or-Brute-Force-(TLE)-and-O(n)-solution-with-explanation-or-86ile-runtime
|
class Solution:
def sumOfBeauties(self, a: List[int]) -> int:
temp,temp2=a[0],a[-1]
left=([a[0]]+[0]*(len(a)-1))
right=[0]*(len(a)-1) + [a[-1]]
for i in range(1,len(a)):
left[i]=max(a[i-1],temp)
temp=left[i]
for i in range(len(a)-2,-1,-1):
right[i]=min(a[i+1],temp2)
temp2=right[i]
res=0
for i in range(1,len(a)-1):
if(a[i]>left[i] and a[i]<right[i]):
res+=2
elif(a[i]>a[i-1] and a[i]<a[i+1]):
res+=1
return res
|
sum-of-beauty-in-the-array
|
Python3 | Brute Force (TLE) and O(n) solution with explanation | 86%ile runtime
|
aaditya47
| 1
| 54
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,092
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/2825351/PreSum-solution-in-Python
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
preSum1, curr = [nums[0]], 0
for i in range(1, len(nums)):
curr = max (nums[i-1], curr)
preSum1.append(curr)
pre2, curr = [nums[-1]], 10**5 + 2
for i in range(len(nums)-2, -1, -1):
curr = min(nums[i+1], curr)
pre2.append(curr)
preSum2 = pre2[::-1]
result = 0
for i in range(1, len(nums)-1):
if preSum1[i] < nums[i] < preSum2[i]:
result += 2
elif nums[i-1] < nums[i] < nums[i+1]:
result += 1
return result
|
sum-of-beauty-in-the-array
|
PreSum solution in Python
|
DNST
| 0
| 1
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,093
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/2721878/Python-Easy-Solution-or-Faster-than-100-or
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
n = len(nums)
left = [-1 for i in range(n)]
right = [-1 for i in range(n)]
mx = -1
for i in range(n):
left[i] = mx
mx = max(mx, nums[i])
mx = 10**9
for i in range(n-1,-1,-1):
right[i] = mx
mx = min(mx, nums[i])
# print(left)
# print(right)
res = 0
for i in range(1, n-1):
if left[i] < nums[i] < right[i]:
res += 2
elif nums[i - 1] < nums[i] < nums[i + 1]:
res += 1
return res
|
sum-of-beauty-in-the-array
|
Python Easy Solution | Faster than 100% |
|
sami2002
| 0
| 10
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,094
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1766916/Python-3-two-pass-O(n)-time-O(n)-space
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
n = len(nums)
minFromRight = [0] * n
curMin = nums[-1]
for i in range(n-2, 0, -1):
minFromRight[i] = curMin
curMin = min(curMin, nums[i])
res = 0
curMax = nums[0]
for i in range(1, n-1):
if curMax < nums[i] < minFromRight[i]:
res += 2
elif nums[i-1] < nums[i] < nums[i+1]:
res += 1
curMax = max(curMax, nums[i])
return res
|
sum-of-beauty-in-the-array
|
Python 3, two pass, O(n) time, O(n) space
|
dereky4
| 0
| 72
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,095
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1514274/Two-passes-O(n)-89-speed
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
len_nums = len(nums)
suffix_min = nums.copy()
for i in range(len_nums - 2, -1, -1):
suffix_min[i] = min(suffix_min[i], suffix_min[i + 1])
pre_max = nums[0]
beauty = 0
for i in range(1, len_nums - 1):
if pre_max < nums[i] < suffix_min[i + 1]:
beauty += 2
elif nums[i - 1] < nums[i] < nums[i + 1]:
beauty += 1
pre_max = max(pre_max, nums[i])
return beauty
|
sum-of-beauty-in-the-array
|
Two passes, O(n), 89% speed
|
EvgenySH
| 0
| 118
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,096
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1478873/Python3-2-pass
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
suffix = [inf] * len(nums) # suffix of min
for i in range(len(nums)-2, 0, -1):
suffix[i] = min(suffix[i+1], nums[i+1])
ans = prefix = 0
for i in range(1, len(nums)-1):
prefix = max(prefix, nums[i-1])
if prefix < nums[i] < suffix[i]: ans += 2
elif nums[i-1] < nums[i] < nums[i+1]: ans += 1
return ans
|
sum-of-beauty-in-the-array
|
[Python3] 2-pass
|
ye15
| 0
| 67
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,097
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1473231/Python-3-Two-heaps
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
left, right = [], []
for i, num in enumerate(nums):
heappush(right, (num, i))
ans = 0
n = len(nums)
for i in range(1, n-1):
heappush(left, (-nums[i-1], i-1))
while right and right[0][1] <= i:
heappop(right)
if right and -left[0][0] < nums[i] < right[0][0]:
ans += 2
elif nums[i-1] < nums[i] < nums[i+1]:
ans += 1
return ans
|
sum-of-beauty-in-the-array
|
[Python 3] Two heaps
|
chestnut890123
| 0
| 35
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,098
|
https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1472602/Python-3-oror-Using-Prefix_maxandSuffix_min-oror-Self-Explanatory-oror-Easy-Understandable
|
class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
suffix_min=[float('inf')]*len(nums)
prefix_max=[float('-inf')]*len(nums)
prefix_max[0]=nums[0]
for i in range(1,len(nums)):
prefix_max[i]=max(prefix_max[i-1],nums[i-1])
suffix_min[-1]=nums[-1]
for i in range(len(nums)-2,-1,-1):
suffix_min[i]=min(suffix_min[i+1],nums[i+1])
beauty_sum=0
for i in range(1,len(nums)-1):
if prefix_max[i]<nums[i]<suffix_min[i]:
beauty_sum+=2
elif nums[i-1]<nums[i]<nums[i+1]:
beauty_sum+=1
return beauty_sum
|
sum-of-beauty-in-the-array
|
Python 3 || Using Prefix_max&Suffix_min || Self-Explanatory || Easy-Understandable
|
bug_buster
| 0
| 35
|
sum of beauty in the array
| 2,012
| 0.467
|
Medium
| 28,099
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.