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/rearrange-characters-to-make-target-string/discuss/2380635/Fast-and-easy-hashmap-%2B-integer-division-python-with-explanation
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
d1 = {} #create counter for target
for i in target:
if i in d1:
d1[i]+=1
else:
d1[i]=1
d2={} #create counter for s
for i in s:
if i in d1:
if i in d2:
d2[i]+=1
else:
d2[i]=1
min_=101
for i in d1:
if i in d2:
min_=min(d2[i]//d1[i],min_) #integer division count of letter in s by count of letter in target
else:
return 0
return min_
|
rearrange-characters-to-make-target-string
|
Fast & easy hashmap + integer division [python] with explanation
|
sunakshi132
| 0
| 48
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,600
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2313864/Python3-freq-table
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
freq = Counter(s)
return min(freq[k]//v for k, v in Counter(target).items())
|
rearrange-characters-to-make-target-string
|
[Python3] freq table
|
ye15
| 0
| 25
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,601
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2285164/Python-easy-1-Liner-beats-~92
|
class Solution:
def rearrangeCharacters(self, s: str, t: str) -> int:
return min([Counter(s)[ch] // Counter(t)[ch] for ch in t])
|
rearrange-characters-to-make-target-string
|
Python easy 1-Liner, beats ~92 %
|
amaargiru
| 0
| 63
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,602
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2278442/Easy-Python3-Solution-or-Beginner-friendly-Approach
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
res = 0
ss = ""
temp = []
for i in s:
if i in target:
ss += i
if len(ss) == len(target) and sorted(ss) == sorted(target):
res += 1
else:
for i in target:
temp.append(ss.count(i)//target.count(i))
res += min(temp)
return(res)
|
rearrange-characters-to-make-target-string
|
Easy Python3 Solution | Beginner-friendly Approach
|
RatnaPriya
| 0
| 44
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,603
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2127373/Python-oror-HashMap-Easy
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
counter = defaultdict(int)
for char in s:
if char in target:
counter[char] += 1
char = target[0]
i = 0
count = 0
while counter[char]:
counter[char] -= 1
if counter[char] < 0:
del counter[char]
i += 1
if i == len(target):
i = 0
count += 1
char = target[i]
return count
|
rearrange-characters-to-make-target-string
|
Python || HashMap Easy
|
morpheusdurden
| 0
| 73
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,604
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2116151/Python-Easy-to-understand-Solution
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
s_dic = {}
for i in s:
s_dic[i] = s_dic.get(i, 0) + 1
target_dic = {}
for i in target:
target_dic[i] = target_dic.get(i, 0) + 1
s_list = sorted(s_dic)
target_list = sorted(target_dic)
count = []
for i in range(len(target_list)):
count.append(s.count(target_list[i]) // target_dic[target_list[i]])
ans = 0
ans =min(count)
return ans
|
rearrange-characters-to-make-target-string
|
✅Python Easy-to-understand Solution
|
chuhonghao01
| 0
| 53
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,605
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2099780/Python-interesting-solution
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
ans = []
for i in set(target):
ans.append(s.count(i)//target.count(i))
return min(ans)
|
rearrange-characters-to-make-target-string
|
Python interesting solution
|
StikS32
| 0
| 56
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,606
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2098765/Python-Easy-solution-with-complexities
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
answer = len(s)
dicS = {}
dicT = {}
for i in s:
if i not in dicS:
dicS[i] = 1
else:
dicS[i] = dicS[i] + 1
for i in target:
if i not in dicT:
dicT[i] = 1
else:
dicT[i] = dicT[i] + 1
# instead of dict, here we can use a set() as well
for i in dicT.keys():
if i not in dicS:
return 0
x = dicS[i]//dicT[i]
answer = min(answer,x)
return answer
# time O(s+target+target) = O(n)
# space O(s+target) = O(n)
from collections import Counter
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
answer = len(s)
dicS = Counter(s)
dicT = Counter(target)
for i in dicT.keys():
if i not in dicS:
return 0
x = dicS[i]//dicT[i]
answer = min(answer,x)
return answer
# time O(s+target+target) = O(n)
# space O(s+target) = O(n)
|
rearrange-characters-to-make-target-string
|
[Python] Easy solution with complexities
|
mananiac
| 0
| 43
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,607
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2093429/python-3-oror-two-hash-maps
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
sCount = collections.Counter(s)
targetCount = collections.Counter(target)
return min(sCount[c] // targetCount[c] for c in targetCount)
|
rearrange-characters-to-make-target-string
|
python 3 || two hash maps
|
dereky4
| 0
| 29
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,608
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2091462/python-java-ASCII
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
letters = [0]*26
targetl = [0]*26
for i in range(len(s)):
letters[ord(s[i]) - 97] += 1
for i in range(len(target)):
targetl[ord(target[i]) - 97] += 1
ans = len(s)
for i in range(26):
if targetl[i] != 0:
ans = min(ans, letters[i]//targetl[i])
return ans
|
rearrange-characters-to-make-target-string
|
python, java - ASCII
|
ZX007java
| 0
| 22
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,609
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2088801/Python-Fast-or-Easy-or-3-lines
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
hm_s = Counter(s)
hm_t = Counter(target)
return min((hm_s.get(k, 0) // hm_t[k]) for k in hm_t)
|
rearrange-characters-to-make-target-string
|
Python Fast | Easy | 3 lines
|
Nk0311
| 0
| 30
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,610
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2087861/Python-easy-solution
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
c1 = Counter(target)
c2 = Counter(s)
ans = float('inf')
for k in c1:
ans = min(c2[k] // c1[k], ans)
return ans
|
rearrange-characters-to-make-target-string
|
Python easy solution
|
user6397p
| 0
| 12
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,611
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2086110/Easy-python-Solution-Using-dictionary
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
d={}
for i in target:
if i not in d:
d[i]=1
else:
d[i]+=1
for k in d:
if k in s:
d1[k]=s.count(k)
else:
d1[k]=0
m=float("inf")
for k,v in d.items():
m=min(m,d1[k]//v)
return m
|
rearrange-characters-to-make-target-string
|
Easy python Solution Using dictionary
|
a_dityamishra
| 0
| 31
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,612
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2085893/Pyhton-oror-simple-approach-oror-Using-Counter
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
c1=Counter(s)
c2=Counter(target)
cnt=float("inf")
for i in c2:
cnt=min(cnt,c1[i]//c2[i])
return cnt
|
rearrange-characters-to-make-target-string
|
Pyhton || simple approach || Using Counter
|
aditya1292
| 0
| 33
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,613
|
https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2085893/Pyhton-oror-simple-approach-oror-Using-Counter
|
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
c1=Counter(s)
c2=Counter(target)
cnt=0
while (c2&c1)==c2:
cnt+=1
c1=c1-c2
return (cnt)
|
rearrange-characters-to-make-target-string
|
Pyhton || simple approach || Using Counter
|
aditya1292
| 0
| 33
|
rearrange characters to make target string
| 2,287
| 0.578
|
Easy
| 31,614
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085723/Simple-Python-with-explanation
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
s = sentence.split() # convert to List to easily update
m = discount / 100
for i,word in enumerate(s):
if word[0] == "$" and word[1:].isdigit(): # Check whether it is in correct format
num = int(word[1:]) * (1-m) # discounted price
w = "$" + "{:.2f}".format(num) #correctly format
s[i] = w #Change inside the list
return " ".join(s) #Combine the updated list
```
|
apply-discount-to-prices
|
Simple Python with explanation
|
Eba472
| 7
| 311
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,615
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2087488/Python-1-Liner-or-Fast-Solution
|
class Solution:
def discountPrices(self, s: str, d: int) -> str:
return ' '.join((f"${(int(w[1:])*(1-(d/100))):.2f}" if w.startswith('$') and w[1:].isnumeric() else w for w in s.split()))
|
apply-discount-to-prices
|
✅ Python 1 Liner | Fast Solution
|
Nk0311
| 2
| 94
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,616
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2086112/Python-RegExp-ONE-FUNCTION-CALL
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
return re.sub(
r"(?:(?<=\s)|(?<=^))\$\d+(?:(?=\s)|(?=$))",
lambda x: "${:.2f}".format(float(x.group(0)[1:]) * (100 - discount) / 100),
sentence,
)
|
apply-discount-to-prices
|
Python RegExp – ONE FUNCTION CALL
|
miguel_v
| 2
| 24
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,617
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2372620/Python3-Regex-substitution
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
"""If you use regex, now you have two problems.
Lots of trial and error on regex101.com
254 ms, faster than 40.17%
"""
def repl(m):
rep = float(m.group(2)) * (100 - discount) / 100
return f'${rep:.2f}'
return re.sub(r'(^|(?<=\s))\$(\d+)(?=\s|$)', repl, sentence)
|
apply-discount-to-prices
|
[Python3] Regex substitution
|
FanchenBao
| 1
| 24
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,618
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2110834/Python-or-Easy
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
words = sentence.split()
calc_price = lambda cost, discount: cost * (discount / 100)
for i, w in enumerate(words):
if w.startswith("$"):
price = w[1:]
if price and "$" not in price and price.isdigit():
words[i] = f'${int(price) - calc_price(int(price), discount):.2f}'
return " ".join(words)
|
apply-discount-to-prices
|
Python | Easy ✅
|
anuragsrawat
| 1
| 90
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,619
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085796/Python-Short
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
splited_sent = sentence.split()
discount = 1 - (discount / 100)
for i in range(len(splited_sent)):
price_str = splited_sent[i]
if price_str[0] == '$' and price_str[1:].isdigit():
price = int(price_str[1:]) * discount
splited_sent[i] = '$' + f'{price:.2f}'
return ' '.join(splited_sent)
|
apply-discount-to-prices
|
Python Short
|
yzhao156
| 1
| 37
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,620
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085659/Python-Easy-Solution-with-Comments
|
class Solution:
# Function to check if value is int or not
def isint(self, x):
try:
a = float(x)
b = int(a)
except (TypeError, ValueError):
return False
else:
return a == b
# Function to check if value is float or not
def isfloat(self, x):
try:
a = float(x)
except (TypeError, ValueError):
return False
else:
return True
def discountPrices(self, sentence: str, discount: int) -> str:
sentence = sentence.split()
for i, val in enumerate(sentence):
if len(val) > 1 and val[0] == '$': # Store price in temporary variable tmp = val[1:] # Check if the value is either int or float, if yes then only apply discount if self.isint(tmp) or self.isfloat(tmp): tmp = float(tmp) if discount == 100: sentence[i] = '$0.00'
else:
disc = (tmp * discount) / 100
disc_price = tmp - disc
# Change discounted price to 2 decimal places
sentence[i] = '$' + str(format(disc_price, '.2f'))
return ' '.join(sentence)
|
apply-discount-to-prices
|
Python Easy Solution with Comments
|
MiKueen
| 1
| 78
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,621
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2808225/Intuitive-Python-Solution-beats-94-.
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
d = 1 - (discount / 100) #calculate the discount
stack = sentence.split(" ") #split the sentence by spaces
for i, word in enumerate(stack):
if word[0] == '$' and word[1:].isnumeric():
x = int(word[1:]) * d
stack[i] = '$' + str("%.2f" % x)
return " ".join(stack)
|
apply-discount-to-prices
|
Intuitive Python Solution - beats 94% .
|
MaverickEyedea
| 0
| 3
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,622
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2725982/easy-solution
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
l=sentence.split(' ')
t=[]
for i in l:
if i[0]=='
``` and i[1:].isdigit():
p=i[1:]
p=int(p)-(int(p)*(discount/100))
p=str(format(p,'.2f'))
i=i[0]+p
t.append(i)
else:
t.append(i)
return " ".join(t)
|
apply-discount-to-prices
|
easy solution
|
sindhu_300
| 0
| 3
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,623
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2712123/Python-Easy-Solution
|
class Solution:
def ifPrice(self, word: str) -> bool:
return word[1:].isdigit() and word[0]=='$'
def getPrice(self, word: str, discount: int) -> str:
price = float(word[1:])
newPrice = price*(100-discount)/100
return f"{word[0]}{newPrice:.2f}"
def discountPrices(self, sentence: str, discount: int) -> str:
words = sentence.split(" ")
for i in range(len(words)):
#If it is a price, then apply update
if self.ifPrice(words[i]):
words[i] = self.getPrice(words[i], discount)
return " ".join(words)
|
apply-discount-to-prices
|
Python Easy Solution
|
abrarjahin
| 0
| 4
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,624
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2313926/Python3-simulation
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
words = sentence.split()
ans = []
for word in words:
if word.startswith('$') and word[1:].isdigit():
word = f'${int(word[1:])*(1-discount/100):.2f}'
ans.append(word)
return ' '.join(ans)
|
apply-discount-to-prices
|
[Python3] simulation
|
ye15
| 0
| 27
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,625
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2214643/Python-interesting-solution-using-built-ins
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
arr = sentence.split()
for i in range(len(arr)):
if arr[i].count('$') == 1 and arr[i][0] == '$' and len(arr[i]) > 1 and arr[i][1:].isdigit():
arr[i] = '${:.2f}'.format(float(arr[i][1:])-(float(arr[i][1:])*(discount/100)))
return ' '.join(arr)
|
apply-discount-to-prices
|
Python interesting solution using built-ins
|
StikS32
| 0
| 48
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,626
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2108645/Easy-python-solution
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
splitted = sentence.split(" ")
for i,val in enumerate(splitted):
potentialNum = val[1:]
if val[0] == "$" and (potentialNum.isdigit()):
potentialNum = float(potentialNum)
tmp = potentialNum - (potentialNum*discount)/100
splitted[i] = "${0:.2f}".format(tmp)
return " ".join(splitted)
|
apply-discount-to-prices
|
Easy python solution
|
m0hsin
| 0
| 48
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,627
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2103505/Python-Easy-Solution
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
ans = []
for word in sentence.split():
try:
if word[0] != '$': x = int('exception')
res = format((100 - discount) / 100 * int(word[1:]), '.2f')
ans.append('$' + str(res))
except:
ans.append(word)
return ' '.join(ans)
|
apply-discount-to-prices
|
✅ Python Easy Solution
|
dhananjay79
| 0
| 42
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,628
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2094563/Python-easy-solution-faster-than-85
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
sen_split = sentence.split()
res = ""
for i in sen_split:
if i.startswith("$") and i[1:].isnumeric(): amt = float(i[1:]) discounted = amt - (amt * (discount / 100)) res += "$" + "{:.2f}".format(discounted) + " "
else:
res += i + " "
return res.strip()
|
apply-discount-to-prices
|
Python easy solution faster than 85%
|
alishak1999
| 0
| 20
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,629
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2086123/Easy-Python-solution
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
l=list(sentence.split())
ls=[]
for i in l:
if i[0]=="$" and i.count("$")==1 and i[-1] in '0123456789':
i=i[0]+"{0:.2f}".format(int(i[1:])-int(i[1:])*discount/100)
ls.append(i)
else:
ls.append(i)
return " ".join(ls)
|
apply-discount-to-prices
|
Easy Python solution
|
a_dityamishra
| 0
| 12
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,630
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085874/Python-oror-Simple-4-liner
|
class Solution:
def discountPrices(self, sentence: str, dis: int) -> str:
s=sentence.split()
for i in range(len(s)):
if s[i][0]=="$" and s[i][1:].isdigit():
p=("$"+str(format(int(s[i][1:])-(dis*0.01*int(s[i][1:])),".2f")))
s[i]=p
return " ".join(s)
|
apply-discount-to-prices
|
Python || Simple 4 liner
|
aditya1292
| 0
| 20
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,631
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085850/PYTHON-oror-SIMPLE-APPROACH-oror-WITH-COMMENTS-oror-O(N)
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
# Splitting sentence into words
words = sentence.split()
for i,j in enumerate(words):
# Base Cases Check
if j[0] == "$" and j.count('$') == 1 and len(j)>1 and j[1:].isnumeric():
# Finding the discount value and subtracting from the original value
words[i] = "${:.2f}".format(int(j[1:]) - (int(j[1:])*discount)/100)
return(" ".join(words))
|
apply-discount-to-prices
|
PYTHON || SIMPLE APPROACH || WITH COMMENTS || O(N)
|
klmsathish
| 0
| 13
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,632
|
https://leetcode.com/problems/apply-discount-to-prices/discuss/2085672/Python-or-Easy-to-Understand
|
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
strings = sentence.split(' ')
result = []
for string in strings:
if string[0] == '$': tmp = string[1:] tmp.replace('.', '') if tmp.isdigit(): new = (float)(string[1:]) * ((100 - discount) / 100) new = "$" + "{:.2f}".format(new)
result.append(new)
else:
result.append(string)
else:
result.append(string)
return " ".join(result)
|
apply-discount-to-prices
|
Python | Easy to Understand
|
Mikey98
| 0
| 20
|
apply discount to prices
| 2,288
| 0.274
|
Medium
| 31,633
|
https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2567529/BFS-with-updating-neighbours-or-O(n)-or-Python3
|
class Solution:
def totalSteps(self, nums: List[int]) -> int:
n = len(nums)
l = [i-1 for i in range(n)]
r = [i+1 for i in range(n)]
q = []
dist = dict()
ans = 0
for i in range(1, n):
if nums[i] < nums[i-1]:
q.append(i)
dist[i] = 1
ans = 1
while len(q) != 0:
u = q.pop(0)
ans = max(ans, dist[u])
if r[u] < n:
l[r[u]] = l[u]
if l[u] > -1:
r[l[u]] = r[u]
if r[u] not in dist and r[u] < n and nums[r[u]] < nums[l[u]]:
dist[r[u]] = dist[u] + 1
q.append(r[u])
return ans
|
steps-to-make-array-non-decreasing
|
BFS with updating neighbours | O(n) | Python3
|
DheerajGadwala
| 0
| 67
|
steps to make array non decreasing
| 2,289
| 0.214
|
Medium
| 31,634
|
https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2341808/Python3-or-Stack%2BDP
|
class Solution:
def totalSteps(self, nums: List[int]) -> int:
n=len(nums)
dp=[0]*n
stack=[]
for i in range(n-1,-1,-1):
while stack and nums[i]>nums[stack[-1]]:
dp[i]=max(dp[i]+1,dp[stack[-1]])
stack.pop()
stack.append(i)
return max(dp)
|
steps-to-make-array-non-decreasing
|
[Python3] | Stack+DP
|
swapnilsingh421
| 0
| 146
|
steps to make array non decreasing
| 2,289
| 0.214
|
Medium
| 31,635
|
https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2313932/Python3-mono-stack
|
class Solution:
def totalSteps(self, nums: List[int]) -> int:
ans = 0
stack = []
for x in nums:
val = 1
while stack and stack[-1][0] <= x: val = max(val, stack.pop()[1]+1)
if not stack: val = 0
stack.append((x, val))
ans = max(ans, val)
return ans
|
steps-to-make-array-non-decreasing
|
[Python3] mono-stack
|
ye15
| 0
| 118
|
steps to make array non decreasing
| 2,289
| 0.214
|
Medium
| 31,636
|
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2313936/Python3-Dijkstra's-algo
|
class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dist = [[inf]*n for _ in range(m)]
dist[0][0] = 0
pq = [(0, 0, 0)]
while pq:
x, i, j = heappop(pq)
if i == m-1 and j == n-1: return x
for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):
if 0 <= ii < m and 0 <= jj < n and x + grid[ii][jj] < dist[ii][jj]:
dist[ii][jj] = x + grid[ii][jj]
heappush(pq, (dist[ii][jj], ii, jj))
|
minimum-obstacle-removal-to-reach-corner
|
[Python3] Dijkstra's algo
|
ye15
| 1
| 32
|
minimum obstacle removal to reach corner
| 2,290
| 0.487
|
Hard
| 31,637
|
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2175710/Python-easy-to-read-and-undertand-or-01-BFS
|
class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
if grid[0][0] == 0:
q = [(0, 0, 0)]
else:
q = [(0, 0, 1)]
visit = set()
while q:
cost, x, y = q.pop(0)
#print(x, y, cost)
if x == m-1 and y == n-1:
return cost
if x > 0 and (x-1, y) not in visit:
visit.add((x-1, y))
if grid[x-1][y] == 0:
q.insert(0, (cost, x-1, y))
else:
q.append((cost+1, x-1, y))
if y > 0 and (x, y-1) not in visit:
visit.add((x, y-1))
if grid[x][y-1] == 0:
q.insert(0, (cost, x, y-1))
else:
q.append((cost+1, x, y-1))
if x < m-1 and (x+1, y) not in visit:
visit.add((x+1, y))
if grid[x+1][y] == 0:
q.insert(0, (cost, x+1, y))
else:
q.append((cost+1, x+1, y))
if y < n-1 and (x, y+1) not in visit:
visit.add((x, y+1))
if grid[x][y+1] == 0:
q.insert(0, (cost, x, y+1))
else:
q.append((cost+1, x, y+1))
|
minimum-obstacle-removal-to-reach-corner
|
Python easy to read and undertand | 01 BFS
|
sanial2001
| 1
| 63
|
minimum obstacle removal to reach corner
| 2,290
| 0.487
|
Hard
| 31,638
|
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2096414/Clean-Python-Code-or-BFS-%2B-deque
|
class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
q = deque([(0, 0, 0)])
d = {(0, 0): 0}
while q:
for _ in range(len(q)):
i, j, dist = q.pop()
for r, c in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
if (r, c) == (m - 1, n - 1):
return dist
if 0 <= r < m and 0 <= c < n and (r, c) not in d:
cur_dist = dist + grid[r][c]
d[(r, c)] = cur_dist
if grid[r][c]:
q.appendleft((r, c, cur_dist))
else:
q.append((r, c, cur_dist))
return d[(m - 1, n - 1)]
|
minimum-obstacle-removal-to-reach-corner
|
Clean Python Code | BFS + deque
|
yzhao156
| 0
| 18
|
minimum obstacle removal to reach corner
| 2,290
| 0.487
|
Hard
| 31,639
|
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2088835/Python3-Easy-to-Understand-or-BFS
|
class Solution:
def minimumObstacles(self, grid: List[List[int]]) -> int:
target = (len(grid)-1, len(grid[0])-1)
state = (0, 0) # x, y
visited = {state: 0} # {(x, y): least obstacles removed to reach this state}
queue = [(0,state)] #obstacles removed, (x, y)
m = float('inf') #number of least obstacles removed
while queue:
removed, (row, col) = heapq.heappop(queue) #pop the least obstacles removed state
if (row, col) == target:
m = removed if removed<m else m #updates number of least obstacles removed
for x, y in [(row-1, col), (row+1, col), (row, col+1), (row, col-1)]:
if (x>=0 and x<=target[0]) and (y>=0 and y<=target[1]):
rmv = removed + grid[x][y]
new_state = (x, y)
if new_state not in visited.keys() or (new_state in visited and rmv<visited[new_state]):
visited[new_state] = rmv
heapq.heappush(queue, (rmv, new_state))
return m
|
minimum-obstacle-removal-to-reach-corner
|
[Python3] Easy to Understand | BFS
|
VuwuV
| 0
| 48
|
minimum obstacle removal to reach corner
| 2,290
| 0.487
|
Hard
| 31,640
|
https://leetcode.com/problems/min-max-game/discuss/2112349/Python-Easy-Approach
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
l=nums
while len(l)>1:
is_min=True
tmp=[]
for i in range(0, len(l), 2):
if is_min:
tmp.append(min(l[i:i+2]))
else:
tmp.append(max(l[i:i+2]))
is_min=not is_min
l=tmp
return l[0]
|
min-max-game
|
✅ Python Easy Approach
|
constantine786
| 8
| 503
|
min max game
| 2,293
| 0.643
|
Easy
| 31,641
|
https://leetcode.com/problems/min-max-game/discuss/2160259/Python-Solution-87.74-faster
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
n=len(nums)
newNums=[]*n
while(n!=1):
n=n//2
newNums=[]*n
for i in range(n):
if i%2==0:
newNums.append(min(nums[2 * i], nums[2 * i + 1]))
else:
newNums.append(max(nums[2 * i], nums[2 * i + 1]))
nums=newNums
return nums[0]
|
min-max-game
|
Python Solution- 87.74% faster
|
T1n1_B0x1
| 1
| 53
|
min max game
| 2,293
| 0.643
|
Easy
| 31,642
|
https://leetcode.com/problems/min-max-game/discuss/2115134/Python-oror-Easy-Solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
if len(nums) == 1: return nums[0]
newNums = [0]*(len(nums)//2)
for i in range(len(nums)//2):
if i % 2 == 0:
newNums[i] = min( nums[2*i], nums[2*i + 1] )
else: newNums[i] = max(nums[2*i], nums[2*i + 1] )
return self.minMaxGame(newNums)
|
min-max-game
|
Python || Easy Solution
|
morpheusdurden
| 1
| 43
|
min max game
| 2,293
| 0.643
|
Easy
| 31,643
|
https://leetcode.com/problems/min-max-game/discuss/2112595/Python-Simple-Python-Solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
if len(nums) ==1:
return nums[0]
while len(nums)>1:
length =len(nums)//2
temp_array = []
for i in range(length):
if i%2==0:
temp_array.append(min(nums[2 * i], nums[2 * i + 1]))
else:
temp_array.append(max(nums[2 * i], nums[2 * i + 1]))
nums = temp_array
return nums[0]
|
min-max-game
|
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
|
ASHOK_KUMAR_MEGHVANSHI
| 1
| 35
|
min max game
| 2,293
| 0.643
|
Easy
| 31,644
|
https://leetcode.com/problems/min-max-game/discuss/2112171/Python-oror-Easy-Approach
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
def div_two(nums):
newNums = []
n = len(nums)
a = 0
while n > 2 * a:
while a < n / 2:
if a % 2 == 0:
newNums.append(min(nums[2 * a], nums[2 * a + 1]))
a += 1
else:
newNums.append(max(nums[2 * a], nums[2 * a + 1]))
a += 1
return newNums
n = len(nums)
while n > 1:
nums = div_two(nums)
n = len(nums)
return nums[0]
|
min-max-game
|
✅Python || Easy Approach
|
chuhonghao01
| 1
| 21
|
min max game
| 2,293
| 0.643
|
Easy
| 31,645
|
https://leetcode.com/problems/min-max-game/discuss/2111982/Python-Easy-Solution
|
class Solution:
def helper(self, nums, n):
if n == 1:
return nums
newNums = [0] * (n // 2)
for i in range(n // 2):
if i % 2 == 0:
newNums[i] = min(nums[2 * i], nums[2 * i + 1])
else:
newNums[i] = max(nums[2 * i], nums[2 * i + 1])
nums[:] = newNums[:]
self.helper(nums, len(nums))
def minMaxGame(self, nums: List[int]) -> int:
n = len(nums)
self.helper(nums, n)
return nums[0]
|
min-max-game
|
Python Easy Solution
|
MiKueen
| 1
| 56
|
min max game
| 2,293
| 0.643
|
Easy
| 31,646
|
https://leetcode.com/problems/min-max-game/discuss/2665643/solution-made-easy
|
class Solution:
def minMaxGame(self, a: List[int]) -> int:
def solve(n):
if n==1:
return
for i in range(n//2):
if i%2:
a[i] = max (a[2*i], a[2*i+1])
else:
a[i] = min (a[2*i], a[2*i+1])
solve(n//2)
return
solve(len(a))
return a[0]
|
min-max-game
|
solution made easy
|
Sukriti0318
| 0
| 5
|
min max game
| 2,293
| 0.643
|
Easy
| 31,647
|
https://leetcode.com/problems/min-max-game/discuss/2614394/Python-One-liner-(and-more-readable-solution)
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
return self.minMaxGame([max(nums[2*i], nums[2*i+1]) if i % 2 else min(nums[2*i], nums[2*i+1]) for i in range(len(nums)//2)]) if len(nums) > 1 else nums[0]
|
min-max-game
|
[Python] - One-liner (and more readable solution)
|
Lucew
| 0
| 20
|
min max game
| 2,293
| 0.643
|
Easy
| 31,648
|
https://leetcode.com/problems/min-max-game/discuss/2614394/Python-One-liner-(and-more-readable-solution)
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
print(nums)
# exit condition
if len(nums) == 1:
return nums[0]
result = []
for i in range(len(nums)//2):
if i % 2:
result.append(max(nums[2*i], nums[2*i+1]))
else:
result.append(min(nums[2*i], nums[2*i+1]))
return self.minMaxGame(result)
|
min-max-game
|
[Python] - One-liner (and more readable solution)
|
Lucew
| 0
| 20
|
min max game
| 2,293
| 0.643
|
Easy
| 31,649
|
https://leetcode.com/problems/min-max-game/discuss/2568187/Python-simple-solution-O(nlogn)
|
class Solution:
def minMaxGame(self, nums: list[int]) -> int:
while len(nums) > 1:
ans = []
for i in range(0, len(nums) - 1, 2):
f = min if i % 4 == 0 else max
ans.append(f(nums[i], nums[i + 1]))
nums = ans
return nums[0]
|
min-max-game
|
Python simple solution O(nlogn)
|
Mark_computer
| 0
| 28
|
min max game
| 2,293
| 0.643
|
Easy
| 31,650
|
https://leetcode.com/problems/min-max-game/discuss/2516876/Simple-using-min-and-max-in-Python
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) > 1:
minT, maxT = True, False
temp = []
for i in range(1, len(nums), 2):
if minT:
temp.append(min(nums[i - 1], nums[i]))
maxT = True
minT = False
elif maxT:
temp.append(max(nums[i - 1], nums[i]))
maxT = False
minT = True
nums = temp
return nums[0]
|
min-max-game
|
Simple using min and max in Python
|
ankurbhambri
| 0
| 15
|
min max game
| 2,293
| 0.643
|
Easy
| 31,651
|
https://leetcode.com/problems/min-max-game/discuss/2436003/Python3-or-Simple-Iterative-Approach-of-Simulating
|
class Solution:
#Time-Complexity: O(logn * (n/2)) -> O(nlogn) -> while loop runs at most logn times since
#we divide nums array size by half each iteration, and the for loop runs at most n/2 times!
#Space-Complexity: O(logn * (n/2)) -> for each iteration of while loop, we allocate
#copy array of size at worst (n/2) -> O(nlogn)
def minMaxGame(self, nums: List[int]) -> int:
#just simulate it?
min_flag = True
while len(nums) > 1:
copy = []
for i in range(0, len(nums)-1, 2):
if(min_flag):
copy.append(min(nums[i], nums[i+1]))
min_flag = (not min_flag)
continue
else:
copy.append(max(nums[i], nums[i+1]))
min_flag = (not min_flag)
continue
nums = copy
min_flag = True
return nums[0]
|
min-max-game
|
Python3 | Simple Iterative Approach of Simulating
|
JOON1234
| 0
| 20
|
min max game
| 2,293
| 0.643
|
Easy
| 31,652
|
https://leetcode.com/problems/min-max-game/discuss/2412576/Simple-Approach-Using-Python
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) != 1:
res = [0]*(len(nums)//2)
for i in range(0, len(nums)//2):
if i %2==0:
res[i] = min(nums[2*i], nums[2*i + 1])
else:
res[i] = max(nums[2*i], nums[2*i + 1])
nums = res
return nums[0]
|
min-max-game
|
Simple Approach Using Python
|
Abhi_-_-
| 0
| 26
|
min max game
| 2,293
| 0.643
|
Easy
| 31,653
|
https://leetcode.com/problems/min-max-game/discuss/2375430/Python-oror-Easy-solution-oror-70-Faster
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums)!=1:
c=1
arr=[]
for i in range(0,len(nums),2):
if c%2!=0:
arr.append(min(nums[i],nums[i+1]))
else:
arr.append(max(nums[i],nums[i+1]))
c=c+1
nums=arr
return nums[0]
|
min-max-game
|
Python || Easy solution || 70% Faster
|
keertika27
| 0
| 45
|
min max game
| 2,293
| 0.643
|
Easy
| 31,654
|
https://leetcode.com/problems/min-max-game/discuss/2374333/StraightForward-iterative-solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return nums[0]
while len(nums) > 1:
new_len = len(nums)//2
new_lst = [0 for i in range(new_len)]
for i in range(new_len):
if i % 2 == 0:
new_lst[i] = min(nums[2*i], nums[2*i + 1])
else:
new_lst[i] = max(nums[2*i], nums[2*i + 1])
nums = new_lst
return nums[0]
|
min-max-game
|
StraightForward iterative solution
|
destifo
| 0
| 10
|
min max game
| 2,293
| 0.643
|
Easy
| 31,655
|
https://leetcode.com/problems/min-max-game/discuss/2360324/Python3-recursion
|
class Solution:
def minMaxGame(self, nums: list[int]) -> int:
j = 0
if len(nums)<=2:
return min(nums)
newNums = []
for i in range(len(nums)//4):
newNums.append(min(nums[j:j+2]))
j += 2
newNums.append(max(nums[j:j+2]))
j += 2
return Solution.minMaxGame(Solution, newNums)
|
min-max-game
|
Python3 recursion
|
siktorovich
| 0
| 16
|
min max game
| 2,293
| 0.643
|
Easy
| 31,656
|
https://leetcode.com/problems/min-max-game/discuss/2301197/Python3-simulation
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
n = len(nums)
while n > 1:
for i in range(n//2):
if i&1: nums[i] = max(nums[2*i], nums[2*i+1])
else: nums[i] = min(nums[2*i], nums[2*i+1])
n //= 2
return nums[0]
|
min-max-game
|
[Python3] simulation
|
ye15
| 0
| 17
|
min max game
| 2,293
| 0.643
|
Easy
| 31,657
|
https://leetcode.com/problems/min-max-game/discuss/2295115/Python-Solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) > 1:
nums = [min(nums[i], nums[i + 1]) if index % 2 == 0 else max(nums[i], nums[i + 1]) for index, i in enumerate(range(0, len(nums), 2))]
return nums[0]
|
min-max-game
|
Python Solution
|
hgalytoby
| 0
| 28
|
min max game
| 2,293
| 0.643
|
Easy
| 31,658
|
https://leetcode.com/problems/min-max-game/discuss/2295115/Python-Solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) > 1:
arr = []
for index, i in enumerate(range(0, len(nums), 2)):
if index % 2 == 0:
arr.append(min(nums[i], nums[i + 1]))
else:
arr.append(max(nums[i], nums[i + 1]))
nums = arr
return nums[0]
|
min-max-game
|
Python Solution
|
hgalytoby
| 0
| 28
|
min max game
| 2,293
| 0.643
|
Easy
| 31,659
|
https://leetcode.com/problems/min-max-game/discuss/2287184/Python3-iterative-solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
flag=1
while len(nums)>1:
temp=[]
for i in range(0,len(nums),2):
if flag:
temp.append(min(nums[i],nums[i+1]))
else:
temp.append(max(nums[i],nums[i+1]))
flag=1-flag
nums=temp[::]
return nums[0]
|
min-max-game
|
Python3 iterative solution
|
atm1504
| 0
| 7
|
min max game
| 2,293
| 0.643
|
Easy
| 31,660
|
https://leetcode.com/problems/min-max-game/discuss/2183768/Python-recursive-solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
def mm(nums):
if len(nums) == 1:
return nums[0]
arr = []
for i in range(0, len(nums),2):
if i % 4 == 0:
arr.append(min(nums[i:i+2]))
else:
arr.append(max(nums[i:i+2]))
return mm(arr)
return mm(nums)
|
min-max-game
|
Python recursive solution
|
StikS32
| 0
| 39
|
min max game
| 2,293
| 0.643
|
Easy
| 31,661
|
https://leetcode.com/problems/min-max-game/discuss/2175406/Python-recursive-one-liner-solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
return nums[0] if len(nums) == 1 else self.minMaxGame([max(nums[2 * i], nums[2 * i + 1]) if i & 1 else min(nums[2 * i], nums[2 * i + 1]) for i in range(len(nums)//2)])
|
min-max-game
|
Python recursive one-liner solution
|
ahmadheshamzaki
| 0
| 44
|
min max game
| 2,293
| 0.643
|
Easy
| 31,662
|
https://leetcode.com/problems/min-max-game/discuss/2144104/Python3-simple-solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) != 1:
ans = []
for i in range(0,len(nums),2):
if (i//2)%2 == 0:
ans.append(min(nums[i],nums[i+1]))
else:
ans.append(max(nums[i],nums[i+1]))
nums = ans
return nums[0]
|
min-max-game
|
Python3 simple solution
|
EklavyaJoshi
| 0
| 39
|
min max game
| 2,293
| 0.643
|
Easy
| 31,663
|
https://leetcode.com/problems/min-max-game/discuss/2124206/Python-Iterative-Solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
temp = []
while len(nums) > 1:
even = True
for i in range(0, len(nums) - 1, 2):
if even:
temp.append(min(nums[i], nums[i + 1]))
even = False
else:
temp.append(max(nums[i], nums[i + 1]))
even = True
nums = temp
temp = []
return nums[0]
|
min-max-game
|
Python Iterative Solution
|
Hejita
| 0
| 39
|
min max game
| 2,293
| 0.643
|
Easy
| 31,664
|
https://leetcode.com/problems/min-max-game/discuss/2113267/Python-Easy-simulation
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
while len(nums) != 1:
new = [-1]*(len(nums)//2)
for i in range(len(nums)//2):
if i % 2 == 0:
new[i] = min(nums[2*i], nums[2*i+1])
else:
new[i] = max(nums[2*i], nums[2*i+1])
nums = new
return nums[0]
|
min-max-game
|
[Python] Easy simulation
|
nightybear
| 0
| 12
|
min max game
| 2,293
| 0.643
|
Easy
| 31,665
|
https://leetcode.com/problems/min-max-game/discuss/2113165/java-python-easy-iterative-solution
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
l = len(nums)
if l == 1 : return nums[0]
while l != 2 :
i, j = 0, 0
while j != l :
nums[i] = min(nums[j], nums[j+1])
nums[i+1] = max(nums[j+2], nums[j+3])
i += 2
j += 4
l>>=1
return min(nums[0], nums[1])
|
min-max-game
|
java, python - easy iterative solution
|
ZX007java
| 0
| 15
|
min max game
| 2,293
| 0.643
|
Easy
| 31,666
|
https://leetcode.com/problems/min-max-game/discuss/2113118/Easy-oror-Python-oror-Simple-Recursion-oror-100-Faster
|
class Solution(object):
def minMaxGame(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
new_nums = [0] * (len(nums) // 2)
i = 0
p1 = 0
while p1 < len(new_nums):
if p1 % 2 == 0:
new_nums[p1] = min(nums[i], nums[i + 1])
else:
new_nums[p1] = max(nums[i], nums[i + 1])
i += 2
p1 += 1
return self.minMaxGame(new_nums)
|
min-max-game
|
Easy || Python || Simple Recursion || 100 % Faster
|
kkarumanchi
| 0
| 25
|
min max game
| 2,293
| 0.643
|
Easy
| 31,667
|
https://leetcode.com/problems/min-max-game/discuss/2112065/Python-or-BFS-approach-or-Easy-to-understand
|
class Solution:
def minMaxGame(self, nums: List[int]) -> int:
x = 0
while len(nums)>1:
a = []
while nums:
if x:
a.append(max(nums[0],nums[1]))
nums.pop(0)
nums.pop(0)
x = 0
else:
a.append(min(nums[0],nums[1]))
nums.pop(0)
nums.pop(0)
x = 1
nums = a
return nums[0]
|
min-max-game
|
Python | BFS approach | Easy to understand
|
AkashHooda
| 0
| 13
|
min max game
| 2,293
| 0.643
|
Easy
| 31,668
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2111923/Python-Easy-Solution-using-Sorting
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
ans = 1
# To keep track of starting element of each subsequence
start = nums[0]
for i in range(1, len(nums)):
diff = nums[i] - start
if diff > k:
# If difference of starting and current element of subsequence is greater
# than K, then only start new subsequence
ans += 1
start = nums[i]
return ans
|
partition-array-such-that-maximum-difference-is-k
|
Python Easy Solution using Sorting
|
MiKueen
| 19
| 877
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,669
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2287274/Python3-O(n)-min-max-blocks-counts
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
res=1
minm=nums[0]
maxm=nums[0]
for x in nums:
if abs(x-minm)>k or abs(x-maxm)>k:
res+=1
minm=x
maxm=x
else:
minm=min(minm,x)
maxm=max(maxm,x)
return res
|
partition-array-such-that-maximum-difference-is-k
|
Python3 O(n) min-max blocks counts
|
atm1504
| 1
| 67
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,670
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2113854/Python3-Sorting-(%2B-heap-version)
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
heap = []
count = 1
for num in nums:
heappush(heap, num)
start = heappop(heap)
while heap:
num = heappop(heap)
if num - start > k:
start = num
count += 1
return count
|
partition-array-such-that-maximum-difference-is-k
|
Python3, Sorting (+ heap version)
|
frolovdmn
| 1
| 42
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,671
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112414/Python3-or-easy-intuitive-method-or-sliding-window
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort(reverse = True)
# print(nums)
initial = nums[0]
count = 0
for i in range(1, len(nums)):
if initial - nums[i] > k:
initial = nums[i]
count += 1
count += 1
return count
|
partition-array-such-that-maximum-difference-is-k
|
✅Python3 | easy intuitive method | sliding window
|
shodan11
| 1
| 62
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,672
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112237/Python-Easy-understanding-Solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
ans = 1
nums = list(set(nums))
nums.sort()
newNums = []
newNums.append(nums[0])
nums.pop(0)
i = 1
while len(nums) >= 1:
if nums[0] <= newNums[ans - 1] + k:
nums.pop(0)
else:
ans += 1
newNums.append(nums[0])
nums.pop(0)
return ans
|
partition-array-such-that-maximum-difference-is-k
|
✅Python Easy-understanding Solution
|
chuhonghao01
| 1
| 15
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,673
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2847853/Easy-sorting-solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
s = sorted(nums)
c=0
temp = []
for i in range(len(s)):
if len(temp)>0 and (s[i]-temp[0])>k:
temp.clear()
c+=1
temp.append(s[i])
return c+1
|
partition-array-such-that-maximum-difference-is-k
|
Easy sorting solution
|
ankansharma1998
| 0
| 1
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,674
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2800914/Golang-Rust-Python-Solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums = sorted(nums,reverse=True)
res = 1
j = 0
for i in range(1,len(nums)):
if nums[j] - nums[i] > k:
res+=1
j=i
return res
|
partition-array-such-that-maximum-difference-is-k
|
Golang Rust Python Solution
|
anshsharma17
| 0
| 5
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,675
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2784864/Python-simple-sorting-solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
count = 1
start = nums[0]
for i in range(1,len(nums)):
if nums[i] >start+k:
count+=1
start = nums[i]
return count
|
partition-array-such-that-maximum-difference-is-k
|
Python simple sorting solution
|
Rajeev_varma008
| 0
| 1
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,676
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2784858/Python-simple-sorting-solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
count = 1
start = nums[0]
for i in range(1,len(nums)):
if nums[i] >start+k:
count+=1
start = nums[i]
return count
|
partition-array-such-that-maximum-difference-is-k
|
Python simple sorting solution
|
Rajeev_varma008
| 0
| 1
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,677
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2568732/Python3-or-Sort-then-2-pointers-to-find-the-start-and-end-of-each-subsequence
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
subsequences = 0
l = r = 0
while r < len(nums):
while r < len(nums) and nums[r] - nums[l] <= k:
r += 1
l = r
subsequences += 1
return subsequences
|
partition-array-such-that-maximum-difference-is-k
|
Python3 | Sort then 2 pointers to find the start and end of each subsequence
|
Ploypaphat
| 0
| 16
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,678
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2387297/Python3-Solution-with-using-sorting
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
begin, res = 0, 0
while begin < len(nums):
_min = nums[begin]
begin += 1
while begin < len(nums) and nums[begin] - _min <= k:
begin += 1
res += 1
return res
|
partition-array-such-that-maximum-difference-is-k
|
[Python3] Solution with using sorting
|
maosipov11
| 0
| 24
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,679
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2301208/Python3-sort-unique-values
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
ans = 0
prev = -inf
for x in sorted(set(nums)):
if x > prev+k:
ans += 1
prev = x
return ans
|
partition-array-such-that-maximum-difference-is-k
|
[Python3] sort unique values
|
ye15
| 0
| 20
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,680
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2200446/Easy-Approach-using-sorting
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
minPartitions = 1
nums = sorted(nums)
n = len(nums)
minimum = nums[0]
for i in range(1, n):
if nums[i] - minimum > k:
minPartitions += 1
minimum = nums[i]
return minPartitions
|
partition-array-such-that-maximum-difference-is-k
|
Easy Approach using sorting
|
Vaibhav7860
| 0
| 30
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,681
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2118786/python3-sort-solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
i=0
answer=0
while i<len(nums):
lower=nums[i]
uper=lower+k
while(i<len(nums) and nums[i]<=uper ):
i+=1
answer+=1
return answer
|
partition-array-such-that-maximum-difference-is-k
|
python3 sort solution
|
manu_nassour
| 0
| 3
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,682
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2116287/Straightforward-Python-sorting-with-detailed-thought-process
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
ans = 0
nums.sort()
mi = nums[0]
for i, num in enumerate(nums):
if num - mi > k:
mi = num
ans += 1
ans += 1
return ans
|
partition-array-such-that-maximum-difference-is-k
|
Straightforward Python sorting with detailed thought process
|
lukefall425
| 0
| 15
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,683
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2113702/java-python-sorting
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
ans, i = 0, 0
while i != len(nums) :
ans += 1
j = i + 1
while j != len(nums) and nums[j] - nums[i] <= k :
j += 1
i = j
return ans
|
partition-array-such-that-maximum-difference-is-k
|
java, python - sorting
|
ZX007java
| 0
| 8
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,684
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112832/Python-oror-Two-Pointers-Solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
print(nums)
slow, fast = 0, 1
count = 1
while slow <= fast and fast < len(nums):
if nums[fast] - nums[slow] <= k:
fast += 1
else:
count += 1
slow = fast
return count
|
partition-array-such-that-maximum-difference-is-k
|
Python || Two Pointers Solution
|
pochun_li
| 0
| 22
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,685
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112562/Python-Simple-Python-Solution-Sorting
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums = sorted(nums)
result = 1
start = nums[0]
for i in range(1,len(nums)):
if nums[i] - start > k:
start = nums[i]
result = result + 1
return result
|
partition-array-such-that-maximum-difference-is-k
|
[ Python ] ✅✅ Simple Python Solution Sorting 🥳✌👍
|
ASHOK_KUMAR_MEGHVANSHI
| 0
| 11
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,686
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112412/Python-solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
if len(nums) == 0:
return 0
ans = 1
currmax = None
currmin = None
for n in nums:
if currmax is None and currmin is None:
currmax = currmin = n
if n > currmax:
currmax = n
if n < currmin:
currmin = n
if currmax - currmin > k:
ans += 1
currmax = currmin = n
return ans
|
partition-array-such-that-maximum-difference-is-k
|
Python solution
|
user6397p
| 0
| 8
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,687
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112215/Python-sort
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
min_val,result = -sys.maxsize-1,0
for num in nums:
if num > min_val + k:
min_val = num
result += 1
return result
|
partition-array-such-that-maximum-difference-is-k
|
Python sort
|
parthberk
| 0
| 6
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,688
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112139/Easy-Python-Solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
c=0
l=[nums[0]]
for i in range(1,len(nums)):
if nums[i]-l[0]<=k:
l.append(nums[i])
else:
c+=1
l=[nums[i]]
if l:
c+=1
return c
|
partition-array-such-that-maximum-difference-is-k
|
Easy Python Solution
|
a_dityamishra
| 0
| 14
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,689
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2112028/Python-Efficient-Solution-or-O(N.Log(N))-Approach-or-Easy-to-Undersatnd
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
nums.sort()
a = nums[0]
x = 1
for i in range(1,len(nums)):
if nums[i]-a>k:
a = nums[i]
x+=1
return x
|
partition-array-such-that-maximum-difference-is-k
|
Python Efficient Solution | O(N.Log(N)) Approach | Easy to Undersatnd
|
AkashHooda
| 0
| 19
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,690
|
https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2111900/Python-simple-Sorting-solution
|
class Solution:
def partitionArray(self, nums: List[int], k: int) -> int:
answer = 0
nums.sort()
while nums:
smallestNumber = nums.pop(0)
while nums and smallestNumber <= nums[0] and nums[0] - smallestNumber <= k:
nums.pop(0)
answer += 1
return answer
|
partition-array-such-that-maximum-difference-is-k
|
Python simple Sorting solution
|
tyrocoder
| 0
| 18
|
partition array such that maximum difference is k
| 2,294
| 0.726
|
Medium
| 31,691
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112285/Python-Simple-Map-Approach
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
replacements = {}
for x, y in reversed(operations):
replacements[x] = replacements.get(y, y)
for idx, val in enumerate(nums):
if val in replacements:
nums[idx] = replacements[val]
return nums
|
replace-elements-in-an-array
|
✅ Python Simple Map Approach
|
constantine786
| 25
| 1,300
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,692
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2111883/Python3-solution
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
d = {}
for i,num in enumerate(nums):
d[num] = i #Save index of all elements in dictionary for O(1) lookup
for x,r in operations:
where = d[x] # Find location of operation from dictionary
nums[where] = r # Complete the operation (Change number)
del d[x] # Update dictionary
d[r] = where # Update dictionary
return nums
|
replace-elements-in-an-array
|
✅ Python3 solution
|
Eba472
| 3
| 153
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,693
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112197/Easy-Python3-solution-using-map
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
seen = {}
for i in range(len(nums)):
seen[nums[i]] = i
print(seen)
for i in range(len(operations)):
idx = seen.get(operations[i][0])
nums[idx] = operations[i][1]
seen.pop(operations[i][0])
seen[operations[i][1]] = idx
return nums
|
replace-elements-in-an-array
|
✅ Easy Python3 solution using map
|
shodan11
| 2
| 119
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,694
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112195/Python-O(n%2Bm)-solution
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
pos = {}
for i in range(len(nums)):
pos[nums[i]] = i
for i,j in operations:
index = pos[i]
nums[index] = j
pos[j] = index
pos.pop(i)
return nums
|
replace-elements-in-an-array
|
Python O(n+m) solution
|
dhananjay79
| 1
| 56
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,695
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2848142/Python-simple-solution-using-hashmap
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
idxDict = {}
for i in range(len(nums)):
idxDict[nums[i]] = i
for a,b in operations:
idx = idxDict[a]
idxDict.pop(a)
idxDict[b] = idx
for k in idxDict:
nums[idxDict[k]] = k
return nums
|
replace-elements-in-an-array
|
Python simple solution using hashmap
|
ankurkumarpankaj
| 0
| 1
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,696
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2826708/python_faster_than_98_Idiotic_solution_XD
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
dect = dict( zip( nums, range(len(nums)) ) )
for o in operations:
e = dect[o[0]]
del dect[o[0]]
dect[o[1]] = e
return sorted( dect.keys(), key = lambda x: dect[x] )
|
replace-elements-in-an-array
|
python_faster_than_98%_Idiotic_solution_XD
|
markhabaevv
| 0
| 2
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,697
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2301232/Python3-mapping
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
mp = {}
for x, y in reversed(operations): mp[x] = mp.get(y, y)
return [mp.get(x, x) for x in nums]
|
replace-elements-in-an-array
|
[Python3] mapping
|
ye15
| 0
| 24
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,698
|
https://leetcode.com/problems/replace-elements-in-an-array/discuss/2115130/Python-oror-Easy-Map-Solution
|
class Solution:
def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
n, m = len(nums), len(operations)
ind = defaultdict(int)
for i, num in enumerate(nums):
ind[num] = i
for op in operations:
idx = ind[op[0]]
nums[idx] = op[1]
ind[op[1]] = idx
del ind[op[0]]
return nums
|
replace-elements-in-an-array
|
Python || Easy Map Solution
|
morpheusdurden
| 0
| 28
|
replace elements in an array
| 2,295
| 0.576
|
Medium
| 31,699
|
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.