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/largest-multiple-of-three/discuss/564606/Python-Clean-code-using-remainder-array | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
digits.sort()
rem = [d % 3 for d in digits]
s = sum(rem) % 3
def remove_smallest_with_rem(x):
idx = rem.index(x)
del digits[idx]
del rem[idx]
if s != 0:
try:
remove_smallest_with_rem(s)
except ValueError:
remove_smallest_with_rem(3-s)
remove_smallest_with_rem(3-s)
if len(digits) == 0: return ""
if digits[-1] == 0: return "0"
return ("".join(str(d) for d in reversed(digits))) | largest-multiple-of-three | [Python] Clean code using remainder array | rajkar86 | 1 | 290 | largest multiple of three | 1,363 | 0.333 | Hard | 20,500 |
https://leetcode.com/problems/largest-multiple-of-three/discuss/517725/Python3-super-simple-long-solution | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
digits.sort()
q0,q1,q2=[],[],[]
sums=0
for i in range(len(digits)):
sums+=digits[i]
remain=digits[i]%3
if remain==0:
q0.append(digits[i])
elif remain==1:
q1.append(digits[i])
else:
q2.append(digits[i])
q1.sort(reverse=True)
q2.sort(reverse=True)
if sums%3==1:
if q1:
q1.pop()
else:
if q2:
q2.pop()
else:
return ""
if q2:
q2.pop()
else:
return ""
elif sums%3==2:
if q2:
q2.pop()
else:
if q1:
q1.pop()
else:
return ""
if q1:
q1.pop()
else:
return ""
res=q0+q1+q2
res.sort(reverse=True)
ans=""
for i in res:
ans+=str(i)
return str(int(ans)) if ans else ans | largest-multiple-of-three | Python3 super simple long solution | jb07 | 1 | 125 | largest multiple of three | 1,363 | 0.333 | Hard | 20,501 |
https://leetcode.com/problems/largest-multiple-of-three/discuss/517688/Python3-A-sorting-based-solution | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
digits.sort(reverse=True)
category = dict()
for d in digits: category.setdefault(d%3, []).append(d)
parity = sum(digits) % 3
if parity != 0:
if len(category.get(parity, [])) > 0:
digits.remove(category[parity][-1])
elif len(category.get(3-parity, [])) > 1:
digits.remove(category[3-parity][-1])
digits.remove(category[3-parity][-2])
else:
return ""
return "0" if digits and not digits[0] else "".join(str(d) for d in digits) | largest-multiple-of-three | [Python3] A sorting-based solution | ye15 | 1 | 61 | largest multiple of three | 1,363 | 0.333 | Hard | 20,502 |
https://leetcode.com/problems/largest-multiple-of-three/discuss/2329746/python-3-or-readable-solution-or-O(n)O(1) | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
count = collections.Counter(digits)
mod1 = count[1] + count[4] + count[7]
zeroMod1 = not mod1
mod1 %= 3
mod2 = count[2] + count[5] + count[8]
zeroMod2 = not mod2
mod2 %= 3
nums1, nums2 = (1, 4, 7), (2, 5, 8)
def removeK(nums, k):
for i in nums:
rem = min(count[i], k)
count[i] -= rem
k -= rem
if mod1 == mod2:
removeK((), 0)
elif zeroMod1:
removeK(nums2, mod2)
elif zeroMod2:
removeK(nums1, mod1)
elif (mod1 - mod2) % 3 == 1:
removeK(nums1, 1)
else:
removeK(nums2, 1)
res = ''.join(str(digit) * count[digit] for digit in range(9, -1, -1))
return res if not res or res[0] != '0' else '0' | largest-multiple-of-three | python 3 | readable solution | O(n)/O(1) | dereky4 | 0 | 60 | largest multiple of three | 1,363 | 0.333 | Hard | 20,503 |
https://leetcode.com/problems/largest-multiple-of-three/discuss/2277498/Python-99-faster-easy-solution | class Solution:
def largestMultipleOfThree(self, nums: List[int]) -> str:
nums.sort(reverse = True)
if sum(nums)%3 == 1:
# we need to remove one minimum or two with remainder == 2
flag = False
for i in reversed(range(len(nums))):
if nums[i]%3 == 1:
nums[i] = -1
flag = True
break
if not flag:
count = 2
for i in reversed(range(len(nums))):
if count == 0:
break
if nums[i]%3 == 2:
nums[i] = -1
count-=1
elif sum(nums)%3 == 2:
flag = False
for i in reversed(range(len(nums))):
if nums[i]%3 == 2:
nums[i] = -1
flag = True
break
if not flag:
# remove 2 elements having 1 remainder
count = 2
for i in reversed(range(len(nums))):
if count == 0:
break
if nums[i]%3 == 1:
nums[i] = -1
count-=1
ans = ''
for i in nums:
if i!=-1:
ans+=str(i)
if ans:
return str(int(ans))
else:
return ans | largest-multiple-of-three | Python 99% faster easy solution | Abhi_009 | 0 | 53 | largest multiple of three | 1,363 | 0.333 | Hard | 20,504 |
https://leetcode.com/problems/largest-multiple-of-three/discuss/517620/Python3-super-simple-solution | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
digits.sort()
q0,q1,q2=[],[],[]
sums=0
for i in range(len(digits)):
sums+=digits[i]
remain=digits[i]%3
if remain==0:
q0.append(digits[i])
elif remain==1:
q1.append(digits[i])
else:
q2.append(digits[i])
q1.sort(reverse=True)
q2.sort(reverse=True)
if sums%3==1:
if q1:
q1.pop()
else:
if q2:
q2.pop()
else:
return ""
if q2:
q2.pop()
else:
return ""
elif sums%3==2:
if q2:
q2.pop()
else:
if q1:
q1.pop()
else:
return ""
if q1:
q1.pop()
else:
return ""
res=q0+q1+q2
res.sort(reverse=True)
ans=""
for i in res:
ans+=str(i)
return str(int(ans)) if ans else ans | largest-multiple-of-three | Python3 super simple solution | jb07 | 0 | 103 | largest multiple of three | 1,363 | 0.333 | Hard | 20,505 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/613343/Simple-Python-Solution-72ms-and-13.8-MB-EXPLAINED | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
a=[]
numi = sorted(nums)
for i in range(0,len(nums)):
a.append(numi.index(nums[i]))
return a | how-many-numbers-are-smaller-than-the-current-number | Simple Python Solution [72ms and 13.8 MB] EXPLAINED | code_zero | 10 | 849 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,506 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1863223/Python-solution-faster-than-86 | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
sort_nums = sorted(nums)
res = []
for i in nums:
res.append(sort_nums.index(i))
return res | how-many-numbers-are-smaller-than-the-current-number | Python solution faster than 86% | alishak1999 | 5 | 288 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,507 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2119776/Python-Easy-solution-with-complexities | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
nums1 = sorted(nums) #time O(nlogn)
dic = {}
answer = []
for i in range(0,len(nums1)): #time O(n)
if nums1[i] in dic: #time O(1)
continue
else:
dic[nums1[i]] = i
for i in range(0,len(nums)): #time O(n)
answer.append(dic[nums[i]])
return answer
#time O(nlogn)
#space O(n) | how-many-numbers-are-smaller-than-the-current-number | [Python] Easy solution with complexities | mananiac | 3 | 206 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,508 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2119776/Python-Easy-solution-with-complexities | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
nums1 = sorted(nums) #time O(nlogn)
dic = {}
answer = []
for index,value in enumerate(nums1): #time O(n)
dic.setdefault(value,index)
for i in range(0,len(nums)): #time O(n)
answer.append(dic[nums[i]])
return answer
#time O(nlogn)
#space O(n) | how-many-numbers-are-smaller-than-the-current-number | [Python] Easy solution with complexities | mananiac | 3 | 206 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,509 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2119776/Python-Easy-solution-with-complexities | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
nums1 = sorted(nums) #time O(nlogn)
dic = {}
answer = []
for index,value in enumerate(nums1): #time O(n)
dic.setdefault(value,index)
for i in nums: #time O(n)
answer.append(dic[i])
return answer
#time O(nlogn)
#space O(n) | how-many-numbers-are-smaller-than-the-current-number | [Python] Easy solution with complexities | mananiac | 3 | 206 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,510 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2119776/Python-Easy-solution-with-complexities | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
count = [0] * 102
answer = []
for num in nums:
count[num+1] = count[num+1] + 1
for i in range(1, 102):
count[i] = count[i] + count[i-1]
for num in nums:
answer.append(count[num])
return answer
#time O(n)
#space O(n) | how-many-numbers-are-smaller-than-the-current-number | [Python] Easy solution with complexities | mananiac | 3 | 206 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,511 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1492937/WEEB-DOES-PYTHON(FASTER-THAN-96.67) | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
arr, result = sorted(nums), []
mapper = self.helper(arr, {})
for i in range(len(nums)):
result.append(mapper[nums[i]])
return result
def helper(self, arr, mapper):
count, cur_max = 0, -float("inf")
for i in range(0, len(arr)):
if arr[i] > cur_max:
cur_max = arr[i]
mapper[arr[i]] = count
count += 1
else:
count+=1
return mapper | how-many-numbers-are-smaller-than-the-current-number | WEEB DOES PYTHON(FASTER THAN 96.67%) | Skywalker5423 | 3 | 373 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,512 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1882814/Python-easy-to-read-and-understand-or-sorting | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
d = collections.defaultdict(int)
sorted_nums = sorted(nums)
for i, val in enumerate(sorted_nums):
d[val] = d.get(val, i)
for i in range(len(nums)):
nums[i] = d[nums[i]]
return nums | how-many-numbers-are-smaller-than-the-current-number | Python easy to read and understand | sorting | sanial2001 | 2 | 183 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,513 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1739142/1365-how-many-lesser | class Solution(object):
def smallerNumbersThanCurrent(self, nums):
rArray = []
for i in range(len(nums)):
lesser = 0
for j in range(len(nums)):
if i!=j and nums[j] < nums[i]:
lesser += 1
rArray.append(lesser)
return rArray | how-many-numbers-are-smaller-than-the-current-number | 1365 - how many lesser | ankit61d | 2 | 48 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,514 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1427607/Python-two-approaches%3A | class Solution(object):
def smallerNumbersThanCurrent(self, nums):
sortedNums = sorted(nums)
dict_count = {}
for i in range(len(nums)):
if sortedNums[i] not in dict_count:
dict_count[sortedNums[i]] = i
return [dict_count[num] for num in nums] | how-many-numbers-are-smaller-than-the-current-number | Python two approaches: | Aroy88 | 2 | 312 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,515 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1427607/Python-two-approaches%3A | class Solution(object):
def smallerNumbersThanCurrent(self, nums):
sortedNums = sorted(nums)
result = []
for i in nums:
result.append(sortedNums.index(i))
return result | how-many-numbers-are-smaller-than-the-current-number | Python two approaches: | Aroy88 | 2 | 312 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,516 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1427607/Python-two-approaches%3A | class Solution(object):
def smallerNumbersThanCurrent(self, nums):
sortedNums = sorted(nums)
return [sortedNums.index(num) for num in nums] | how-many-numbers-are-smaller-than-the-current-number | Python two approaches: | Aroy88 | 2 | 312 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,517 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2393882/Python-solution-short-code-.. | class Solution(object):
def smallerNumbersThanCurrent(self, nums):
arr=[]
num = sorted(nums)
for i in range(0,len(nums)):
arr.append(num.index(nums[i]))
return arr | how-many-numbers-are-smaller-than-the-current-number | Python solution short code ..🐍 | RohanRob | 1 | 79 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,518 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1742299/Short-Efficient-and-Easy-Solution-Python | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# sort in descending order
sorted_nums = sorted(nums, reverse=True)
small_nums = dict()
n = len(sorted_nums)
for i, num in enumerate(sorted_nums, 1):
small_nums[num] = n - i
return [small_nums[num] for num in nums] | how-many-numbers-are-smaller-than-the-current-number | Short, Efficient and Easy Solution {Python} | ashudva | 1 | 124 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,519 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1670663/Python-Solution-using-Sorting | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
n=sorted(nums)
n2=[]
for i in range(len(n)):
n2.append(n.index(nums[i]))
return (n2) | how-many-numbers-are-smaller-than-the-current-number | Python Solution using Sorting | shreerajbhamare | 1 | 75 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,520 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1379093/Python-solution-using-filter | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
ans = []
for n in nums:
temp = list(filter(lambda x:x<n,nums))
ans.append(len(temp))
return ans | how-many-numbers-are-smaller-than-the-current-number | Python solution using filter | shraddhapp | 1 | 97 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,521 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1182226/Binary-Search-Lower-Bound-Faster-than-80-Python-3-Solution | class Solution:
def find(self,arr,target):
low = 0
high = len(arr)
close = 0
while low<=high:
mid = low+(high-low)//2
if arr[mid] == target:
close = mid
high = mid-1
elif arr[mid]>target:
high = mid-1
else:
low = mid+1
return close
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
sortedNum = sorted(nums)
res = []
for num in nums:
res.append(self.find(sortedNum,num))
return res | how-many-numbers-are-smaller-than-the-current-number | Binary Search - Lower Bound - Faster than 80% Python 3 Solution | tgoel219 | 1 | 58 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,522 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/788481/Python-Solution-with-complexity-analysis | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
n, counts = len(nums), []
numMap = {} # O(n) space
sortedNums = sorted(nums) # O(n log n) time, O(n) space
# O(n)
for i in range(n-1, -1, -1):
numMap[sortedNums[i]] = i
# O(n)
for num in nums:
counts.append(numMap[num])
'''
In the absolute worst case, dictionary access could be
O(n)! Most people ignore this case but it can happen!
Therefore in the absolute worst case, the overall time
complexity for this algorithm is O(n^2), if we use the
amortized time complexity for dict access and insert,
the time complexity is:
Time: O(n log n)
Space: O(n)
'''
return counts | how-many-numbers-are-smaller-than-the-current-number | Python Solution with complexity analysis | zuu | 1 | 132 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,523 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/530333/Simple-and-Easy-to-understand-Python3-solution-using-sort()-and-dictionary | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
my_dict = {}
n = nums[:]
nums.sort()
for i in range(len(nums)):
if i == 0 or nums[i-1] < nums[i]:
my_dict[nums[i]] = i
return [my_dict[num] for num in n] | how-many-numbers-are-smaller-than-the-current-number | Simple and Easy to understand Python3 solution [using sort() and dictionary] | aravind5010 | 1 | 281 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,524 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2838593/Python3-~96-faster | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# counters will have a sorted dict of nums and its count
counters = collections.Counter(sorted(nums))
# Update the dict values with sum of nums[j]s for each nums[i]
sum = 0
for k in counters.keys():
prev_sum = sum
sum += counters[k]
counters[k] = prev_sum
return [counters[k] for k in nums] | how-many-numbers-are-smaller-than-the-current-number | Python3 ~96% faster | jubinmehta369 | 0 | 3 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,525 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2826703/Python-or-Fenwick-Tree-O(n-log-n)-to-Array-based-O(n) | class Solution:
def smallerNumbersThanCurrent(self, xs: List[int]) -> List[int]:
tree = FenwickTree(101)
for x in xs:
# Add 1 to the count of occurrences of x. The offset
# of 1 is due to the fact that the Fenwick tree uses
# the indices 1 through n−1.
tree.add(x+1, 1)
ans = []
for x in xs:
# Use the tree to find the count of values smaller
# than x.
ans.append(tree.prefix_sum(x))
return ans
def smallerNumbersThanCurrent2(self, xs: List[int]) -> List[int]
n = len(xs)
counts = [0]*102
for x in xs:
counts[x+1] += 1
for i in range(1,102):
counts[i] += counts[i-1]
ans = []
for x in xs:
ans.append(counts[x])
return ans
class FenwickTree:
def __init__(self, n):
self.n = n
self.s = [0]*n
# for i in range(1,n):
# self.add(i, t[i])
def add(self, i, x):
while i < self.n:
self.s[i] += x
i += i & -i # Add lsb of i
def get(self, i):
return self.prefix_sum(i)
def interval_add(self, a, b, x):
self.add(a, x)
self.add(b+1, -x)
def interval_sum(self, a, b):
return self.prefix_sum(b) - self.prefix_sum(a-1)
def prefix_sum(self, i):
ans = 0
while i > 0:
ans += self.s[i]
i -= (i & -i)
return ans
def __str__(self):
return str(self.s) | how-many-numbers-are-smaller-than-the-current-number | Python | Fenwick Tree O(n log n) to Array-based O(n) | on_danse_encore_on_rit_encore | 0 | 1 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,526 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2825858/Simple-Python-Solution | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
output=[]
for i in nums:
count=0
for j in nums:
if i>j:
count=count+1
output.append(count)
return output | how-many-numbers-are-smaller-than-the-current-number | Simple Python Solution | durgaraopolamarasetti | 0 | 2 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,527 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2821580/2-line-easy-peasy | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
x = sorted(nums)
return [x.index(i) for i in nums] | how-many-numbers-are-smaller-than-the-current-number | 2 line easy peasy | almazgimaev | 0 | 2 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,528 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2807075/Python-Solution | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
arr = sorted(nums)
return [arr.index(i) for i in nums] | how-many-numbers-are-smaller-than-the-current-number | Python Solution | Divyanshu_Kumar | 0 | 3 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,529 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2805672/python-code | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
l=[]
for i in range(len(nums)):
c=0
for j in range(len(nums)):
if(nums[i]>nums[j]):
c=c+1
l.append(c)
return l; | how-many-numbers-are-smaller-than-the-current-number | python code | Manjeet_Malik | 0 | 2 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,530 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2805661/here's-the-soln | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
res=[]
for i in range(len (nums)):
count=0
for j in range(len(nums)):
if(nums[i]>nums[j] and i!=j):
count=count+1
res.append(count)
return res | how-many-numbers-are-smaller-than-the-current-number | here's the soln | Prabhleen_17 | 0 | 1 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,531 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2711783/Two-Solutions-including-One-Liner-or-Time%3A-O(n2)-or-Python-3 | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
return [len([other_num for other_num in nums if other_num < num]) for num in nums] | how-many-numbers-are-smaller-than-the-current-number | Two Solutions including One-Liner | Time: O(n^2) | Python / 3 | keioon | 0 | 7 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,532 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2674996/Python-O(nlogn)-solution-with-O(n)-extra-space | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
map = {}
temp = sorted(nums)
for i in range(len(temp)):
if temp[i] not in map:
map[temp[i]] = i
res = []
for number in nums:
res.append(map[number])
return res | how-many-numbers-are-smaller-than-the-current-number | Python O(nlogn) solution with O(n) extra space | cat_woman | 0 | 5 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,533 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2669801/easy-using-loops-python | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
m=[]
res=0
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i]>nums[j]:
res+=1
m.append(res)
res=0
return(m) | how-many-numbers-are-smaller-than-the-current-number | easy using loops python | AMBER_FATIMA | 0 | 1 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,534 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2663302/Simple-python-code-with-explanation | class Solution:
def smallerNumbersThanCurrent(self, nums):
#create an empty list(k)
k = []
#iterate over the elements in list(nums)
for i in range(len(nums)):
#create a variable(summ) and assign 0 to it
summ = 0
#iterate over the elements in list(nums)
for j in range(len(nums)):
#if any element is less than curr element
if nums[i] > nums[j]:
#then increase summ value by one
summ +=1
#after finishing forloop(j)
#add summ value in list(k)
k.append(summ)
#reset summ to 0
summ = 0
#after finishing forloop(i)
#return list(k)
return k | how-many-numbers-are-smaller-than-the-current-number | Simple python code with explanation | thomanani | 0 | 40 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,535 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2653089/Python-Simple-Solution | class Solution(object):
def smallerNumbersThanCurrent(self, nums):
sorted_nums=sorted(nums)
op=[sorted_nums.index(n) for n in nums]
return op | how-many-numbers-are-smaller-than-the-current-number | Python Simple Solution | shandilayasujay | 0 | 46 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,536 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2611813/Python-Basic-Solution | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
n = len(nums)
result = []
for i in range(n):
j_counter = 0
for j in range(0, n):
if nums[j] < nums[i]:
j_counter += 1
result.append(j_counter)
return result | how-many-numbers-are-smaller-than-the-current-number | Python Basic Solution | dk_talks | 0 | 31 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,537 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2587322/optimized-solution-(python3) | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
sorted_array = sorted(nums)
h_map = {}
result =[]
n = len(nums)
for i in range(n):
if sorted_array[i] not in h_map:
h_map[sorted_array[i]] = i
for i in range (n):
result.append( h_map[nums[i]])
return result | how-many-numbers-are-smaller-than-the-current-number | optimized solution (python3) | kingshukmaity60 | 0 | 74 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,538 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2564478/using-hashmap | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# the size of nums, n, is only 500
# create an array to store the smaller nums for each index
# create a hashmap to store the numbers in nums with numbers smaller as values
# if a number is in the hashmap append the value in the array
# otherwise iterate through nums, find all values smaller than it, store in the map
# then append that value in nums
# Time O(n^2) Space O(n)
hashmap = dict()
res = []
for num in nums:
if num in hashmap:
res.append(hashmap[num])
else:
hashmap[num] = 0
for n in nums:
if num > n:
hashmap[num] += 1
res.append(hashmap[num])
return res | how-many-numbers-are-smaller-than-the-current-number | using hashmap | andrewnerdimo | 0 | 52 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,539 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2564478/using-hashmap | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
# optimized solution in place
d = dict()
arr = sorted(nums)
n = len(nums)
for i in range(n):
val = arr[i]
if val not in d:
d[val] = i
for i in range(n):
num = nums[i]
nums[i] = d[num]
return nums | how-many-numbers-are-smaller-than-the-current-number | using hashmap | andrewnerdimo | 0 | 52 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,540 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2554556/Python3-Solution-oror-Easy-oror-O(n2) | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
new = []
for i in nums:
count = 0
for j in nums:
if i > j :
count += 1
new.append(count)
return new | how-many-numbers-are-smaller-than-the-current-number | Python3 Solution || Easy || O(n^2) | shashank_shashi | 0 | 16 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,541 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2541034/Python-easy-solution | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
sorted_nums = nums[:]
sorted_nums.sort()
for index, value in enumerate(nums):
nums[index] = sorted_nums.index(value)
return nums | how-many-numbers-are-smaller-than-the-current-number | Python easy solution | anton_python | 0 | 45 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,542 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2529340/Easy-solution-in-python3-(2-solutions) | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
return [sorted(nums).index(i) for i in nums]
count = 0
result = []
for i in range(len(nums)):
for j in range(len(nums)):
if nums[j] < nums[i]:
count += 1
result.append(count)
count = 0
return result | how-many-numbers-are-smaller-than-the-current-number | Easy solution in python3 (2 solutions) | khushie45 | 0 | 48 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,543 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2529340/Easy-solution-in-python3-(2-solutions) | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
return [sorted(nums).index(i) for i in nums] | how-many-numbers-are-smaller-than-the-current-number | Easy solution in python3 (2 solutions) | khushie45 | 0 | 48 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,544 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2417458/easy-python-solution | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
i = 0 ;c = 0 ; res = []
while i<len(nums):
for j in range(len(nums)):
if nums[j] < nums[i]:
c+=1
res.append(c)
c = 0
i+=1
return res | how-many-numbers-are-smaller-than-the-current-number | easy python solution | Abdulrahman_Ahmed | 0 | 81 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,545 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2363685/How-Many-Numbers-Are-Smaller-Than-the-Current-Number | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
y = [i for i in nums ]
for i in range(len(y)):
minIndex=i
for j in range(i+1,len(y)):
if y[minIndex]>y[j]:
minIndex = j
x = y[minIndex]
y[minIndex]= y[i]
y[i] = x
x={}
for i in range(len(y)):
if y[i] in x:
pass
else:
x[y[i]]=i
out= []
for i in nums:
out.append(x[i])
return(out) | how-many-numbers-are-smaller-than-the-current-number | How Many Numbers Are Smaller Than the Current Number | dhananjayaduttmishra | 0 | 17 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,546 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2280454/How-Many-Numbers-Are-Smaller-Than-the-Current-Number | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
temp = sorted(nums)
for i in range(len(nums)):
nums[i] = temp.index(nums[i])
return nums | how-many-numbers-are-smaller-than-the-current-number | How Many Numbers Are Smaller Than the Current Number | tancoder24 | 0 | 45 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,547 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2280454/How-Many-Numbers-Are-Smaller-Than-the-Current-Number | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
temp = sorted(nums)
return [ temp.index(nums[i]) for i in range(len(nums)) ] | how-many-numbers-are-smaller-than-the-current-number | How Many Numbers Are Smaller Than the Current Number | tancoder24 | 0 | 45 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,548 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/2158591/Using-dictionary-and-sort-function-Python | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
temp = nums.copy()
temp.sort()
lookup = {}
res = []
for i, n in enumerate(temp):
if n not in lookup:
lookup[n] = i
for j in nums:
res.append(lookup[j])
return res | how-many-numbers-are-smaller-than-the-current-number | Using dictionary and sort function Python | ankurbhambri | 0 | 96 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,549 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1982139/Python-Simplest-Solution-With-Explanation-or-92.32-Faster-or-Sorting-or-Beg-to-adv | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
sorted_nums = sorted(nums) # sorting the list
# In this way, all the elements are sorted and we dont need to separately count the smaller elements separately.
res = [] # taking empty list to save the result
for i in range(len(sorted_nums)): # traversing the list
res.append(sorted_nums.index(nums[i])) # here we are checking index of the elements present in nums inside sorted nums & them we are appending the result in our empty list res.
return (res) # returning the resulting list. | how-many-numbers-are-smaller-than-the-current-number | Python Simplest Solution With Explanation | 92.32% Faster | Sorting | Beg to adv | rlakshay14 | 0 | 164 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,550 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1982025/Python-Easiest-Solution-With-Explanation. | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
res = [] # took a list to store the result
count = 0 # took a counter
for i in range(len(nums)): # loop one to traverse all the elements in the list.
for j in range(len(nums)): # loop two to traverse all the elements in the list for comparison
if j != i and nums[j] < nums[i]: # condition provided in the problem statement, which says inner loop value should be lower then outer one and we are checking how many elems are lesser then the current one.
count += 1 # increasing the counter to count the lesser elems
res.append(count) # as we have to return a list so per elem we are counting lesser elems and appending the counter in the resulting list
count = 0 # resetting count to 0 as we have to reinstate the counter to 0 for each elem at the intial stage.
return res # returning the resulting list | how-many-numbers-are-smaller-than-the-current-number | Python Easiest Solution With Explanation. | rlakshay14 | 0 | 75 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,551 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1930538/Python-Simple-and-Clean! | class Solution:
def smallerNumbersThanCurrent(self, nums):
d = {}
for i,n in enumerate(sorted(nums)):
if n not in d: d[n]=i
return [d[i] for i in nums] | how-many-numbers-are-smaller-than-the-current-number | Python - Simple and Clean! | domthedeveloper | 0 | 85 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,552 |
https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/1930538/Python-Simple-and-Clean! | class Solution:
def smallerNumbersThanCurrent(self, nums):
count = [0 for i in range(102)]
for num in nums: count[num+1] += 1
for i in range(1, len(count)): count[i] += count[i-1]
return [count[num] for num in nums] | how-many-numbers-are-smaller-than-the-current-number | Python - Simple and Clean! | domthedeveloper | 0 | 85 | how many numbers are smaller than the current number | 1,365 | 0.867 | Easy | 20,553 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/2129031/python-3-oror-simple-O(n)O(1)-solution | class Solution:
def rankTeams(self, votes: List[str]) -> str:
teamVotes = collections.defaultdict(lambda: [0] * 26)
for vote in votes:
for pos, team in enumerate(vote):
teamVotes[team][pos] += 1
return ''.join(sorted(teamVotes.keys(), reverse=True,
key=lambda team: (teamVotes[team], -ord(team)))) | rank-teams-by-votes | python 3 || simple O(n)/O(1) solution | dereky4 | 5 | 465 | rank teams by votes | 1,366 | 0.586 | Medium | 20,554 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/524981/Python3-organize-votes-in-a-frequency-table | class Solution:
def rankTeams(self, votes: List[str]) -> str:
ranking = dict()
for vote in votes:
for i, x in enumerate(vote):
ranking.setdefault(x, [0]*len(vote))[i] += 1
return "".join(sorted(sorted(vote), key=ranking.get, reverse=True)) | rank-teams-by-votes | [Python3] organize votes in a frequency table | ye15 | 4 | 631 | rank teams by votes | 1,366 | 0.586 | Medium | 20,555 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/1200413/Python-Following-Hints | class Solution:
ALPHABET_LENGTH = 26
ASCII_OFFSET = 97
def rankTeams(self, votes: List[str]) -> str:
"""
1. Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank.
2. Sort the teams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order.
"""
num_teams = len(votes[0])
ranks = [[0 for i in range(self.ALPHABET_LENGTH)] for j in range(len(votes[0]))]
# Populate Ranks Matrix
for voter_index, vote in enumerate(votes):
for rank, team in enumerate(vote):
ranks[rank][self.getAlphabetPosition(team)] = ranks[rank][self.getAlphabetPosition(team)] + 1
# Associate Teams with their Votes (Columns)
# Take care of sorting by appending duplicates to value list
teams_to_ranks = {}
for team, rankings in enumerate(self.getMatrixTranspose(ranks)):
tuple_key = tuple(rankings)
if tuple_key in teams_to_ranks:
teams_to_ranks[tuple_key].append(self.getCharacterFromPosition(team))
else:
teams_to_ranks[tuple_key] = [self.getCharacterFromPosition(team)]
# Sort Teams (Columns) of Rank Matrix by Rank (Rows)
ranks = self.getMatrixTranspose(ranks)
ranks.sort(key=lambda row: row[:], reverse=True)
ranks = self.getMatrixTranspose(ranks)
# Assemble String of Final Rankings
final_ranking = ""
for team, rankings in enumerate(self.getMatrixTranspose(ranks)):
tuple_key = tuple(rankings)
teams_with_rankings = teams_to_ranks[tuple_key] # Can't search transposed!
if len(teams_with_rankings) > 1: # If multiple teams have the same rankings, get the first by alphabet
sorted_ranking = sorted(teams_with_rankings)
final_ranking += sorted_ranking.pop(0)
teams_to_ranks[tuple_key] = sorted_ranking
else: # Otherwise just append the team matched with that ranking
final_ranking += teams_with_rankings[0]
return final_ranking[:num_teams] # Everything behind num teams is extra
def getMatrixTranspose(self, matrix: List[List[int]]) -> List[List[int]]:
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
def getCharacterFromPosition(self, position: int) -> str:
return chr(position + self.ASCII_OFFSET).upper()
def getAlphabetPosition(self, char: str) -> int:
return ord(char.lower()) - self.ASCII_OFFSET | rank-teams-by-votes | Python Following Hints | doubleimpostor | 1 | 386 | rank teams by votes | 1,366 | 0.586 | Medium | 20,556 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/676468/Python3-2-liner-Rank-Teams-by-Votes | class Solution:
def rankTeams(self, votes: List[str]) -> str:
counters = [Counter(v) for v in zip(*votes)]
return ''.join(sorted(votes[0], key=lambda x:(*(-c[x] for c in counters), x))) | rank-teams-by-votes | Python3 2 liner - Rank Teams by Votes | r0bertz | 1 | 320 | rank teams by votes | 1,366 | 0.586 | Medium | 20,557 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/542452/Python-Straightforward | class Solution(object):
def rankTeams(self, votes):
"""
:type votes: List[str]
:rtype: str
"""
counts = collections.defaultdict(list)
for vote in zip(*votes):
cntr = collections.Counter(vote)
for ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
counts[ch] += [-1*cntr[ch]]
return "".join(sorted(votes[0],key=lambda x :counts[x]+[x])) | rank-teams-by-votes | [Python] Straightforward | fallenranger | 1 | 494 | rank teams by votes | 1,366 | 0.586 | Medium | 20,558 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/2842233/Explained-solution-optimal | class Solution:
def rankTeams(self, votes: List[str]) -> str:
# map teams to their ranking votes in a map
# once the teams are mapped get a list of the teams sorted by their character
# sort by character first because next, the teams will be sorted by their ranking votes
# that way, teams with larger rankings will always preceed those with lower, but teams
# with conflicts will always be resolved due to the sorting of characters, or the next highest
# votes in the list be greater or less than
# time O(n * m logn) space O(n) m = (votes) n = (teams)
d = dict()
n = len(votes[0])
for team in votes[0]:
d[team] = [0] * n
for vote in votes:
for i, team in enumerate(vote):
d[team][i] += 1
res = sorted(d.keys())
res.sort(key=d.get, reverse=True)
return "".join(res) | rank-teams-by-votes | Explained solution optimal | andrewnerdimo | 0 | 3 | rank teams by votes | 1,366 | 0.586 | Medium | 20,559 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/2729727/Python-98-speed-6-lines | class Solution:
def rankTeams(self, votes: List[str]) -> str:
n_team = len(votes[0])
vote_count = dict(zip(votes[0], ([0 for _ in range(n_team)] for i in range(n_team))))
for vote in votes:
for i, team in enumerate(vote):
vote_count[team][i] += 1
return ''.join(sorted(vote_count, key=lambda team: vote_count[team] + [-ord(team)], reverse=True)) | rank-teams-by-votes | Python 98 % speed, 6 lines | very_drole | 0 | 37 | rank teams by votes | 1,366 | 0.586 | Medium | 20,560 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/2393968/Python-sorting | class Solution:
def rankTeams(self, votes: List[str]) -> str:
n = len(votes[0])
places = defaultdict(lambda: [0]*n)
for vote in votes:
for idx, team in enumerate(vote):
places[team][idx] -= 1 # for correct sorting
places = sorted([p + [team] for team, p in places.items()])
return "".join(p[n] for p in places) | rank-teams-by-votes | Python, sorting | blue_sky5 | 0 | 142 | rank teams by votes | 1,366 | 0.586 | Medium | 20,561 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/2159059/Python-solution | class Solution:
def rankTeams(self, votes: List[str]) -> str:
c = {}
for w in votes:
val = 0
for char in w:
if char in c:
c[char][val] += 1
else:
c[char] = [0] * len(w)
c[char][val] += 1
val += 1
ans = []
prev = None
cur = []
for k, v in sorted(c.items(), key = lambda x:x[1], reverse = True):
if prev == None:
cur = [k]
prev = v
continue
if prev == v:
cur.append(k)
continue
else:
ans += sorted(cur)
cur = [k]
prev = v
if cur:
ans += sorted(cur)
return ''.join(ans) | rank-teams-by-votes | Python solution | user6397p | 0 | 126 | rank teams by votes | 1,366 | 0.586 | Medium | 20,562 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/1487092/Unique-and-Easy-oror-Sorting-of-dictionary-oror-93-faster | class Solution:
def rankTeams(self, votes: List[str]) -> str:
dic = defaultdict(lambda : [0]*len(votes[0]))
for vote in votes:
for p,t in enumerate(vote): # p-> postion(rank), t->teamName
dic[t][p]-=1
res = dict(sorted(dic.items(),key=lambda x: (x[1],x[0])))
return ''.join(res.keys()) | rank-teams-by-votes | 📌📌 Unique & Easy || Sorting of dictionary || 93% faster 🐍 | abhi9Rai | 0 | 350 | rank teams by votes | 1,366 | 0.586 | Medium | 20,563 |
https://leetcode.com/problems/rank-teams-by-votes/discuss/1468421/Python3-solution-using-dictionary | class Solution:
def rankTeams(self, votes: List[str]) -> str:
d = {}
for z in range(len(votes[0])):
for i in votes:
d[i[z]] = d.get(i[z],'') + chr(97 + z)
d = dict((i,j) for i,j in sorted(d.items(),key=lambda x:x[0]))
return ''.join([i for i,j in sorted(d.items(),key=lambda x:x[1])]) | rank-teams-by-votes | Python3 solution using dictionary | EklavyaJoshi | 0 | 189 | rank teams by votes | 1,366 | 0.586 | Medium | 20,564 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/525814/Python3-A-naive-dp-approach | class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
#build longest prefix-suffix array
pattern, lps = [head.val], [0] #longest prefix-suffix array
j = 0
while head.next:
head = head.next
pattern.append(head.val)
while j and head.val != pattern[j]: j = lps[j-1]
if head.val == pattern[j]: j += 1
lps.append(j)
def dfs(root, i):
"""Return True of tree rooted at "root" match pattern"""
if i == len(pattern): return True
if not root: return False
while i > 0 and root.val != pattern[i]: i = lps[i-1]
if root.val == pattern[i]: i += 1
return dfs(root.left, i) or dfs(root.right, i)
return dfs(root, 0) | linked-list-in-binary-tree | [Python3] A naive dp approach | ye15 | 1 | 96 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,565 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/2633911/python3-easy-peasy-solution-using-combo-of-recursion-and-iteration | class Solution:
def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
def dfs(hd,node):
if not hd.next :
return hd.val==node.val
if hd.val==node.val:
if node.left and node.right:
return dfs(hd.next,node.left) or dfs(hd.next,node.right)
elif node.left:
return dfs(hd.next,node.left)
elif node.right :
return dfs(hd.next,node.right)
else:
return False
else:
return False
stk=[root]
while stk:
temp=stk.pop()
if dfs(head,temp):
return True
if temp.left:
stk.append(temp.left)
if temp.right:
stk.append(temp.right)
return False | linked-list-in-binary-tree | python3 easy-peasy solution using combo of recursion and iteration | benon | 0 | 15 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,566 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/1856648/Backtrack-with-help-of-string-express | class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
return self.backtrack(head, root)
def backtrack(self, head: ListNode, root: TreeNode) -> bool:
target_path = ''
while head:
target_path += f'|{head.val}'
head = head.next
path = ['']
def backtrack(node: TreeNode) -> bool:
''' retval: is target found? '''
if node:
path.append(f'{path[-1]}|{node.val}')
# check target
if target_path in path[-1]: return True
if backtrack(node.left): return True
if backtrack(node.right): return True
path.pop() # recover
return False
return backtrack(root) | linked-list-in-binary-tree | Backtrack with help of string express | steve-jokes | 0 | 28 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,567 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/1810646/Python3-oror-2-Method-BFS-BFS%2BDFS-oror-recursion-sucks-I-love-recursion | class Solution:
def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
def listcheck(root, head):
if not head:
res[0] = True
return
elif not root: return
if root.val == head.val:
listcheck(root.left, head.next)
listcheck(root.right, head.next)
def preord(root, head):
if not root: return
if root.val == head.val:
listcheck(root, head)
preord(root.left, head)
preord(root.right, head)
res = [False]
preord(root, head)
return res[0] | linked-list-in-binary-tree | Python3 || 2 Method - BFS, BFS+DFS || recursion sucks / I love recursion ❤ | Dewang_Patil | 0 | 100 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,568 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/1810646/Python3-oror-2-Method-BFS-BFS%2BDFS-oror-recursion-sucks-I-love-recursion | class Solution:
def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
def listchk(head, root):
if not head:
return True
if root and head.val == root.val:
return (listchk(head.next, root.left) or
listchk(head.next, root.right))
return False
row = {root}
while row:
nextrow = set()
for root in row:
if root.val == head.val and listchk(head, root):
return True
if root.left:
nextrow.add(root.left)
if root.right:
nextrow.add(root.right)
row = nextrow
return False | linked-list-in-binary-tree | Python3 || 2 Method - BFS, BFS+DFS || recursion sucks / I love recursion ❤ | Dewang_Patil | 0 | 100 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,569 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/1440965/Python3-Recursive-solution | class Solution:
def traversal(self, head, node):
if not head:
return True
if not node:
return False
return head.val == node.val and (
self.traversal(head.next, node.left) or self.traversal(head.next, node.right))
def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
if not root:
return False
if not head:
return True
return self.traversal(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right) | linked-list-in-binary-tree | [Python3] Recursive solution | maosipov11 | 0 | 89 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,570 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/1393707/Python3-Preorder-Traversal-%2B-KMP-matching.-greater99-runtime-70%2Bms-.-O(N)-Space-O(N)-RunTime | class Solution:
def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:
# Utilize KMP String Pattern Matching Algorithm with the preorder traversal
# O(N) space where N is max( depth of Tree, size of linked llist)
# O(N) Runtime.
def LPS(stack, size):
prd = [0] * size
prefixMatch = 0
i = 1
while i < size:
if stack[i] == stack[prefixMatch]:
prefixMatch += 1
prd[i] = prefixMatch
i += 1
else:
if prefixMatch != 0:
prefixMatch = prd[prefixMatch - 1]
else:
i += 1
return prd
def preorder(node, stack, lps, j):
if j == len(stack):
return True
elif node is None:
return False
if node.val == stack[j]:
j += 1
else:
while j:
j = lps[j - 1]
if node.val == stack[j]:
j += 1
break
return preorder(node.left, stack, lps, j) or preorder(node.right, stack, lps, j)
if head is None or root is None:
return False
stack = []
while head:
stack.append(head.val)
head = head.next
lps = LPS(stack, len(stack))
return preorder(root, stack, lps, 0) | linked-list-in-binary-tree | [Python3] Preorder Traversal + KMP matching. >99% runtime, 70+ms . O(N) Space O(N) RunTime | whitehatbuds | 0 | 115 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,571 |
https://leetcode.com/problems/linked-list-in-binary-tree/discuss/531241/Python3-108ms-solution | class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
if root is None:
return False
if self.helper(head, root):
return True
if self.isSubPath(head, root.left):
return True
return self.isSubPath(head, root.right)
def helper(self, list_node: ListNode, tree_node: TreeNode) -> bool:
if list_node is None:
return True
if tree_node is None:
return False
if tree_node.val != list_node.val:
return False
else:
return self.helper(list_node.next, tree_node.left) or self.helper(list_node.next, tree_node.right) | linked-list-in-binary-tree | Python3 108ms solution | tjucoder | 0 | 55 | linked list in binary tree | 1,367 | 0.435 | Medium | 20,572 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/1504913/Python-or-Template-or-0-1-BFS-vs-Dijkstra-or-Explanation | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
graph = {}
m, n = len(grid), len(grid[0])
def addEdges(i, j):
graph[(i, j)] = {}
neighbors = [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
for each in neighbors:
x, y = each
if x < 0 or y < 0 or x > m - 1 or y > n - 1:
continue
else:
graph[(i, j)][(x, y)] = 1
if grid[i][j] == 1:
if j != n - 1:
graph[(i, j)][(i, j + 1)] = 0
elif grid[i][j] == 2:
if j != 0:
graph[(i, j)][(i, j - 1)] = 0
elif grid[i][j] == 3:
if i != m - 1:
graph[(i, j)][(i + 1, j)] = 0
else:
if i != 0:
graph[(i, j)][(i - 1, j)] = 0
for i in range(m):
for j in range(n):
addEdges(i, j)
# convert row, col to index value in distances array
def convert(x, y):
return x * n + y
def BFS(graph):
q = deque()
q.append([0, 0, 0])
distances = [float(inf)] * (m * n)
while q:
cost, x, y = q.popleft()
if (x, y) == (m - 1, n - 1):
return cost
idx = convert(x, y)
if distances[idx] < cost:
continue
distances[idx] = cost
for node, nxtCost in graph[(x, y)].items():
nxtIndex = convert(node[0], node[1])
if distances[nxtIndex] <= cost + nxtCost:
continue
distances[nxtIndex] = cost + nxtCost
if nxtCost == 0:
q.appendleft([cost, node[0], node[1]])
else:
q.append([cost + 1, node[0], node[1]])
def dijkstra(graph):
distances = [float(inf)] * (m * n)
myheap = [[0, 0, 0]]
#distances[0] = 0
while myheap:
cost, x, y = heappop(myheap)
if (x, y) == (m - 1, n - 1):
return cost
idx = convert(x, y)
if distances[idx] < cost:
continue
else:
distances[idx] = cost
for node, nxtCost in graph[(x, y)].items():
total = cost + nxtCost
nxtIndex = convert(node[0], node[1])
if distances[nxtIndex] <= total:
continue
else:
distances[nxtIndex] = total
heappush(myheap, [total, node[0], node[1]])
return distances[-1]
#return dijkstra(graph)
return BFS(graph) | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | Python | Template | 0-1 BFS vs Dijkstra | Explanation | detective_dp | 3 | 290 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,573 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/527871/Two-kinds-of-BFS%3A-deque-BFS-and-layer-by-layer-BFS-(python) | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
i_curr, j_curr = 0, 0
cost = 0
frontier = []
visited = [[False for _ in range(n)] for _ in range(m)]
dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
while 0 <= i_curr < m and 0 <= j_curr < n and not visited[i_curr][j_curr]:
if i_curr == m - 1 and j_curr == n - 1:
return cost
visited[i_curr][j_curr] = True
frontier.append((i_curr, j_curr))
di, dj = dirs[grid[i_curr][j_curr] - 1]
i_curr += di
j_curr += dj
while frontier:
cost += 1
next_layer = []
for i, j in frontier:
for di, dj in dirs:
i_next, j_next = i + di, j + dj
while 0 <= i_next < m and 0 <= j_next < n and not visited[i_next][j_next]:
if i_next == m - 1 and j_next == n - 1:
return cost
visited[i_next][j_next] = True
next_layer.append((i_next, j_next))
di, dj = dirs[grid[i_next][j_next] - 1]
i_next += di
j_next += dj
frontier = next_layer | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | Two kinds of BFS: deque BFS and layer by layer BFS (python) | lechen999 | 2 | 156 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,574 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/1735980/Python-Djikstras-vs-01-BFS | class Solution:
def minCost(self, grid) -> int:
m, n = len(grid), len(grid[0])
pq = [(0, 0, 0)]
cost = 0
visited = [[False for _ in range(n)] for _ in range(m)]
while pq:
cost, x, y = heapq.heappop(pq)
# print(cost, x, y)
visited[x][y] = True
if x == m - 1 and y == n - 1:
return cost
if x > 0 and visited[x - 1][y] == False:
if grid[x][y] == 4:
heapq.heappush(pq, (cost, x - 1, y))
else:
heapq.heappush(pq, (cost + 1, x - 1, y))
if y > 0 and visited[x][y - 1] == False:
if grid[x][y] == 2:
heapq.heappush(pq, (cost, x, y - 1))
else:
heapq.heappush(pq, (cost + 1, x, y - 1))
if x < m - 1 and visited[x + 1][y] == False:
if grid[x][y] == 3:
heapq.heappush(pq, (cost, x + 1, y))
else:
heapq.heappush(pq, (cost + 1, x + 1, y))
if y < n - 1 and visited[x][y + 1] == False:
if grid[x][y] == 1:
heapq.heappush(pq, (cost, x, y + 1))
else:
heapq.heappush(pq, (cost + 1, x, y + 1)) | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | [Python] Djikstras vs 01 BFS | sanial2001 | 1 | 108 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,575 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/1735980/Python-Djikstras-vs-01-BFS | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
pq = [(0, 0, 0)]
cost = 0
visited = [[False for _ in range(n)] for _ in range(m)]
while pq:
cost, x, y = pq.pop(0)
#print(cost, x, y)
visited[x][y] = True
if x == m-1 and y == n-1:
return cost
if x > 0 and visited[x-1][y] == False:
if grid[x][y] == 4:
pq.insert(0, (cost, x-1, y))
else:
pq.append((cost+1, x-1, y))
if y > 0 and visited[x][y-1] == False:
if grid[x][y] == 2:
pq.insert(0, (cost, x, y-1))
else:
pq.append((cost+1, x, y-1))
if x < m-1 and visited[x+1][y] == False:
if grid[x][y] == 3:
pq.insert(0, (cost, x+1, y))
else:
pq.append((cost+1, x+1, y))
if y < n-1 and visited[x][y+1] == False:
if grid[x][y] == 1:
pq.insert(0, (cost, x, y+1))
else:
pq.append((cost+1, x, y+1)) | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | [Python] Djikstras vs 01 BFS | sanial2001 | 1 | 108 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,576 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/526344/Python3-BFS | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
direct = [(0, 1), (0, -1), (1, 0), (-1, 0)]
seen = set()
queue = [(0, 0)]
cost = 0
while queue: #breadth-first search
temp = set()
for i, j in queue:
if i == m-1 and j == n-1: return cost
if 0 <= i < m and 0 <= j < n and (i, j) not in seen: #skip invalid point
seen.add((i, j))
di, dj = direct[grid[i][j]-1]
queue.append((i+di, j+dj))
temp |= {(i+di, j+dj) for di, dj in direct}
queue = list(temp - seen)
cost += 1 | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | [Python3] BFS | ye15 | 1 | 96 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,577 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/2848360/Python3-BFS-with-PriorityQueue-soln | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
dir=[0,[0,1],[0,-1],[1,0],[-1,0]]
n=len(grid)
m=len(grid[0])
q=[[0,0,0]]
visit=set()
while q:
val,i,j=heapq.heappop(q)
if i==n-1 and j==m-1:
return val
if i<0 or i>=n or j<0 or j>=m or (i,j) in visit:
continue
visit.add((i,j))
for d in range(1,5):
heapq.heappush(q,[val+int(grid[i][j]!=d),i+dir[d][0],j+dir[d][1]]) | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | Python3 BFS with PriorityQueue soln | DhruvBagrecha | 0 | 1 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,578 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/2831318/Python-Min-Heap%3A-12-time-28-space | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
next_path = {
1: [0, 1],
2: [0, -1],
3: [1, 0],
4: [-1, 0],
}
heap = [(0, 0, 0)]
visited = set()
while(len(heap)):
c, x, y = heapq.heappop(heap)
if (x, y) in visited: continue
visited.add((x, y))
# If we reach the goal
if x == m - 1 and y == n - 1: return c
sign = grid[x][y]
for i in range(1, 5):
xx, yy = next_path[i]
new_x, new_y = x + xx, y + yy
# Move to the next spot
if 0 <= new_x < m and 0 <= new_y < n:
heapq.heappush(heap, ((c if sign == i else c + 1), new_x, new_y)) | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | Python Min Heap: 12% time, 28% space | hqz3 | 0 | 2 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,579 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/2222005/Python3-solution-Build-directed-weighted-graph-%2B-heap | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
adj_list = collections.defaultdict(list)
m, n = len(grid), len(grid[0])
dirs = [(0, -1, 2), (0, 1, 1), (1, 0, 3), (-1, 0, 4)]
for i in range(m):
for j in range(n):
for d in dirs:
new_i = i + d[0]
new_j = j + d[1]
sign = d[2]
if 0 <= new_i < m and 0 <= new_j < n:
if sign == grid[i][j]:
adj_list[(i, j)].append((new_i, new_j, 0))
else:
adj_list[(i, j)].append((new_i, new_j, 1))
heap = [(0, 0, 0)]
visited = set()
while heap:
dist, i, j = heapq.heappop(heap)
if i == m - 1 and j == n - 1:
return dist
if (i, j) in visited:
continue
visited.add((i, j))
for node in adj_list[(i, j)]:
new_i, new_j, weight = node
if (new_i, new_j) not in visited:
heapq.heappush(heap, (dist + weight, new_i, new_j))
return -1 | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | Python3 solution - Build directed, weighted graph + heap | myvanillaexistence | 0 | 11 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,580 |
https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/526126/Python3-dfs-bfs-and-dijkstra | class Solution:
def dfs(self, grid: List[List[int]]) -> int:
# timeout
size_y = len(grid)
size_x = len(grid[0])
src = (0, 0)
des = (size_y - 1, size_x - 1)
stack = [(src, 0)]
costs = {
src: 0
}
while stack:
cur, cost = stack.pop()
sign = grid[cur[0]][cur[1]]
# print(cur, cost, sign)
for neighbor, neighbor_sign in self.iter_neighbors(cur, size_y, size_x):
neighbor_cost = cost
if sign != neighbor_sign:
neighbor_cost += 1
known_neighbor_cost = costs.get(neighbor)
if known_neighbor_cost is None or known_neighbor_cost > neighbor_cost:
costs[neighbor] = neighbor_cost
stack.append((neighbor, neighbor_cost))
return costs[des]
def bfs(self, grid: List[List[int]]) -> int:
# 7500 ms, 14.2 MB
size_y = len(grid)
size_x = len(grid[0])
src = (0, 0)
des = (size_y - 1, size_x - 1)
queue = [(src, 0)]
costs = {
src: 0
}
while queue:
cur, cost = queue.pop(0)
sign = grid[cur[0]][cur[1]]
for neighbor, neighbor_sign in self.iter_neighbors(cur, size_y, size_x):
neighbor_cost = cost
if sign != neighbor_sign:
neighbor_cost += 1
known_neighbor_cost = costs.get(neighbor)
if known_neighbor_cost is None or known_neighbor_cost > neighbor_cost:
costs[neighbor] = neighbor_cost
queue.append((neighbor, neighbor_cost))
return costs[des]
def dijkstra(self, grid: List[List[int]]) -> int:
# 1000 ms, 16.7 MB
import heapq
class Node:
def __init__(self, y, x, sign, distance=0, via=None):
self.coord = (y, x)
self.distance = distance
self.via = via
self.sign = sign
def __lt__(self, other):
return self.distance < other.distance
size_y = len(grid)
size_x = len(grid[0])
start = Node(0, 0, grid[0][0])
node_map = {
(0, 0): start
}
visited_coords = {(0,0)}
heap = [start]
des_coord = (size_y - 1, size_x - 1)
while heap:
cur = heapq.heappop(heap)
visited_coords.add(cur.coord)
y, x = cur.coord
for neighbor_coord, neighbor_sign in self.iter_neighbors(cur.coord, size_y, size_x):
if neighbor_coord != cur.coord and neighbor_coord not in visited_coords:
if cur.sign == neighbor_sign:
# no penalty when it's the node the arrow is pointing at
nd = cur.distance
else:
nd = cur.distance + 1
node = node_map.get(neighbor_coord)
if node:
if node.distance > nd:
node.distance = nd
node.via = cur
heapq.heapify(heap)
else:
node = Node(*neighbor_coord, grid[neighbor_coord[0]][neighbor_coord[1]], distance=nd, via=cur)
node_map[neighbor_coord] = node
heapq.heappush(heap, node)
des_node = node_map[des_coord]
return des_node.distance
def iter_neighbors(self, coord: tuple, size_y: int, size_x: int):
y, x = coord
for sign in range(1, 5):
if sign == 1: # right
if x < size_x - 1:
yield (y, x + 1), sign
elif sign == 2: # left
if x > 0:
yield (y, x - 1), sign
elif sign == 3: # down
if y < size_y - 1:
yield (y + 1, x), sign
else: # up
if y > 0:
yield (y - 1, x), sign
def minCost(self, grid: List[List[int]]) -> int:
return self.dijkstra(grid) | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | [Python3] dfs, bfs and dijkstra | iameugenejo | 0 | 152 | minimum cost to make at least one valid path in a grid | 1,368 | 0.613 | Hard | 20,581 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/543172/Python-3-Using-Set-and-Sort-with-commentary | class Solution:
def sortString(self, s: str) -> str:
s = list(s)
# Big S: O(n)
result = []
# Logic is capture distinct char with set
# Remove found char from initial string
# Big O: O(n)
while len(s) > 0:
# Big O: O(n log n) Space: O(n)
smallest = sorted(set(s))
# Big O: O(s) - reduced set
for small in smallest:
result.append(small)
s.remove(small)
# Big O: O(n log n) Space: O(n)
largest = sorted(set(s), reverse = True)
# Big O: O(s) - reduced set
for large in largest:
result.append(large)
s.remove(large)
return ''.join(result)
# Summary: Big O(n)^2 Space: O(n) | increasing-decreasing-string | [Python 3] Using Set and Sort with commentary | dentedghost | 11 | 966 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,582 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1073396/Python-3-Simple-Clean-code-beats-greater98-speed. | class Solution:
def sortString(self, s: str) -> str:
res = ''
counter = dict(collections.Counter(s))
chars = sorted(list(set(s)))
while(counter):
for char in chars:
if char in counter:
res += char
counter[char] -= 1
if counter[char] == 0:
del counter[char]
for char in reversed(chars):
if char in counter:
res += char
counter[char] -= 1
if counter[char] == 0:
del counter[char]
return res | increasing-decreasing-string | [Python 3] Simple Clean code, beats >98% speed. | rohitmujumdar | 5 | 516 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,583 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2167833/PythonPython-3-hashmap-easy-understand-solution!!!-Beats-97 | class Solution(object):
def sortString(self, s):
dict = {}
for s1 in s:
dict[s1] = dict.get(s1, 0)+1
list1 = sorted(list(set(s)))
result = ''
while len(result) < len(s):
for l in list1:
if l in dict and dict[l] != 0:
result += l
dict[l] -= 1
for l in list1[::-1]:
if l in dict and dict[l] != 0:
result += l
dict[l] -= 1
return result | increasing-decreasing-string | [Python/Python 3] hashmap easy-understand solution!!! Beats 97% | sophiel625 | 1 | 101 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,584 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1481728/Python3-faster-than-95-Consistently-*Commented* | class Solution:
def sortString(self, s: str) -> str:
dict = {
'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0, 'e' : 0, 'f' : 0,
'g' : 0, 'h' : 0, 'i' : 0, 'j' : 0, 'k' : 0, 'l' : 0,
'm' : 0, 'n' : 0, 'o' : 0, 'p' : 0, 'q' : 0, 'r' : 0,
's' : 0, 't' : 0, 'u' : 0, 'v' : 0, 'w' : 0, 'x' : 0,
'y' : 0, 'z' : 0
}
# Set the number of occurences of each letter
# to its corresponding letter in the dict
for i in s:
dict[i] = dict[i] + 1
alpha = "abcdefghijklmnopqrstuvwxyz"
out = ''
while len(out) < len(s):
# part 1 increasing ord value of letters
for i in range(0, len(alpha)):
if dict[alpha[i]] > 0:
out = out + alpha[i]
dict[alpha[i]] = dict[alpha[i]] - 1
# decreasing ord value of letters
for i in range(len(alpha) - 1, -1, -1):
if dict[alpha[i]] > 0:
out = out + alpha[i]
dict[alpha[i]] = dict[alpha[i]] - 1
return out | increasing-decreasing-string | Python3 faster than 95% Consistently *Commented* | manuel_lemos | 1 | 200 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,585 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1403851/WEEB-DOES-PYTHON | class Solution:
def sortString(self, s: str) -> str:
string, memo = sorted(set(s)), Counter(s)
result = ""
count = 0
while len(result) < len(s):
if count == 0:
for char in string:
if memo[char] == 0: continue
result += char
memo[char] -= 1
count += 1
if count == 1:
for char in string[::-1]:
if memo[char] == 0: continue
result += char
memo[char] -= 1
count -=1
return result | increasing-decreasing-string | WEEB DOES PYTHON | Skywalker5423 | 1 | 158 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,586 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2805741/Easy-to-understand-or-BEATS-90 | class Solution:
def sortString(self, s: str) -> str:
count = len(s)
freq = [0]*26 #conatins frequency(no. of occurance) - a-z
res=[]
#incrementing frequency of characters that are found in string ...kinda like dict / hashmap
for i in s:
freq[ord(i)-ord('a')] += 1
while count>0:
for i in range(len(freq)): #forward
if freq[i]!=0:
res.append(chr(ord('a')+i)) #appending to result in charater form
freq[i] -= 1
count -= 1
for i in range(len(freq)-1,-1,-1): #reverse
if freq[i]!=0:
res.append(chr(ord('a')+i))
freq[i] -= 1
count -= 1
return ''.join(res) | increasing-decreasing-string | Easy to understand | BEATS 90% | Nick_23 | 0 | 6 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,587 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2723284/Python3-Solution-with-using-counting | class Solution:
def sortString(self, s: str) -> str:
c = [0] * 26
cur_symb_cnt = len(s)
for char in s:
c[ord(char) - 97] += 1
res = []
while cur_symb_cnt > 0:
for i in range(len(c)):
if c[i] != 0:
res.append(chr(i + 97))
cur_symb_cnt -= 1
c[i] -= 1
for i in range(len(c) - 1, -1, -1):
if c[i] != 0:
res.append(chr(i + 97))
cur_symb_cnt -= 1
c[i] -= 1
return ''.join(res) | increasing-decreasing-string | [Python3] Solution with using counting | maosipov11 | 0 | 7 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,588 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2714240/Python3-KeySort-left-to-right | class Solution:
def sortString(self, s: str) -> str:
# count the elements and have an order
chars = [0]*26
for char in s:
# 97 == ord('a')
chars[ord(char) - 97] += 1
# end if we have no chars lef
leftover = len(s)
update = 1
position = -1
result = []
while leftover:
# update the position
position += update
# check the position in of bounds
if position < 0 or position > 25:
# change the updater
update = -1*update
# continue again
continue
# check the current position
if chars[position] > 0:
# update char counter and
# overall counter
chars[position] -= 1
leftover -= 1
# append the char, 97 == ord('a')
result.append(chr(position+97))
return "".join(result) | increasing-decreasing-string | [Python3] - KeySort left to right | Lucew | 0 | 3 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,589 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2587026/SIMPLE-PYTHON3-SOLUTION-using-hashmap | class Solution:
def sort_hm(self, s1,hm, keys):
for k in keys:
if hm[k] >0:
s1 += k
hm[k] -=1
return s1, hm
def sortString(self, s: str) -> str:
# Logic is based on counts
# Create hash map first
hm = {}
for i in s:
hm[i] = hm.get(i,0) + 1
s1=''
while(len(s1) != len(s)):
# step 1,2,3 of algoriths
keys = sorted(hm)
s1, hm = self.sort_hm(s1,hm, keys)
# step 4,5,6 of algoriths
keys = sorted(hm,reverse=True)
s1, hm = self.sort_hm(s1,hm, keys)
return s1 | increasing-decreasing-string | ✅✔ SIMPLE PYTHON3 SOLUTION ✅✔using hashmap | rajukommula | 0 | 37 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,590 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2579652/solution-in-python3 | class Solution:
def sortString(self, s: str) -> str:
l=len(s)
res=''
f={}
for i in s:
if i in f:
f[i]+=1
else:
f[i]=1
s_k=sorted(f.keys())
r_k=list(reversed(s_k))
while l!=0:
for x in s_k:
if f[x]!=0:
res+=x
f[x]-=1
l-=1
for x in r_k:
if f[x]!=0:
res+=x
f[x]-=1
l-=1
return res | increasing-decreasing-string | solution in python3 | RITIK_30454 | 0 | 39 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,591 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2550616/Python3-sort-the-key-one-time-instead-of-the-string. | class Solution:
def sortString(self, s: str) -> str:
counter = collections.Counter(s)
sorted_keys = sorted(counter.keys())
result = ''
while sum(counter.values()):
for key in sorted_keys:
if counter[key]!=0:
result+=key
counter[key]-=1
for key in reversed(sorted_keys):
if counter[key]!=0:
result+=key
counter[key]-=1
return result | increasing-decreasing-string | [Python3] sort the key one time instead of the string. | JustinL | 0 | 33 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,592 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2129242/python-3-oror-simple-hash-map-solution | class Solution:
def sortString(self, s: str) -> str:
count = collections.Counter(s)
res = []
chrs = [''] * 52
for i in range(26):
chrs[i] = chrs[~i] = chr(i + 97)
remaining = True
while remaining:
remaining = False
for c in chrs:
if count[c] == 0:
continue
res.append(c)
count[c] -= 1
remaining = True
return ''.join(res) | increasing-decreasing-string | python 3 || simple hash map solution | dereky4 | 0 | 133 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,593 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2072763/python-solution-using-dictionary-and-sets | class Solution:
def sortString(self, s: str) -> str:
size = len(s)
d = {k: s.count(k) for k in s}
s = sorted(list(set(s)), key=ord)
res = ""
for i in range(size):
for c in s:
if d.get(c):
res += c
d[c] -= 1
if not d[c]:
d.pop(c)
for c in reversed(s):
if d.get(c):
res += c
d[c] -= 1
if not d[c]:
d.pop(c)
return res | increasing-decreasing-string | python solution using dictionary and sets | andrewnerdimo | 0 | 83 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,594 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2047646/Increasing-Decreasing-String | class Solution(object):
def sortString(self, s):
"""
:type s: str
:rtype: str
"""
data = sorted([c, n] for c, n in Counter(s).items())
result = []
while len(result) < len(s):
for i in range(len(data)):
if data[i][1]:
result.append(data[i][0])
data[i][1] -= 1
for i in range(len(data)):
if data[~i][1]:
result.append(data[~i][0])
data[~i][1] -= 1
return ''.join(result) | increasing-decreasing-string | Increasing Decreasing String | Muggles102 | 0 | 55 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,595 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/2010686/Python-easy-solution-faster-than-97 | class Solution:
def sortString(self, s: str) -> str:
freq = dict(Counter(s))
chars = sorted(list(set(s)))
res = ""
while freq:
for i in chars:
if i in freq:
res += i
freq[i] -= 1
if freq[i] == 0:
del freq[i]
for i in chars[::-1]:
if i in freq:
res += i
freq[i] -= 1
if freq[i] == 0:
del freq[i]
return res | increasing-decreasing-string | Python easy solution faster than 97% | alishak1999 | 0 | 116 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,596 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1980562/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def sortString(self, s: str) -> str:
dict = {}
alphabets = "abcdefghijklmnopqrstuvwxyz"
output = ""
for i in s:
if i not in dict:
dict[i] = 1
else:
dict[i]+=1
while len(output) < len(s):
for i in alphabets:
if i in dict and dict[i]>0:
output+=i
dict[i]-=1
for j in reversed(alphabets):
if j in dict and dict[j]>0:
output+=j
dict[j]-=1
return output | increasing-decreasing-string | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 90 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,597 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1851544/5-Lines-Python-Solution-oror-93-Faster-oror-Memory-less-than-63 | class Solution:
def sortString(self, s: str) -> str:
C=sorted(Counter(s).items()) ; ans=''
while len(C)>0:
ans+=''.join([x for x,y in C]) ; C=[(x,y-1) for x,y in C if y>1]
ans+=''.join([x for x,y in C])[::-1] ; C=[(x,y-1) for x,y in C if y>1]
return ans | increasing-decreasing-string | 5-Lines Python Solution || 93% Faster || Memory less than 63% | Taha-C | 0 | 101 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,598 |
https://leetcode.com/problems/increasing-decreasing-string/discuss/1851544/5-Lines-Python-Solution-oror-93-Faster-oror-Memory-less-than-63 | class Solution:
def sortString(self, s: str) -> str:
s=list(s) ; ans=[]
while len(s)>0:
smallest=sorted(set(s))
for small in smallest: ans.append(small) ; s.remove(small)
largest=sorted(set(s),reverse=True)
for large in largest: ans.append(large) ; s.remove(large)
return ''.join(ans) | increasing-decreasing-string | 5-Lines Python Solution || 93% Faster || Memory less than 63% | Taha-C | 0 | 101 | increasing decreasing string | 1,370 | 0.774 | Easy | 20,599 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.