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/minimum-time-to-complete-trips/discuss/1802745/Python-solution-using-Binary-Search
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: if len(time) == 1: return totalTrips * time[0] def compute(arr, number): res = 0 for i in arr: if number >= i: res += number // i else: break return res time.sort() n = len(time) left = totalTrips * time[0] // n right = totalTrips * time[0] while left < right: mid = (left + right) // 2 res = compute(time, mid) if res < totalTrips: left = mid + 1 else: right = mid return left
minimum-time-to-complete-trips
Python solution using Binary Search
bianrui0315
0
14
minimum time to complete trips
2,187
0.32
Medium
30,400
https://leetcode.com/problems/minimum-time-to-complete-trips/discuss/1802659/Python3-or-binary-search
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: def feasible(timeAllot): ''' This function find the number of trips taken by the buses for the given time ''' totalCount = 0 for var in time: totalCount+=timeAllot//var return totalCount maxBus = max(time) low = 1 high = maxBus * totalTrips ans = 0 while low <= high: mid = low+(high-low)//2 #Finding how many trips the buses are doing tripsDone = feasible(mid) if tripsDone>=totalTrips: #If tripsDone are more than totalTrips this can be a possible Solution #Hence we store this and search the remaining solution space ans = mid high = mid-1 else: #If we are unable to do that many trips we should discard #this and move forward with a smile :) low = mid+1 return ans
minimum-time-to-complete-trips
Python3 | binary search
Anilchouhan181
0
24
minimum time to complete trips
2,187
0.32
Medium
30,401
https://leetcode.com/problems/minimum-time-to-complete-trips/discuss/1802559/Python3-O(N-log-T2)-Binary-Search-on-Solution-Space-(explained)
class Solution: def maxtrip(self, time): trips = 0 for t in (k for k in self.counter.keys() if k <= time): trips += self.counter[t] * (time // t) return trips def minimumTime(self, time: List[int], totalTrips: int) -> int: self.counter = Counter(time) lo, hi = 1, 10**14 def p(t): return self.maxtrip(t) >= totalTrips while lo < hi: mid = lo + (hi - lo) // 2 if p(mid): hi = mid else: lo = mid + 1 return lo
minimum-time-to-complete-trips
[Python3] O(N log T^2) Binary Search on Solution Space (explained)
dwschrute
0
20
minimum time to complete trips
2,187
0.32
Medium
30,402
https://leetcode.com/problems/minimum-time-to-complete-trips/discuss/1802521/PYTHON3-SIMPLE-BINARY-SEARCH
class Solution: def minimumTime(self, time: List[int], totalTrips: int) -> int: def condition(mid,nums,totalTrips): ans=0 for num in nums: ans+=mid//num if ans>=totalTrips: return True return False lo=0 #minimum time any truck can take hi=totalTrips*min(time) #maximum time any truck can take while lo<=hi: mid=lo+(hi-lo)//2 if condition(mid, time,totalTrips): hi=mid-1 else: lo=mid+1 return lo
minimum-time-to-complete-trips
[PYTHON3] SIMPLE BINARY SEARCH
_shubham28
0
15
minimum time to complete trips
2,187
0.32
Medium
30,403
https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1803014/Python-DP-with-pre-treatment-to-reduce-time-complexity
class Solution: def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: tires.sort() newTires = [] minTime = [changeTime*(i-1) + tires[0][0]*i for i in range(numLaps+1)] minTime[0] = 0 maxi = 0 for f,r in tires: if not newTires or f>newTires[-1][0] and r<newTires[-1][1]: newTires.append([f,r]) t = f i = 1 while i<numLaps and t*(r-1)<changeTime: t = t*r + f i += 1 if minTime[i]>t: minTime[i]=t maxi = max(i,maxi) for lap in range(numLaps+1): for run in range(min(lap,maxi+1)): minTime[lap] = min(minTime[lap],minTime[lap-run]+changeTime+minTime[run]) return minTime[numLaps]
minimum-time-to-finish-the-race
[Python] DP with pre-treatment to reduce time complexity
wssx349
3
226
minimum time to finish the race
2,188
0.419
Hard
30,404
https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1802676/Python3-dp
class Solution: def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: init = [inf] * 20 for f, r in tires: prefix = term = f for i in range(20): init[i] = min(init[i], prefix) term *= r if term >= f+changeTime: break prefix += term @cache def fn(n): """Return min time to finish n laps.""" ans = init[n-1] if n <= 20 else inf for nn in range(1, min(20, n//2)+1): ans = min(ans, fn(nn) + fn(n-nn) + changeTime) return ans return fn(numLaps)
minimum-time-to-finish-the-race
[Python3] dp
ye15
1
214
minimum time to finish the race
2,188
0.419
Hard
30,405
https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1804202/Python-3-Geometric-progression-sum-and-DP-(hint-solution)-with-comments-(Optimization-needed)
class Solution: def minimumFinishTime(self, tires: List[List[int]], ct: int, laps: int) -> int: t_nochange = defaultdict(lambda: float('inf')) for f, r in tires: # calculate how many laps could go without changing tires # f * pow(r, p) <= f + ct p = math.ceil(math.log(1 + ct/f, r)) # for each possible lap calculate cumulative sum and update the minimum time for laps # geometric progression sum = f * (pow(r, i) - 1) / (r - 1) for i in range(1, p+1): t_nochange[i] = min(t_nochange[i], f * (pow(r, i) - 1) / (r - 1)) # possible max laps without changing tires max_t = max(t_nochange) @lru_cache(None) def dp(rest_laps): if rest_laps == 0: return 0 ans = float('inf') for k in range(1, min(rest_laps, max_t) + 1): ans = min(ans, t_nochange[k] + ct + dp(rest_laps - k)) return ans return int(dp(laps)) - ct # no need to change tire for first one
minimum-time-to-finish-the-race
[Python 3] Geometric progression sum and DP (hint solution) with comments (Optimization needed)
chestnut890123
0
92
minimum time to finish the race
2,188
0.419
Hard
30,406
https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1802856/Python3-Dynamic-Programming
class Solution: def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int: @cache def lapTime(tire,x): f,r = tire return f*(r**(x-1)) best_laps = {} for tire in tires: tire = tuple(tire) time = 0 # stop at max time for a tire without changing for i in range(1,1001): currtime = lapTime(tire,i) if currtime >= lapTime(tire,1)+changeTime: break time += currtime # update dictionary if i in best_laps: best_laps[i] = min(best_laps[i],time+changeTime) else: best_laps[i] = time+changeTime # dynamic programming dp = [float('inf') for _ in range(numLaps)] for i in range(numLaps): # if could get lap i using a single tire if i+1 in best_laps: dp[i] = best_laps[i+1] # or get lap i changing from last tire for k,v in best_laps.items(): if i-k>=0: dp[i] = min(dp[i], dp[i-k]+v) # subtract change time because first tire doesn't need to change return dp[numLaps-1] - changeTime
minimum-time-to-finish-the-race
[Python3] Dynamic Programming
Rainyforest
0
81
minimum time to finish the race
2,188
0.419
Hard
30,407
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
class Solution: def mostFrequent(self, nums, key): counts = {} for i in range(1,len(nums)): if nums[i-1]==key: if nums[i] not in counts: counts[nums[i]] = 1 else: counts[nums[i]] += 1 return max(counts, key=counts.get)
most-frequent-number-following-key-in-an-array
Python - Multiple Solutions + One-Liners | Clean and Simple
domthedeveloper
4
214
most frequent number following key in an array
2,190
0.605
Easy
30,408
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
class Solution: def mostFrequent(self, nums, key): arr = [nums[i] for i in range(1,len(nums)) if nums[i-1]==key] c = Counter(arr) return max(c, key=c.get)
most-frequent-number-following-key-in-an-array
Python - Multiple Solutions + One-Liners | Clean and Simple
domthedeveloper
4
214
most frequent number following key in an array
2,190
0.605
Easy
30,409
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
class Solution: def mostFrequent(self, nums, key): return max(c := Counter([nums[i] for i in range(1,len(nums)) if nums[i-1]==key]), key=c.get)
most-frequent-number-following-key-in-an-array
Python - Multiple Solutions + One-Liners | Clean and Simple
domthedeveloper
4
214
most frequent number following key in an array
2,190
0.605
Easy
30,410
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
class Solution: def mostFrequent(self, nums, key): return mode(nums[i] for i in range(1,len(nums)) if nums[i-1]==key)
most-frequent-number-following-key-in-an-array
Python - Multiple Solutions + One-Liners | Clean and Simple
domthedeveloper
4
214
most frequent number following key in an array
2,190
0.605
Easy
30,411
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple
class Solution: def mostFrequent(self, nums, key): return mode(b for a, b in pairwise(nums) if a == key)
most-frequent-number-following-key-in-an-array
Python - Multiple Solutions + One-Liners | Clean and Simple
domthedeveloper
4
214
most frequent number following key in an array
2,190
0.605
Easy
30,412
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1914928/Python3-Dictionary-Solution-With-Explanation
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: m = {} for i in range(len(nums) - 1): if nums[i] == key: if nums[i + 1] in m: m[nums[i + 1]] += 1 else: m[nums[i + 1]] = 1 # Get the value related to the max value in the dictionary return max(m, key = lambda k : m[k])
most-frequent-number-following-key-in-an-array
Python3 Dictionary Solution With Explanation
Hejita
1
110
most frequent number following key in an array
2,190
0.605
Easy
30,413
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1822593/Python
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: c = defaultdict(int) max_count = 0 max_target = 0 for i in range(1, len(nums)): if nums[i-1] == key: c[nums[i]] += 1 if c[nums[i]] > max_count: max_count = c[nums[i]] max_target = nums[i] return max_target
most-frequent-number-following-key-in-an-array
Python
blue_sky5
1
49
most frequent number following key in an array
2,190
0.605
Easy
30,414
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2833207/Python-easy-code-solution-or-Runtime-beats%3A-98
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: a = [] for i in range(len(nums)): if(i != len(nums)-1): if(nums[i] == key): a.append(nums[i+1]) c = Counter(a) print(c) ans = max(c,key = c.get) return ans
most-frequent-number-following-key-in-an-array
Python easy code solution | Runtime beats: 98%
anshu71
0
2
most frequent number following key in an array
2,190
0.605
Easy
30,415
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2807798/O(n%2Bm)-87ms-python
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: uniqueInts = max(nums) length = len(nums) freqs = [0 for i in range(uniqueInts+1)] #count every unique number #Goto each target for i in range(len(nums)): #iterate the index of inputlist if nums[i] == key: #at each key if i+1 < length: #if following target is in arr freqs[nums[i+1]] += 1 #increase the frequency #Find most often target maximum = 0 #saves which count is the highest value = -1 #saves the value counted for i in range(uniqueInts+1): #for each unique value if freqs[i] > maximum: maximum=freqs[i]; value = i #check if its the new max and saves it return value #return most occurring target
most-frequent-number-following-key-in-an-array
O(n+m) 87ms python
lucasscodes
0
2
most frequent number following key in an array
2,190
0.605
Easy
30,416
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2763799/Most-Frequent-Number-Following-Key-In-an-Array-or-Using-Dictionaries-or-Python
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: d={} i=0 while(i<len(nums)-1): if nums[i]==key: target=nums[i+1] count=0 for j in range(i+1,len(nums)): if nums[j]==target: count+=1 else: break if target not in d: d[target]=count else: d[target]= d[target]+count i+=count else: i+=1 key_list = list(d.keys()) val_list = list(d.values()) maximim_count=max(val_list) position = val_list.index(maximim_count) return (key_list[position])
most-frequent-number-following-key-in-an-array
Most Frequent Number Following Key In an Array | Using Dictionaries | Python
saptarishimondal
0
1
most frequent number following key in an array
2,190
0.605
Easy
30,417
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2502510/Simple-solution-using-dictionary-and-lambda-function-in-Python
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: freq = {} for i in range(len(nums)): val = nums[i] if val == key and i + 1 < len(nums): val2 = nums[i + 1] freq[val2] = 1 + freq.get(val2, 0) return max(freq, key= lambda x: freq[x])
most-frequent-number-following-key-in-an-array
Simple solution using dictionary and lambda function in Python
ankurbhambri
0
16
most frequent number following key in an array
2,190
0.605
Easy
30,418
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2384958/Python3-Easy-hashmap-Faster-than-90
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: nums=nums + [-1] c={} l=len(nums) max_=-1 ans=-1 for i in range(l-1): if nums[i]==key: if nums[i+1] in c: c[nums[i+1]]+=1 else: c[nums[i+1]]=1 if c[nums[i+1]] > max_: max_ = max(max_,c[nums[i+1]]) ans=nums[i+1] return ans
most-frequent-number-following-key-in-an-array
[Python3] Easy hashmap- Faster than 90%
sunakshi132
0
26
most frequent number following key in an array
2,190
0.605
Easy
30,419
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2332476/Easy-Hashmap-Solution
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: hashMap = collections.defaultdict(int) key_found=False for idx, el in enumerate(nums): # Check if key is already found and the target value is key and is contiguous if key_found and nums[idx-1] == key: hashMap[el]+=1 if el == key: key_found=True print(hashMap) return sorted(hashMap.items(), key=lambda k:k[1], reverse=True)[0][0]
most-frequent-number-following-key-in-an-array
Easy Hashmap Solution
yashchandani98
0
14
most frequent number following key in an array
2,190
0.605
Easy
30,420
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2252836/Python-Short-and-Simple
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: arr = [nums[i+1] for i in range(len(nums)-1) if nums[i] == key] d = Counter(arr) return max(d, key = d.get) ## Return the Key with Maximum Value
most-frequent-number-following-key-in-an-array
Python Short and Simple
theReal007
0
18
most frequent number following key in an array
2,190
0.605
Easy
30,421
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2217803/Python-Simple-Solution-or-Beats-speed-97
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: d = {} l = len(nums) m = ind = 0 for i in range(l - 1): if nums[i] == key: cur_n = nums[i + 1] if cur_n in d: d[cur_n] += 1 else: d[cur_n] = 1 if d[cur_n] > m: m = d[cur_n] ind = cur_n return ind
most-frequent-number-following-key-in-an-array
Python Simple Solution | Beats speed 97%
Bec1l
0
43
most frequent number following key in an array
2,190
0.605
Easy
30,422
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/2152345/Python3-freq-table
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: freq = Counter(x for i, x in enumerate(nums) if i and nums[i-1] == key) return max(freq, key=freq.get)
most-frequent-number-following-key-in-an-array
[Python3] freq table
ye15
0
29
most frequent number following key in an array
2,190
0.605
Easy
30,423
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1979234/Python-Easy-To-Understand-Solution
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: def most_frequent(List): return max(set(List), key = List.count) amt_following = 0 amt_showed = [] for i in range(len(nums)): if nums[i] == key: if i <= len(nums)-2: amt_following = nums[i+1] amt_showed.append(nums[i+1]) return most_frequent(amt_showed)
most-frequent-number-following-key-in-an-array
Python Easy To Understand Solution
KirillMcQ
0
74
most frequent number following key in an array
2,190
0.605
Easy
30,424
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1944124/Python-dollarolution
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: d = {} for i in range(1,len(nums)): if nums[i-1] == key: if nums[i] not in d: d[nums[i]] = 1 else: d[nums[i]] += 1 return max(d, key=d.get)
most-frequent-number-following-key-in-an-array
Python $olution
AakRay
0
31
most frequent number following key in an array
2,190
0.605
Easy
30,425
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1860222/python-simple-hashmap-solution
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: n = len(nums) count = defaultdict(int) maxcount = 0 for i in range(n-1): if nums[i] == key: count[nums[i+1]] += 1 maxcount = max(maxcount, count[nums[i+1]]) for k, v in count.items(): if v == maxcount: return k
most-frequent-number-following-key-in-an-array
python simple hashmap solution
byuns9334
0
44
most frequent number following key in an array
2,190
0.605
Easy
30,426
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1843877/Python-(Simple-approach-and-Beginner-friendly)
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: dict = {} for i in range(len(nums)-1): if nums[i] == key: if nums[i+1] not in dict: dict[nums[i+1]]=1 else: dict[nums[i+1]]+=1 return max(dict, key = dict.get)
most-frequent-number-following-key-in-an-array
Python (Simple approach and Beginner-friendly)
vishvavariya
0
60
most frequent number following key in an array
2,190
0.605
Easy
30,427
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1825271/Python-Simply-follow-the-topic
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: targets = [] for i in range(1, len(nums)): if nums[i - 1] == key: targets.append(nums[i]) if len(targets) == 1: return targets[0] m = collections.defaultdict(int) for t in targets: m[t] += 1 return max(m, key=m.get)
most-frequent-number-following-key-in-an-array
[Python] Simply follow the topic
casshsu
0
29
most frequent number following key in an array
2,190
0.605
Easy
30,428
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1825271/Python-Simply-follow-the-topic
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: c = Counter() for i in range(1, len(nums)): if nums[i - 1] == key: c[nums[i]] += 1 return c.most_common(1)[0][0]
most-frequent-number-following-key-in-an-array
[Python] Simply follow the topic
casshsu
0
29
most frequent number following key in an array
2,190
0.605
Easy
30,429
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1822423/An-intuitive-approach-simple
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: n = len(nums) dic = {} for i in range(n-1): if nums[i] == key: if nums[i+1] not in dic: dic[nums[i+1]] = 1 else: dic[nums[i+1]] += 1 #print(dic) val = max(dic.values()) #print(val) for key in dic: if dic[key] == val: #print(key) return key
most-frequent-number-following-key-in-an-array
An intuitive approach [simple]
nandanabhishek
0
43
most frequent number following key in an array
2,190
0.605
Easy
30,430
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1822398/python-3-simple-hash-map-solution
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: count = collections.Counter() max_count = 0 target = -1 for i in range(len(nums) - 1): if nums[i] != key: continue count[nums[i + 1]] += 1 if count[nums[i + 1]] > max_count: max_count = count[nums[i + 1]] target = nums[i + 1] return target
most-frequent-number-following-key-in-an-array
python 3, simple hash map solution
dereky4
0
33
most frequent number following key in an array
2,190
0.605
Easy
30,431
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1822358/Python3-or-Simple-solution-using-max-function-with-key-and-an-extra-array-to-keep-track-of-targets
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: target = [] for i in range(len(nums) - 1): if nums[i] == key: target.append(nums[i+1]) return max(target, key=target.count) # Time Complexity: O(n) # Space Complexity: O(n)
most-frequent-number-following-key-in-an-array
Python3 | Simple solution using max function with key and an extra array to keep track of targets
HunkWhoCodes
0
22
most frequent number following key in an array
2,190
0.605
Easy
30,432
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1822275/python3-hashmap
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: hashmap = collections.defaultdict(int) for a, b in zip(nums, nums[1:]): if a == key: hashmap[b] += 1 max_val = max(val for val in hashmap.values()) for key, val in hashmap.items(): if val == max_val: return key
most-frequent-number-following-key-in-an-array
python3, hashmap
emersonexus
0
20
most frequent number following key in an array
2,190
0.605
Easy
30,433
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1822127/Python-hashmap
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: d = defaultdict(int) left, right = 0, len(nums)-1 while left < right: if nums[left] == key: d[nums[left+1]] += 1 left += 1 return max(d, key=d.get)
most-frequent-number-following-key-in-an-array
Python hashmap
Rush_P
0
28
most frequent number following key in an array
2,190
0.605
Easy
30,434
https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1821973/Python-3-(70ms)-or-Dictionary-Solution-or-Easy-to-Understand
class Solution: def mostFrequent(self, nums: List[int], key: int) -> int: d={} for i in range(len(nums)-1): if nums[i]==key: if nums[i+1] in d: d[nums[i+1]]+=1 else: d[nums[i+1]]=1 m=-1 for j in d: m=max(m,d[j]) for key, value in d.items(): if m == value: return key
most-frequent-number-following-key-in-an-array
Python 3 (70ms) | Dictionary Solution | Easy to Understand
MrShobhit
0
54
most frequent number following key in an array
2,190
0.605
Easy
30,435
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822244/Sorted-Lambda
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: @cache def convert(i: int): res, pow10 = 0, 1 while i: res += pow10 * mapping[i % 10] i //= 10 pow10 *= 10 return res return sorted(nums, key=lambda i: mapping[i] if i < 10 else convert(i))
sort-the-jumbled-numbers
Sorted Lambda
votrubac
8
869
sort the jumbled numbers
2,191
0.453
Medium
30,436
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822468/Python-10-Liner-Solution
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: res = [] for num in nums: ans = "" for char in str(num): ans += str(mapping[int(char)]) res.append(int(ans)) final = list(zip(nums, res)) final = sorted(final, key=lambda x: x[1]) return [tup[0] for tup in final]
sort-the-jumbled-numbers
[Python] - 10 Liner Solution ✔
leet_satyam
2
54
sort the jumbled numbers
2,191
0.453
Medium
30,437
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822287/python-1-line
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: return sorted(nums, key = lambda x: int("".join([str(mapping[int(digit)]) for digit in str(x)])))
sort-the-jumbled-numbers
python 1-line
emersonexus
2
97
sort the jumbled numbers
2,191
0.453
Medium
30,438
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1828757/Python-2-lines.-Does-using-strings-count-as-cheating
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: m = { str(i): str(v) for i, v in enumerate(mapping) } def mapFunc(n): return int(''.join(m[i] for i in str(n))) return sorted(nums, key=mapFunc)
sort-the-jumbled-numbers
Python 2 lines. Does using strings count as cheating?
SmittyWerbenjagermanjensen
1
73
sort the jumbled numbers
2,191
0.453
Medium
30,439
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1828757/Python-2-lines.-Does-using-strings-count-as-cheating
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: m = { str(i): str(v) for i, v in enumerate(mapping) } return sorted(nums, key=lambda x: int(''.join(m[i] for i in str(x))))
sort-the-jumbled-numbers
Python 2 lines. Does using strings count as cheating?
SmittyWerbenjagermanjensen
1
73
sort the jumbled numbers
2,191
0.453
Medium
30,440
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822078/Python-3%3A-Easy-Solution
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: h = {} ans = [] for num in nums: res = 0 for i in str(num): val = mapping[int(i)] res = res*10 + val ans.append((num,res)) ans.sort(key=lambda x:x[1]) return [each[0] for each in ans]
sort-the-jumbled-numbers
Python 3: Easy Solution
deleted_user
1
20
sort the jumbled numbers
2,191
0.453
Medium
30,441
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822072/Python-3-Sorting-using-key-function-in-Python
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: ans = [] def compare(num): temp = "" for digit in str(num): temp += str(mapping[int(digit)]) return int(temp) return sorted(nums, key=compare)
sort-the-jumbled-numbers
[Python 3] Sorting using key function in Python
hari19041
1
49
sort the jumbled numbers
2,191
0.453
Medium
30,442
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/2777340/Python-3-3-Lines
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: md={str(i):str(mapping[i]) for i in range(len(mapping))} md2=[[i,int(''.join([md[j] for j in str(i)]))] for i in nums] return [i[0] for i in sorted(md2,key=lambda x:x[1])]
sort-the-jumbled-numbers
Python 3-3 Lines
Burak1069711851
0
2
sort the jumbled numbers
2,191
0.453
Medium
30,443
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/2152354/Python3-1-line
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: return sorted(nums, key=lambda x: int(''.join(str(mapping[int(d)]) for d in str(x))))
sort-the-jumbled-numbers
[Python3] 1-line
ye15
0
24
sort the jumbled numbers
2,191
0.453
Medium
30,444
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1927733/python-3-oror-simple-solution
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: nums.sort(key=lambda num: self.value(num, mapping)) return nums def value(self, num, mapping): if num == 0: return mapping[0] res, m = 0, 1 while num: res += m * mapping[num % 10] m *= 10 num //= 10 return res
sort-the-jumbled-numbers
python 3 || simple solution
dereky4
0
66
sort the jumbled numbers
2,191
0.453
Medium
30,445
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1828027/Sort-tuples-66-speed
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: mapping = [str(i) for i in mapping] return [tpl[2] for tpl in sorted((int("".join(mapping[int(c)] for c in str(n))), i, n) for i, n in enumerate(nums))]
sort-the-jumbled-numbers
Sort tuples, 66% speed
EvgenySH
0
14
sort the jumbled numbers
2,191
0.453
Medium
30,446
https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822122/Python-sort-list-of-tuples
class Solution: def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]: def getMappedNum(num): s = str(num) mappedNum = "" for c in s: mappedNum = mappedNum + str(mapping[int(c)]) return int(mappedNum) sortedNums = [] for num in nums: sortedNums.append((getMappedNum(num), num)) sortedNums.sort(key=lambda x: x[0]) for i, (_, num) in enumerate(sortedNums): nums[i] = num return nums
sort-the-jumbled-numbers
Python sort list of tuples
Rush_P
0
25
sort the jumbled numbers
2,191
0.453
Medium
30,447
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2333862/Python3-or-Solved-using-Topo-Sort(Kahn-Algo)-with-Queue(BFS)
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: #Use Kahn's algorithm of toposort using a queue and bfs! graph = [[] for _ in range(n)] indegrees = [0] * n #Time: O(n^2) #Space: O(n^2 + n + n) -> O(n^2) #1st step: build adjacency list grpah and update the initial indegrees of every node! for edge in edges: src, dest = edge[0], edge[1] graph[src].append(dest) indegrees[dest] += 1 queue = deque() ans = [set() for _ in range(n)] #2nd step: go through the indegrees array and add to queue for any node that has no ancestor! for i in range(len(indegrees)): if(indegrees[i] == 0): queue.append(i) #Kahn's algorithm initiation! #while loop will run for each and every node in graph! #in worst case, adjacency list for one particular node may contain all other vertices! while queue: cur = queue.pop() #for each neighbor for neighbor in graph[cur]: #current node is ancestor to each and every neighboring node! ans[neighbor].add(cur) #every ancestor of current node is also an ancestor to the neighboring node! ans[neighbor].update(ans[cur]) indegrees[neighbor] -= 1 if(indegrees[neighbor] == 0): queue.append(neighbor) #at the end, we should have set of ancestors for each and every node! #in worst case, set s for ith node could have all other vertices be ancestor to node i ! ans = [(sorted(list(s))) for s in ans] return ans
all-ancestors-of-a-node-in-a-directed-acyclic-graph
Python3 | Solved using Topo Sort(Kahn Algo) with Queue(BFS)
JOON1234
4
169
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,448
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1822118/Python-3-Reverse-direction-and-Find-all-Children
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: ans = [[] for _ in range(n)] graph = defaultdict(list) for f, t in edges: graph[t].append(f) memo = defaultdict(list) def dfs(src): if src in memo: return memo[src] for nei in graph[src]: memo[src] += [nei]+dfs(nei) memo[src] = list(set(memo[src])) return memo[src] for i in range(n): dfs(i) return [sorted(memo[i]) for i in range(n)]
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[Python 3] Reverse direction and Find all Children
hari19041
2
112
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,449
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1823284/Python-3-Topological-sort-via-BFS
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: # Topological sort with BFS (Kahn's algorithm) # Similar to LC 207 (Course Schedule), LC 210 (Course Schedule II) graph = [[] for _ in range(n)] inDegree = [0] * n for edge in edges: start, end = edge[0], edge[1] graph[start].append(end) inDegree[end] += 1 output = [set() for _ in range(n)] queue = deque() for i in range(n): if inDegree[i] == 0: queue.append(i) while queue: for _ in range(len(queue)): node = queue.popleft() for desc in graph[node]: output[desc].add(node) for anc in output[node]: output[desc].add(anc) inDegree[desc] -= 1 if inDegree[desc] == 0: queue.append(desc) for i in range(n): output[i] = sorted(list(output[i])) return output
all-ancestors-of-a-node-in-a-directed-acyclic-graph
Python 3 Topological sort via BFS
xil899
1
106
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,450
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2774441/Topological-sort-Python-N2
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: retList = [[] for i in range(n) ] graph = collections.defaultdict(list) indegree = [0] * n topologicalSort = [] # Build graph and calculate indegree for one,two in edges: graph[one].append(two) indegree[two]+=1 # Until the topological sort is done while len(topologicalSort) != n: # Find a source with a indegree of 0 source = indegree.index(0) indegree[source] = -1 topologicalSort.append(source) for node in graph[source]: # Add source retList[node].append(source) # Add parents sources retList[node] = list(set(retList[source]).union(set(retList[node]))) retList[node].sort() indegree[node] -=1 return retList
all-ancestors-of-a-node-in-a-directed-acyclic-graph
Topological sort Python N^2
Sarthaksin1857
0
16
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,451
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2502761/Python-Simple-Topological-Sort-Solution
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: indeg, graph = [0]*n, defaultdict(list) for u, v in edges: graph[u].append(v) indeg[v] += 1 queue, res = deque([i for i in range(n) if indeg[i] == 0]), [set() for _ in range(n)] while queue: curr = queue.popleft() for nxtNode in graph[curr]: res[nxtNode].add(curr) res[nxtNode] |= res[curr] indeg[nxtNode] -= 1 if indeg[nxtNode] == 0: queue.append(nxtNode) return list(map(sorted, res))
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[Python] Simple Topological Sort Solution
Saksham003
0
55
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,452
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2152396/Python3-Kahn's-algo
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: graph = [[] for _ in range(n)] indeg = [0]*n for u, v in edges: graph[u].append(v) indeg[v] += 1 ans = [set() for _ in range(n)] queue = deque([u for u in range(n) if not indeg[u]]) while queue: u = queue.popleft() for v in graph[u]: ans[v] |= ans[u] | {u} indeg[v] -= 1 if indeg[v] == 0: queue.append(v) return [sorted(x) for x in ans]
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[Python3] Kahn's algo
ye15
0
26
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,453
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1923587/Python3-or-Simple-DFS-from-Every-Node-O(N2)
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: self.ans=[[] for i in range(n)] adj=[[] for i in range(n)] hset=set([tuple(i) for i in edges]) for i,j in edges: adj[i].append(j) adj[j].append(i) self.vis=set() for i in range(n): self.vis=set() self.vis.add(i) self.dfs(i,i,adj,hset) return [sorted(i) for i in self.ans] def dfs(self,parent,currNode,adj,hset): for it in adj[currNode]: if (currNode,it) not in hset and it not in self.vis: self.vis.add(it) self.ans[parent].append(it) self.dfs(parent,it,adj,hset) else: continue return
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[Python3] | Simple DFS from Every Node O(N^2)
swapnilsingh421
0
52
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,454
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1830511/Dictionary-of-ancestors-76-speed
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: ancestors = defaultdict(set) for parent, child in edges: ancestors[child].add(parent) ans = [set() for _ in range(n)] for i in range(n): if i not in ancestors: continue level = ancestors[i] ans[i].update(level) while level: new_level = set() for parent in level: if parent < i: ans[i].update(ans[parent]) elif parent in ancestors: for grand_parent in ancestors[parent]: if grand_parent not in ans[i]: ans[i].add(grand_parent) new_level.add(grand_parent) level = new_level return [sorted(s) for s in ans]
all-ancestors-of-a-node-in-a-directed-acyclic-graph
Dictionary of ancestors, 76% speed
EvgenySH
0
52
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,455
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1822948/Python-3-DFS-and-Kahn's-algorithm
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: ans = [set() for _ in range(n)] g = defaultdict(set) deg = defaultdict(int) for u, v in edges: g[u].add(v) deg[v] += 1 def dfs(node, path): for nei in g[node]: ans[nei] |= path deg[nei] -= 1 if not deg[nei]: vis.add(nei) # ancestors include the node's ancestor and the node itself dfs(nei, path | ans[nei] | {nei}) # keep track of visited nodes vis = set() for i in range(n): if not deg[i]: if i in vis: continue vis.add(i) dfs(i, ans[i] | {i}) return [sorted(x) for x in ans]
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[Python 3] DFS and Kahn's algorithm
chestnut890123
0
65
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,456
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1822948/Python-3-DFS-and-Kahn's-algorithm
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: ans = [set() for _ in range(n)] g = defaultdict(set) deg = defaultdict(int) for u, v in edges: g[u].add(v) deg[v] += 1 starts = [i for i in range(n) if not deg[i]] def dfs(node, path): for nei in g[node]: ans[nei] |= path if not deg[nei]: continue deg[nei] -= 1 if not deg[nei]: # vis.add(nei) # ancestors include the node's ancestor and the node itself dfs(nei, path | ans[nei] | {nei}) # keep track of visited nodes # vis = set() for i in starts: if not deg[i]: # if i in vis: continue # vis.add(i) dfs(i, ans[i] | {i}) return [sorted(x) for x in ans]
all-ancestors-of-a-node-in-a-directed-acyclic-graph
[Python 3] DFS and Kahn's algorithm
chestnut890123
0
65
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,457
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1822353/Python-or-Easy-Understanding-or-DFS-and-caching
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: parents = defaultdict(set) for frm, to in edges: parents[to].add(frm) @cache def find_ancestor(n): if n not in parents: return set() res = set() for parent in parents[n]: res.add(parent) res |= find_ancestor(parent) return res ancestors = [] for i in range(n): ancestors.append(sorted(find_ancestor(i))) return ancestors
all-ancestors-of-a-node-in-a-directed-acyclic-graph
Python | Easy Understanding | DFS and caching
rbhandu
0
31
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,458
https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/1822304/python-hashmap-of-parents
class Solution: def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]: result = [] hashmap = collections.defaultdict(set) parent = collections.defaultdict(set) # indegree = collections.defaultdict(int) for a, b in edges: hashmap[a].add(b) parent[b].add(a) # indegree[b] += 1 roots = set() leafs = set() for node in range(n): if node not in parent: roots.add(node) if node not in hashmap: leafs.add(node) # print(roots) # print(leafs) # ancestors = collections.defaultdict(set) @cache def find_parent(node): parents = set() if node in parent: for p in parent[node]: parents.add(p) parents |= find_parent(p) return parents for node in range(n): result.append(sorted(list(find_parent(node)))) return result
all-ancestors-of-a-node-in-a-directed-acyclic-graph
python, hashmap of parents
emersonexus
0
39
all ancestors of a node in a directed acyclic graph
2,192
0.503
Medium
30,459
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2152484/Python3-peel-the-string
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: ans = 0 while len(s) > 2: lo = s.find(s[-1]) hi = s.rfind(s[0]) if lo < len(s)-hi-1: ans += lo s = s[:lo] + s[lo+1:-1] else: ans += len(s)-hi-1 s = s[1:hi] + s[hi+1:] return ans
minimum-number-of-moves-to-make-palindrome
[Python3] peel the string
ye15
1
614
minimum number of moves to make palindrome
2,193
0.514
Hard
30,460
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2812340/Python-%2B-2-pointers-%2B-Explanation.
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: # At each point, we look at the first and the last elements # if they are the same, then we skip them, else we find # another element in the string that matches the left # element and then we make the necessary swaps to move it # to the right place. # if we can't find that element -- this means this is the middle element # in the palindrome, we just move it one position to the right and continue # over the next few iterations, it will be moved to the center automatically # run it for string = "dpacacp", answer should be 4 # the character that should be in the middle is "d" l, r, res, st = 0, len(s)-1, 0, list(s) while l < r: if st[l] != st[r]: i = r while i > l and st[l] != st[i]: i -= 1 if i == l: st[i], st[i+1] = st[i+1], st[i] res += 1 continue else: while i < r: st[i], st[i+1] = st[i+1], st[i] i += 1 res += 1 l, r = l+1, r-1 return res
minimum-number-of-moves-to-make-palindrome
Python + 2 pointers + Explanation.
rasnouk
0
7
minimum number of moves to make palindrome
2,193
0.514
Hard
30,461
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2800512/Easy-to-Understand-2-Pointer-Solution
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: ''' Intuition: Start on the outer corners, moving in from left and right, and do min swaps to make them the same. Spacetime: O(n) Runtime: O(n^2) ''' i, j = 0, len(s) - 1 sArr = list(s) swaps = 0 while i < j: if sArr[i] != sArr[j]: minSwapsI = math.inf # min swaps needed to get i the same as position j minSwapsJ = math.inf # get min swaps needed to make pos i == pos j for k in range(i+1,j): if sArr[k] == sArr[j]: minSwapsI = k - i break # get min swaps needed to make pos j == pos i for k in range(j-1, i, -1): if sArr[k] == sArr[i]: minSwapsJ = j - k break # make min swaps needed if minSwapsI < minSwapsJ: for k in range(i + minSwapsI, i, -1): sArr[k-1], sArr[k] = sArr[k], sArr[k-1] else: for k in range(j - minSwapsJ, j): sArr[k+1], sArr[k] = sArr[k], sArr[k+1] swaps += min(minSwapsI, minSwapsJ) # update swap count # update pointers i += 1 j -= 1 return swaps
minimum-number-of-moves-to-make-palindrome
Easy to Understand 2-Pointer Solution
nickpavini
0
4
minimum number of moves to make palindrome
2,193
0.514
Hard
30,462
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2567960/Python-Greedy-2-pointer
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: s = list(s) #makes it easy for assignment op res = 0 left, right = 0, len(s) - 1 while left < right: l, r = left, right #find matching char while s[l] != s[r]: r -= 1 # if index dont match then swap if l != r: # swap one by one while r < right: s[r], s[r + 1] = s[r + 1], s[r] res += 1 r += 1 else: s[r], s[r + 1] = s[r + 1], s[r] res += 1 continue # get outside the main while loop left += 1 right -= 1 return res
minimum-number-of-moves-to-make-palindrome
Python Greedy 2 pointer
shubhamnishad25
0
222
minimum number of moves to make palindrome
2,193
0.514
Hard
30,463
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/1831236/Removing-pairs-70-speed
class Solution: def minMovesToMakePalindrome(self, s: str) -> int: ans = 0 def remove_edges(current: str) -> str: nonlocal ans left, right = dict(), dict() len_c1 = len(current) - 1 for i, c in enumerate(current): if c in right and i != right[c]: j = right[c] i, j = (i, j) if i < j else (j, i) ans += i + len_c1 - j return f"{current[:i]}{current[i + 1:j]}{current[j + 1:]}" elif c not in left: left[c] = i j = len_c1 - i right_c = current[j] if right_c in left and left[right_c] != j: i = left[right_c] i, j = (i, j) if i < j else (j, i) ans += i + len_c1 - j return f"{current[:i]}{current[i + 1:j]}{current[j + 1:]}" elif right_c not in right: right[right_c] = j return "" while len(s) > 2: s = remove_edges(s) return ans
minimum-number-of-moves-to-make-palindrome
Removing pairs, 70% speed
EvgenySH
0
240
minimum number of moves to make palindrome
2,193
0.514
Hard
30,464
https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/1826026/python-3%3A-basic-1000ms
class Solution: @lru_cache(None) def minMovesToMakePalindrome(self, s: str) -> int: n = len(s) if n<=1: return 0 if s[0] == s[-1]: return self.minMovesToMakePalindrome(s[1:-1]) i = 1 while s[i]!=s[-1]: i+=1 j = n - 2 while s[j]!=s[0]: j-=1 if i <= n - 1 - j: return i + self.minMovesToMakePalindrome(s[:i]+s[i+1:-1]) else: return n - 1 - j + self.minMovesToMakePalindrome(s[1:j]+s[j+1:])
minimum-number-of-moves-to-make-palindrome
python 3: basic 1000ms
akbc
0
133
minimum number of moves to make palindrome
2,193
0.514
Hard
30,465
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823607/Python3-1-line
class Solution: def cellsInRange(self, s: str) -> List[str]: return [chr(c)+str(r) for c in range(ord(s[0]), ord(s[3])+1) for r in range(int(s[1]), int(s[4])+1)]
cells-in-a-range-on-an-excel-sheet
[Python3] 1-line
ye15
7
368
cells in a range on an excel sheet
2,194
0.856
Easy
30,466
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2369701/Simple-Python3-or-NO-ord()-NO-chr()
class Solution: def cellsInRange(self, s: str) -> List[str]: start, end = s.split(':') start_letter, start_num = start[0], int(start[-1]) end_letter, end_num = end[0], int(end[1]) alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') alphabet_slice = \ alphabet[alphabet.index(start_letter):alphabet.index(end_letter) + 1] res = list() for el in alphabet_slice: res += [el + str(num) for num in range(start_num, end_num + 1)] return res
cells-in-a-range-on-an-excel-sheet
Simple Python3 | NO ord(), NO chr()
Sergei_Gusev
2
87
cells in a range on an excel sheet
2,194
0.856
Easy
30,467
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823610/Beginner-Friendly-Python-Solution
class Solution: def cellsInRange(self, s: str) -> List[str]: row1 = int(s[1]) row2 = int(s[4]) col1 = ord(s[0]) # To get their Unicode values col2 = ord(s[3]) # To get their Unicode values res = [] # Since we are asked to sort the answer list first column and then row wise. for i in range(col1, col2+1): for j in range(row1, row2+1): res.append(f"{chr(i)}{j}") # First column then row return res
cells-in-a-range-on-an-excel-sheet
Beginner Friendly Python Solution
anCoderr
2
187
cells in a range on an excel sheet
2,194
0.856
Easy
30,468
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823610/Beginner-Friendly-Python-Solution
class Solution: def cellsInRange(self, s: str) -> List[str]: return [f"{chr(i)}{j}" for i in range(ord(s[0]), ord(s[3])+1) for j in range(int(s[1]), int(s[4])+1)]
cells-in-a-range-on-an-excel-sheet
Beginner Friendly Python Solution
anCoderr
2
187
cells in a range on an excel sheet
2,194
0.856
Easy
30,469
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2823458/Simplest-Detailed-Approach-in-Python3
class Solution: def cellsInRange(self, s: str) -> List[str]: alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Rows r1 = int(s[1]) r2 = int(s[-1]) # Columns c1 = s[0] c2 = s[-2] op = [] for col in range(alpha.index(c1), alpha.index(c2)+1): for row in range(r1, r2+1): op.append(alpha[col] + str(row)) return op
cells-in-a-range-on-an-excel-sheet
Simplest Detailed Approach in Python3
kschaitanya2001
1
28
cells in a range on an excel sheet
2,194
0.856
Easy
30,470
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1944120/Python-dollarolution
class Solution: def cellsInRange(self, s: str) -> List[str]: v = [] for i in range(ord(s[0]),ord(s[3])+1): for j in range(int(s[1]),int(s[4])+1): v.append(chr(i)+str(j)) return v
cells-in-a-range-on-an-excel-sheet
Python $olution
AakRay
1
81
cells in a range on an excel sheet
2,194
0.856
Easy
30,471
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1937740/Python-Using-For-Loops-Faster-Than-94
class Solution: def cellsInRange(self, s: str) -> List[str]: res = [] for letter in range(ord(s[0]), ord(s[3]) + 1, 1): for i in range(int(s[1]), int(s[-1]) + 1): res.append(chr(letter) + str(i)) return res
cells-in-a-range-on-an-excel-sheet
Python Using For Loops, Faster Than 94%
Hejita
1
105
cells in a range on an excel sheet
2,194
0.856
Easy
30,472
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1868179/Python3-Simple-two-loops-O(n)-time-O(1)-space
class Solution: def cellsInRange(self, s: str) -> List[str]: alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] res = [] start = alphabet.index(s[0]) for i in range(start, len(alphabet)): j1 = int(s[1]) j2 = int(s[4]) for j in range(j1, j2+1): res.append("" + alphabet[i] + str(j)) if alphabet[i] == s[3]: break return res
cells-in-a-range-on-an-excel-sheet
[Python3] Simple two loops - O(n) time, O(1) space
hanelios
1
66
cells in a range on an excel sheet
2,194
0.856
Easy
30,473
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1856136/1-Line-Python-Solution-oror-80-Faster-oror-Memory-less-than-25
class Solution: def cellsInRange(self, s: str) -> List[str]: return [chr(i)+str(j) for i in range(ord(s[0]),ord(s[3])+1) for j in range(int(s[1]),int(s[4])+1)]
cells-in-a-range-on-an-excel-sheet
1-Line Python Solution || 80% Faster || Memory less than 25%
Taha-C
1
100
cells in a range on an excel sheet
2,194
0.856
Easy
30,474
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2839665/Python-Dynamic-Solution
class Solution: def cellsInRange(self, s: str) -> List[str]: alpha = ['A','B','C','D','E','F', 'G','H','I','J','K','L', 'M','N','O','P','Q','R', 'S','T','U','V','W','X', 'Y','Z'] r=0 end_num,start_num = int(s[-1]),int(s[1]) start_alpha, end_alpha= alpha.index(s[0]), alpha.index(s[-2]) res = [0]*((end_alpha-start_alpha+1)*(end_num-start_num +1)) for alp in range(start_alpha,end_alpha+1): for count in range(start_num,end_num+1): res[r] = alpha[alp]+str(count) r = r+1 return res
cells-in-a-range-on-an-excel-sheet
Python Dynamic Solution
ameenusyed09
0
1
cells in a range on an excel sheet
2,194
0.856
Easy
30,475
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2799364/simple-solution-in-python-3-lines-of-codes
class Solution: def cellsInRange(self, s: str) -> List[str]: minCol, maxCol = ord(s[0]), ord(s[3]) minRow, maxRow = int(s[1]), int(s[4]) return [chr(i)+str(j) for i in range(minCol, maxCol+1) for j in range(minRow, maxRow+1)]
cells-in-a-range-on-an-excel-sheet
simple solution in python, 3 lines of codes
chj2788
0
1
cells in a range on an excel sheet
2,194
0.856
Easy
30,476
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2690477/Python3-One-Liner-and-Readable-Solution
class Solution: def cellsInRange2(self, s: str) -> List[str]: result = [] for col in range(ord(s[0]), ord(s[3])+1): for row in range(int(s[1]), int(s[4])+1): result.append(f"{chr(col)}{row}") return result def cellsInRange(self, s: str) -> List[str]: return [f"{chr(col)}{row}" for col in range(ord(s[0]), ord(s[3])+1) for row in range(int(s[1]), int(s[4])+1)]
cells-in-a-range-on-an-excel-sheet
[Python3] - One-Liner and Readable Solution
Lucew
0
2
cells in a range on an excel sheet
2,194
0.856
Easy
30,477
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2685441/Python-solution-beats-98-uses-string-array-as-hashmap-(comments-and-explanation-incl.)
class Solution: def cellsInRange(self, s: str) -> List[str]: colmap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #Calculate number of rows and columns num_rows = abs(int(s[-1])-int(s[1])) + 1 num_cols = abs(ord(s[0]) - ord(s[-2])) + 1 print(num_rows) print(num_cols) res = [] #We know how many rows and columns exist. Now we calculate the starting point of the loop for row and column col_start = ord(s[0]) - ord(colmap[0]) row_start = int(s[1]) for col in range(col_start, col_start + num_cols): for row in range(row_start, row_start + num_rows): cell_name = colmap[col] + str(row) res.append(cell_name) return res
cells-in-a-range-on-an-excel-sheet
Python solution beats 98%, uses string array as hashmap (comments and explanation incl.)
cat_woman
0
1
cells in a range on an excel sheet
2,194
0.856
Easy
30,478
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2656057/easy-fast-straightforward-solution-in-Python
class Solution: def cellsInRange(self, s: str) -> List[str]: s1 =(s[:2]) s2= (s[3:]) endL = ord(s2[0]) startL = ord(s1[0]) start = int(s1[1]) end = int(s2[1]) res = [] for i in range(startL, endL+1): for j in range(start,end+1): res.append(str(chr(i)+ str(j))) return res
cells-in-a-range-on-an-excel-sheet
easy fast straightforward solution in Python
asamarka
0
1
cells in a range on an excel sheet
2,194
0.856
Easy
30,479
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2156816/Python-Solutions
class Solution: def cellsInRange(self, s: str) -> List[str]: return [f'{chr(i)}{j}' for i in range(ord(s[0]), ord(s[-2]) + 1) for j in range(int(s[1]), int(s[-1]) + 1)]
cells-in-a-range-on-an-excel-sheet
Python Solutions
hgalytoby
0
87
cells in a range on an excel sheet
2,194
0.856
Easy
30,480
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2156816/Python-Solutions
class Solution: def cellsInRange(self, s: str) -> List[str]: result = [] for i in range(ord(s[0]), ord(s[-2]) + 1): for j in range(int(s[1]), int(s[-1]) + 1): result.append(f'{chr(i)}{j}') return result
cells-in-a-range-on-an-excel-sheet
Python Solutions
hgalytoby
0
87
cells in a range on an excel sheet
2,194
0.856
Easy
30,481
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2044705/using-range-and-ordinals-to-obtain-cells
class Solution: def cellsInRange(self, s: str) -> List[str]: res = [] c1, c2, r1, r2 = s[0], s[3], s[1], s[4] for c in range(ord(c1), ord(c2) + 1): c = chr(c) for r in range(int(r1), int(r2) + 1): res.append(f"{c}{r}") return res
cells-in-a-range-on-an-excel-sheet
using range and ordinals to obtain cells
andrewnerdimo
0
52
cells in a range on an excel sheet
2,194
0.856
Easy
30,482
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2008379/Python-easy-solution-for-you!
class Solution: def cellsInRange(self, s: str) -> List[str]: from string import ascii_uppercase as au mi,ma = int(s[1]),int(s[4]) fl,ll = s[0],s[3] ans = [] for i in range(au.index(fl),au.index(ll)+1): for j in range(mi, ma+1): ans += [au[i]+str(j)] return ans
cells-in-a-range-on-an-excel-sheet
Python easy solution for you!
StikS32
0
144
cells in a range on an excel sheet
2,194
0.856
Easy
30,483
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/2000338/Python3-Ord-nested-loops-n**2
class Solution: def cellsInRange(self, s: str) -> List[str]: alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') ans = [] start_col, end_col = str.upper(s.split(':')[0][0]), str.upper(s.split(':')[1][0]) start_row, end_row = int(s.split(':')[0][1:]), int(s.split(':')[1][1:]) start_idx = ord(start_col) - ord('A') end_idx = ord(end_col) - ord('A') cur_row = start_row cur_col = start_idx while cur_col <= end_idx: while cur_row <= end_row: ans.append(f'{alphabet[cur_col]}{cur_row}') cur_row += 1 cur_row = start_row cur_col += 1 return ans
cells-in-a-range-on-an-excel-sheet
[Python3] - Ord, nested loops, n**2
patefon
0
29
cells in a range on an excel sheet
2,194
0.856
Easy
30,484
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1972042/Easiest-and-Simplest-Python-Solution-or-100-Faster-or-Nested-Loop-Implementation
class Solution: def cellsInRange(self, s: str) -> List[str]: first=s.split(":") temp=[] low=first[0][1] high=first[1][1] ele=0 diff=ord(first[1][0])-ord(first[0][0]) ele=ord(first[0][0]) for i in range(0,diff+1): while ele<=ord(first[1][0]): for j in range(int(low),int(high)+1): st=chr(ele) ss=st+str(j) temp.append(ss) ele+=1 return (temp)
cells-in-a-range-on-an-excel-sheet
Easiest & Simplest Python Solution | 100% Faster | Nested Loop Implementation
RatnaPriya
0
75
cells in a range on an excel sheet
2,194
0.856
Easy
30,485
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1928337/Python-3-One-Line-Solution
class Solution: def cellsInRange(self, s: str) -> List[str]: return [chr(c) + str(r) for c in range(ord(s[0]), ord(s[3]) + 1) for r in range(int(s[1]), int(s[4]) + 1)]
cells-in-a-range-on-an-excel-sheet
[Python 3] One-Line Solution
terrencetang
0
48
cells in a range on an excel sheet
2,194
0.856
Easy
30,486
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1924308/Python-Clean-and-Simple!
class Solution: def cellsInRange(self, s): out = [] # separate expression into two cells cell1, cell2 = s.split(":") # separate cols fom rows col1, row1 = cell1 col2, row2 = cell2 # append cells for col in range(ord(col1), ord(col2)+1): for row in range(int(row1), int(row2)+1): cell = chr(col) + str(row) out.append(cell) return out
cells-in-a-range-on-an-excel-sheet
Python - Clean and Simple!
domthedeveloper
0
50
cells in a range on an excel sheet
2,194
0.856
Easy
30,487
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1901180/Python3-simple-solution
class Solution: def cellsInRange(self, s: str) -> List[str]: a,b = s.split(':') a1,a2 = a[0],int(a[1]) b1,b2 = b[0],int(b[1]) l1 = [] ans = [] l2 = list(range(a2,b2+1)) for i in range(ord(a1.lower()),ord(b1.lower())+1): l1.append(chr(i).upper()) for i in l1: for j in l2: ans.append(i+str(j)) return ans
cells-in-a-range-on-an-excel-sheet
Python3 simple solution
EklavyaJoshi
0
26
cells in a range on an excel sheet
2,194
0.856
Easy
30,488
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1875025/Python3-Two-Loop-With-ASCII-Code
class Solution: def cellsInRange(self, s: str) -> List[str]: cell_s, cell_e = s.split(":") head_c = ord(cell_s[0]); tail_c = ord(cell_e[0]) head_r = int(cell_s[1]); tail_r = int(cell_e[1]) res = [] for c in range(head_c, tail_c+1): for r in range(head_r, tail_r+1): res.append(f"{chr(c)}{r}") return res
cells-in-a-range-on-an-excel-sheet
✔Python3 Two Loop With ASCII Code
khRay13
0
35
cells in a range on an excel sheet
2,194
0.856
Easy
30,489
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1856780/Python-easy-solution-using-ord()
class Solution: def cellsInRange(self, s: str) -> List[str]: res = [] for i in range(ord(s[0]), ord(s[3])+1): for j in range(int(s[1]), int(s[4])+1): res.append(str(chr(i))+str(j)) return res
cells-in-a-range-on-an-excel-sheet
Python easy solution using ord()
alishak1999
0
39
cells in a range on an excel sheet
2,194
0.856
Easy
30,490
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1856527/very-easy-understand-beginner-level-python-code
class Solution: def cellsInRange(self, s: str) -> List[str]: x = s.split(":") c = [] r = [] output = [] for i in range(ord(x[0][0]),(ord(x[1][0])+1)): c.append(chr(i)) for i in range(int(x[0][1]),(int(x[1][1])+1)): r.append(str(i)) for i in c: for j in r: output.append(i+j) return output
cells-in-a-range-on-an-excel-sheet
very easy understand beginner level python code
dakash682
0
29
cells in a range on an excel sheet
2,194
0.856
Easy
30,491
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1848921/Python-Simple-Solution
class Solution: def cellsInRange(self, s): res=[] for i in range(int(s[1]),int(s[4])+1): for j in range(int(ord(s[0])),int(ord(s[3])+1)): #conc=str(chr(j)) res.append(str(chr(j))+str(i)) return res
cells-in-a-range-on-an-excel-sheet
Python Simple Solution
sangam92
0
38
cells in a range on an excel sheet
2,194
0.856
Easy
30,492
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1846772/Python3-solution
class Solution: def cellsInRange(self, s: str) -> List[str]: letters = [] counter = int(s[1]) for x in range(ord(s[0]), ord(s[3])+1): if s[1] == s[4]: letters.append((chr(x))+ s[1]) elif s[1] < s[4]: temp = [chr(x)] * (int(s[4])-int(s[1])+1) if counter < 1: counter += 1 for x in temp: curr = x + str(counter) letters.append(curr) counter += 1 counter = int(s[1]) return letters
cells-in-a-range-on-an-excel-sheet
Python3 solution
zhivkob
0
32
cells in a range on an excel sheet
2,194
0.856
Easy
30,493
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1825413/Python
class Solution: def cellsInRange(self, s: str) -> List[str]: result = [] r_start, r_end = ord(s[1]), ord(s[4]) c_start, c_end = ord(s[0]), ord(s[3]) for c in range(c_start, c_end+1): for r in range(r_start, r_end+1): result.append(chr(c) + chr(r)) return result
cells-in-a-range-on-an-excel-sheet
Python
blue_sky5
0
63
cells in a range on an excel sheet
2,194
0.856
Easy
30,494
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1824640/Python3-Simple-Solution
class Solution: def cellsInRange(self, s: str) -> List[str]: arr = s.split(":") l_one,l_last,n_start,n_end = arr[0][0],arr[1][0],arr[0][1],arr[1][1] result = [] for i in range(ord(l_one),ord(l_last)+1): char = chr(i) for j in range(int(n_start),int(n_end)+1): result.append(char+str(j)) return result
cells-in-a-range-on-an-excel-sheet
[Python3] Simple Solution
abhijeetmallick29
0
14
cells in a range on an excel sheet
2,194
0.856
Easy
30,495
https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823668/Easy-to-understand-Python-solution
class Solution: def cellsInRange(self, s: str) -> List[str]: source, dest = s[0], s[3] upper_bound = max(int(s[1]), int(s[4])) start = int(s[1]) res = [] beg_cell = ord(source) while beg_cell <= ord(dest): for i in range(start, upper_bound + 1): res.append(chr(beg_cell) + str(i)) beg_cell += 1 return res
cells-in-a-range-on-an-excel-sheet
Easy to understand Python solution
prudentprogrammer
0
46
cells in a range on an excel sheet
2,194
0.856
Easy
30,496
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823628/Python3-swap
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: ans = k*(k+1)//2 prev = -inf for x in sorted(nums): if prev < x: if x <= k: k += 1 ans += k - x else: break prev = x return ans
append-k-integers-with-minimal-sum
[Python3] swap
ye15
10
495
append k integers with minimal sum
2,195
0.25
Medium
30,497
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823649/Python-Solution-using-AP-Sum-Explained
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: nums.sort() res = 0 nums.insert(0, 0) nums.append(2000000001) n = len(nums) for i in range(n-1): start = nums[i] # This is the lowerbound for current iteration end = nums[i+1] # This is the higherbound for current iteration if start == end: continue a = start + 1 # Starting value is lowerbound + 1 n = min(end - start - 1, k) # Since the total number possible b/w start and end might be more than the k numbers left, so always choose the minimum. v = (n*(2*a + n - 1))//2 # n/2[2a + (n-1)d] with d = 1 res += v # Add the sum of elements selected into res k -= n # n number of k's expired, thus k decrements return res
append-k-integers-with-minimal-sum
Python Solution using AP Sum Explained
anCoderr
8
716
append k integers with minimal sum
2,195
0.25
Medium
30,498
https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1824492/Python-Explanation-oror-sort-and-add
class Solution: def minimalKSum(self, nums: List[int], k: int) -> int: n=len(nums) curr=prev=0 # intialize both curr and prev nums.sort() # sort the nums sum=0 for i in range(n): curr=nums[i] # make curr equal to prev diff=curr-(prev+1) # find if there is any numbers in (prev,curr) if diff<=0: # if no then update prev and continue prev=curr continue if diff>k: # if yes then if number between (prev,curr) is more then k diff=k # then we will consider first k numbers only curr=prev+1+k # update curr to last number that we will add to use formula 1 of A.P. sum+=(diff*(curr+prev)//2) # formula 1 of A.P. prev=curr # update prev to curr k-=diff # update k if k==0: # if k is 0 then return break if k: # second case # we have finish nums but wnat to add more numbers sum+=(k*(2*prev+k+1)//2) # use formual 2 of A.P. we take d=1 return sum
append-k-integers-with-minimal-sum
Python Explanation || sort and add
rushi_javiya
6
177
append k integers with minimal sum
2,195
0.25
Medium
30,499