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/kth-smallest-element-in-a-sorted-matrix/discuss/2368206/GolangPython-O(N)-timeor-O(N)-space-Quick-Select
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: array = [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[0]))] return quickselect(array,k) def quickselect(array,k): middle = len(array)//2 middle_item = array[middle] left = [] right = [] for i,item in enumerate(array): if i == middle: continue if item < middle_item: left.append(item) else: right.append(item) if len(left)+1 == k: return middle_item elif len(left) >= k: return quickselect(left,k) else: return quickselect(right,k-len(left)-1)
kth-smallest-element-in-a-sorted-matrix
Golang/Python O(N) time| O(N) space Quick Select
vtalantsev
0
44
kth smallest element in a sorted matrix
378
0.616
Medium
6,500
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367833/378.-Stupid-215ms-Python3-in-place-sort
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: row0 = matrix[0] for i in range(1, len(matrix)): row0, matrix[i] = row0+matrix[i], [] row0.sort() return row0[k-1]
kth-smallest-element-in-a-sorted-matrix
378. Stupid 215ms Python3 in-place sort
leetavenger
0
3
kth smallest element in a sorted matrix
378
0.616
Medium
6,501
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367832/Python-Solution-or-One-Liner-or-99-Faster-or-Sorting-Based
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted([cell for row in matrix for cell in row])[k-1]
kth-smallest-element-in-a-sorted-matrix
Python Solution | One-Liner | 99% Faster | Sorting Based
Gautam_ProMax
0
14
kth smallest element in a sorted matrix
378
0.616
Medium
6,502
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367524/python-solution-99-faster
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: sus = [i for k in matrix for i in k] return sorted(sus)[k-1]
kth-smallest-element-in-a-sorted-matrix
python solution 99% faster
Noicelikeice
0
14
kth smallest element in a sorted matrix
378
0.616
Medium
6,503
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367493/Python-easy-solution-faster-than-95
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: one_dim_mat = [] for i in range(len(matrix)): one_dim_mat += matrix[i] return sorted(one_dim_mat)[k-1]
kth-smallest-element-in-a-sorted-matrix
Python easy solution faster than 95%
alishak1999
0
26
kth smallest element in a sorted matrix
378
0.616
Medium
6,504
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367396/Python-Simple-Python-Solution
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: result = [] for row in matrix: result = result + row result = sorted(result) return result[k - 1]
kth-smallest-element-in-a-sorted-matrix
[ Python ] ✅✅ Simple Python Solution 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
115
kth smallest element in a sorted matrix
378
0.616
Medium
6,505
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367117/2-lines-of-code-using-list-flatten-technique-and-sorting
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: mat = [j for i in matrix for j in i] mat.sort() return mat[k - 1]
kth-smallest-element-in-a-sorted-matrix
2 lines of code using list flatten technique and sorting
ankurbhambri
0
31
kth smallest element in a sorted matrix
378
0.616
Medium
6,506
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2367021/Python-1-Line-List-Comprehension-(beats-98.95)
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: return sorted([val for sublist in matrix for val in sublist])[k - 1]
kth-smallest-element-in-a-sorted-matrix
Python 1 Line List Comprehension (beats 98.95%)
Jonathanace
0
29
kth smallest element in a sorted matrix
378
0.616
Medium
6,507
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2318549/Short-solution-python
class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ sol=matrix[0] for i in matrix[1:]: sol+=i sol.sort() return sol[k-1]
kth-smallest-element-in-a-sorted-matrix
Short solution python
henryhe707
0
71
kth smallest element in a sorted matrix
378
0.616
Medium
6,508
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2193377/easy-python-solution-in-5-lines
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: ans = [] for i in matrix: ans += i ans = sorted(ans) return ans[k-1]
kth-smallest-element-in-a-sorted-matrix
easy python solution in 5 lines
rohansardar
0
89
kth smallest element in a sorted matrix
378
0.616
Medium
6,509
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2073052/Simple-Short-Python-Solution-Lists
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: N = len(matrix) for i in range(1, N): for j in range(N): matrix[0].append(matrix[i][j]) matrix[0].sort() return matrix[0][k-1]
kth-smallest-element-in-a-sorted-matrix
Simple Short Python Solution - Lists
kn_vardhan
0
79
kth smallest element in a sorted matrix
378
0.616
Medium
6,510
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2073052/Simple-Short-Python-Solution-Lists
class Solution: def kthSmallest(self, matrix: List[List[int]], k: int) -> int: values = [] for row in matrix: values += row values.sort() return values[k - 1]
kth-smallest-element-in-a-sorted-matrix
Simple Short Python Solution - Lists
kn_vardhan
0
79
kth smallest element in a sorted matrix
378
0.616
Medium
6,511
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/1971474/Python-oror-Easy-Solution-Using-Heap-oror-O(k*logk)
class Solution: import heapq def kthSmallest(self, matrix: List[List[int]], k: int) -> int: heap = [] for arr in matrix: heapq.heappush(heap,(arr[0],0,arr)) while k > 0 and heap: val,idx,arr = heapq.heappop(heap) ans = val if idx+1<len(arr): heapq.heappush(heap,(arr[idx+1],idx+1,arr)) k-=1 return ans
kth-smallest-element-in-a-sorted-matrix
Python || Easy Solution Using Heap || O(k*logk)
gamitejpratapsingh998
0
210
kth smallest element in a sorted matrix
378
0.616
Medium
6,512
https://leetcode.com/problems/linked-list-random-node/discuss/811617/Python3-reservoir-sampling
class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.head = head # store head of linked list def getRandom(self) -> int: """ Returns a random node's value. """ cnt = 0 node = self.head while node: cnt += 1 if randint(1, cnt) == cnt: ans = node.val # reservoir sampling node = node.next return ans
linked-list-random-node
[Python3] reservoir sampling
ye15
4
395
linked list random node
382
0.596
Medium
6,513
https://leetcode.com/problems/linked-list-random-node/discuss/811617/Python3-reservoir-sampling
class Solution: def __init__(self, head: ListNode): self.head = head # store head def getRandom(self) -> int: node = self.head n = 0 while node: if randint(0, n) == 0: ans = node.val n += 1 node = node.next return ans
linked-list-random-node
[Python3] reservoir sampling
ye15
4
395
linked list random node
382
0.596
Medium
6,514
https://leetcode.com/problems/linked-list-random-node/discuss/1672294/Python3-solution
class Solution: def __init__(self, head: Optional[ListNode]): # store nodes' value in an array self.array = [] curr = head while curr: self.array.append(curr.val) curr = curr.next def getRandom(self) -> int: num = int(random.random() * len(self.array)) return self.array[num]
linked-list-random-node
Python3 solution
Janetcxy
1
28
linked list random node
382
0.596
Medium
6,515
https://leetcode.com/problems/linked-list-random-node/discuss/1673785/Python-Intuition
class Solution: def __init__(self, head: Optional[ListNode]): self.nums = [] while head: self.nums.append(head.val) head = head.next def getRandom(self) -> int: return random.choice(self.nums)
linked-list-random-node
Python Intuition
princess_asante
0
26
linked list random node
382
0.596
Medium
6,516
https://leetcode.com/problems/linked-list-random-node/discuss/1338778/Python-code-Beats-96-in-time
class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.mylist=[] self.insert(head) def insert(self, head): while head: self.mylist.append(head.val) head=head.next def getRandom(self) -> int: """ Returns a random node's value. """ return random.choice(self.mylist)
linked-list-random-node
Python code, Beats 96% in time
prajwal_vs
0
89
linked list random node
382
0.596
Medium
6,517
https://leetcode.com/problems/linked-list-random-node/discuss/976242/4Sum-II-Python3-one-liner
class Solution: def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: return sum(xcount * cdcounts[-x] for cdcounts in [Counter(x+y for x in C for y in D)] for x, xcount in Counter(x+y for x in A for y in B).items() if -x in cdcounts)
linked-list-random-node
4Sum II Python3 one-liner
leetavenger
0
46
linked list random node
382
0.596
Medium
6,518
https://leetcode.com/problems/linked-list-random-node/discuss/957190/Python3-beats-98.-%22random.choice(-)%22.-Very-Easy
class Solution: def __init__(self, head: ListNode): """ @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. """ self.res = [] while head: self.res.append(head.val) head = head.next def getRandom(self) -> int: """ Returns a random node's value. """ return random.choice(self.res)
linked-list-random-node
[Python3] beats 98%. "random.choice( )". Very-Easy
tilak_
0
62
linked list random node
382
0.596
Medium
6,519
https://leetcode.com/problems/ransom-note/discuss/1346131/Easiest-python-solution-faster-than-95
class Solution: def canConstruct(self, ransomNote, magazine): for i in set(ransomNote): if magazine.count(i) < ransomNote.count(i): return False return True
ransom-note
Easiest python solution, faster than 95%
mqueue
35
3,500
ransom note
383
0.576
Easy
6,520
https://leetcode.com/problems/ransom-note/discuss/2500721/Very-Easy-oror-100-oror-Fully-Explained-oror-C%2B%2B-Java-Python-Python3
class Solution(object): def canConstruct(self, ransomNote, magazine): st1, st2 = Counter(ransomNote), Counter(magazine) if st1 &amp; st2 == st1: return True return False
ransom-note
Very Easy || 100% || Fully Explained || C++, Java, Python, Python3
PratikSen07
29
1,500
ransom note
383
0.576
Easy
6,521
https://leetcode.com/problems/ransom-note/discuss/2550434/Easy-and-Faster-than-98-python3-solutions
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: if len(magazine) < len(ransomNote): return False else: for ransomNote_char in set(ransomNote): if ransomNote.count(ransomNote_char) > magazine.count(ransomNote_char): return False return True
ransom-note
Easy and Faster than 98% python3 solutions
LucasHarim
9
302
ransom note
383
0.576
Easy
6,522
https://leetcode.com/problems/ransom-note/discuss/2359975/Python-One-Line-Solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: return Counter(ransomNote)-Counter(magazine)=={}
ransom-note
Python One Line Solution
dhruva3223
6
428
ransom note
383
0.576
Easy
6,523
https://leetcode.com/problems/ransom-note/discuss/1718553/Python-simple-solution-6-lines
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: dict1=collections.Counter(ransomNote) dict2=collections.Counter(magazine) for key in dict1: if key not in dict2 or dict2[key]<dict1[key]: return False return True
ransom-note
Python simple solution 6 lines
amannarayansingh10
5
459
ransom note
383
0.576
Easy
6,524
https://leetcode.com/problems/ransom-note/discuss/2671667/Python-solution.-Clean-code-with-full-comments-93.55-space
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: dict_1 = from_str_to_dict(ransomNote) dict_2 = from_str_to_dict(magazine) return check_compatibility(dict_1, dict_2) # Define helper method that checks if to dictionaries have keys in common, and # if the ransomNote needs more letters then what the magazine can provide. def check_compatibility(dict_1, dict_2): # Check for common keys. for key in list(dict_1.keys()): if not key in dict_2: return False # Check for valid quantity. if dict_1[key] > dict_2[key]: return False return True # Convert a string into a dictionary. def from_str_to_dict(string: str): dic = {} for i in string: if i in dic: dic[i] += 1 else: dic[i] = 1 return dic # Runtime: 134 ms, faster than 24.02% of Python3 online submissions for Ransom Note. # Memory Usage: 14.1 MB, less than 93.55% of Python3 online submissions for Ransom Note. # If you like my work and found it helpful, then I'll appreciate a like. Thanks!
ransom-note
Python solution. Clean code with full comments 93.55% space
375d
4
191
ransom note
383
0.576
Easy
6,525
https://leetcode.com/problems/ransom-note/discuss/2480010/Python3-95.20-O(N)-Solution-or-Beginner-Friendly
class Solution: def canConstruct(self, a: str, b: str) -> bool: letter = [0 for _ in range(26)] for c in b: letter[ord(c) - 97] += 1 for c in a: letter[ord(c) - 97] -= 1 return not any((i < 0 for i in letter))
ransom-note
Python3 95.20% O(N) Solution | Beginner Friendly
doneowth
3
88
ransom note
383
0.576
Easy
6,526
https://leetcode.com/problems/ransom-note/discuss/2270590/Simple-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: if len(magazine) < len(ransomNote): return False for letter in ransomNote: if(letter not in magazine): return False magazine = magazine.replace(letter,'',1) return True
ransom-note
Simple solution
jivanbasurtom
3
126
ransom note
383
0.576
Easy
6,527
https://leetcode.com/problems/ransom-note/discuss/1977169/Python3-Solution
class Solution(object): def canConstruct(self, ransomNote, magazine): for i in set(ransomNote): if ransomNote.count(i) > magazine.count(i): return False return True
ransom-note
Python3 Solution
nomanaasif9
3
211
ransom note
383
0.576
Easy
6,528
https://leetcode.com/problems/ransom-note/discuss/610555/Python3-Simple-Solution-Beats-99.5
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for l in ransomNote: if l not in magazine: return False magazine = magazine.replace(l, '', 1) return True
ransom-note
[Python3] Simple Solution Beats 99.5%
naraB
3
419
ransom note
383
0.576
Easy
6,529
https://leetcode.com/problems/ransom-note/discuss/2594211/Python-simple-solution-or-no-hashtable-or-beats-98.63-in-runtime
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: out = False for elem in ransomNote: if elem in magazine: out = True magazine = magazine.replace(elem,'',1) else: out = False return out return out
ransom-note
Python simple solution | no hashtable | beats 98.63% in runtime
shwetachandole
2
147
ransom note
383
0.576
Easy
6,530
https://leetcode.com/problems/ransom-note/discuss/2585361/Python-99.5-Faster.-Simple-Solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: #iterate the unqiue letter in ransom note for i in set(ransomNote): #check if the letter count in magazine is less than ransom note if magazine.count(i) < ransomNote.count(i): return(False) return(True)
ransom-note
Python 99.5% Faster. Simple Solution
ovidaure
2
213
ransom note
383
0.576
Easy
6,531
https://leetcode.com/problems/ransom-note/discuss/1825705/Python-3-or-99.60-Faster-or-Easy-to-understand-or-Six-lines-of-code
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: c = 0 for i in ransomNote: if i in magazine: magazine = magazine.replace(i,"",1) c += 1 return c == len(ransomNote)
ransom-note
✔Python 3 | 99.60% Faster | Easy to understand | Six lines of code
Coding_Tan3
2
182
ransom note
383
0.576
Easy
6,532
https://leetcode.com/problems/ransom-note/discuss/1433367/python-3-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: r=sorted(list(ransomNote)) m=sorted(list(magazine)) for char in m: if r and char==r[0]: r.pop(0) if r: return False else: return True ```
ransom-note
python 3 solution
abhi_n_001
2
207
ransom note
383
0.576
Easy
6,533
https://leetcode.com/problems/ransom-note/discuss/1266898/Easy-Python-Solution(94.14)
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: x=Counter(ransomNote) y=Counter(magazine) for i,v in x.items(): if(x[i]<=y[i]): continue else: return False return True
ransom-note
Easy Python Solution(94.14%)
Sneh17029
2
758
ransom note
383
0.576
Easy
6,534
https://leetcode.com/problems/ransom-note/discuss/2480474/Python-1-line-%2B-Set-%2B-Brute-Force-or-Detailed-explanation-or-Easy-understand-or-Detailed
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for i in set(ransomNote): if ransomNote.count(i) > magazine.count(i): return False return True
ransom-note
✅ Python 1 line + Set + Brute Force | Detailed explanation | Easy understand | Detailed
sezanhaque
1
20
ransom note
383
0.576
Easy
6,535
https://leetcode.com/problems/ransom-note/discuss/2480474/Python-1-line-%2B-Set-%2B-Brute-Force-or-Detailed-explanation-or-Easy-understand-or-Detailed
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: magazine_dict, ransomNote_dict = {}, {} for letter in magazine: if letter in magazine_dict: magazine_dict[letter] += 1 else: magazine_dict[letter] = 1 for letter in ransomNote: if letter in ransomNote_dict: ransomNote_dict[letter] += 1 else: ransomNote_dict[letter] = 1 for letter in ransomNote_dict: if letter not in magazine_dict: return False if ransomNote_dict[letter] > magazine_dict[letter]: return False return True
ransom-note
✅ Python 1 line + Set + Brute Force | Detailed explanation | Easy understand | Detailed
sezanhaque
1
20
ransom note
383
0.576
Easy
6,536
https://leetcode.com/problems/ransom-note/discuss/2418464/Low-time-complexity-approach
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: res = True # use set() to get unique characters in string for uniqueChar in set(ransomNote): if ransomNote.count(uniqueChar) <= magazine.count(uniqueChar): pass else: res = False return res
ransom-note
Low time complexity approach
Wok2882
1
79
ransom note
383
0.576
Easy
6,537
https://leetcode.com/problems/ransom-note/discuss/2366128/Python-Short-Faster-Solution-using-str.replace()-oror-Documented
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for c in ransomNote: # if letter not in magazine, return True if c not in magazine: return False else: # remove first occurrence of letter magazine = magazine.replace(c,'',1) return True
ransom-note
[Python] Short Faster Solution using str.replace() || Documented
Buntynara
1
66
ransom note
383
0.576
Easy
6,538
https://leetcode.com/problems/ransom-note/discuss/2327790/Python-Simple-Solution-oror-2-Dicts-or-HashMaps-oror-Explained
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: dictRansom = {} dictMagazine = {} # construct dictionary with initial value of 0 for all letters for c in 'abcdefghijklmnopqrstuvwxyz': dictRansom[c] = 0; dictMagazine[c] = 0 # increase count for each letter for v in ransomNote: dictRansom[v] += 1 for v in magazine: dictMagazine[v] += 1 # if any letter-count in ransome is greater than on in magazine, return False for k, v in dictRansom.items(): if v > dictMagazine[k]: return False # all counts in limit return True
ransom-note
[Python] Simple Solution || 2 Dicts or HashMaps || Explained
Buntynara
1
89
ransom note
383
0.576
Easy
6,539
https://leetcode.com/problems/ransom-note/discuss/2282408/Python3-or-O(n)-with-list
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: letters = [0]*26 for letter in list(ransomNote): letters[ord(letter)-ord('a')] += 1 for letter in list(magazine): if letters[ord(letter)-ord('a')] > 0: letters[ord(letter)-ord('a')] -= 1 check = [0]*26 return check == letters
ransom-note
Python3 | O(n) with list
muradbay
1
90
ransom note
383
0.576
Easy
6,540
https://leetcode.com/problems/ransom-note/discuss/2254814/Python-Easy-and-Short-Solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for i in set(ransomNote): if i not in magazine or ransomNote.count(i) > magazine.count(i): return False return True
ransom-note
Python Easy & Short Solution
Skiper228
1
87
ransom note
383
0.576
Easy
6,541
https://leetcode.com/problems/ransom-note/discuss/2187284/Python-FAST-and-Simple-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for i in ransomNote: if i in magazine: magazine = magazine.replace(i, '', 1) else: return False return True
ransom-note
Python FAST and Simple solution
ingli
1
78
ransom note
383
0.576
Easy
6,542
https://leetcode.com/problems/ransom-note/discuss/2019703/Python3-Solution-with-using-counting
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: c = collections.Counter(magazine) for char in ransomNote: if c[char] == 0: return False c[char] -= 1 return True
ransom-note
[Python3] Solution with using counting
maosipov11
1
81
ransom note
383
0.576
Easy
6,543
https://leetcode.com/problems/ransom-note/discuss/1825041/2-Lines-Python-Solution-oror-75-Faster-oror-Memory-less-than-75
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: if Counter(ransomNote) <= Counter(magazine): return True return False
ransom-note
2-Lines Python Solution || 75% Faster || Memory less than 75%
Taha-C
1
55
ransom note
383
0.576
Easy
6,544
https://leetcode.com/problems/ransom-note/discuss/1793445/Python-Simple-Python-Solution-With-Two-Approach
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: t=list(dict.fromkeys(ransomNote)) s=0 for i in t: if ransomNote.count(i)<=magazine.count(i): s=s+1 if s==len(t): return True else: return False
ransom-note
[ Python ] ✅✅ Simple Python Solution With Two Approach 🔥✌🥳👍
ASHOK_KUMAR_MEGHVANSHI
1
205
ransom note
383
0.576
Easy
6,545
https://leetcode.com/problems/ransom-note/discuss/1793445/Python-Simple-Python-Solution-With-Two-Approach
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: frequecy_r = {} for i in range(len(ransomNote)): if ransomNote[i] not in frequecy_r: frequecy_r[ransomNote[i]] = 1 else: frequecy_r[ransomNote[i]] = frequecy_r[ransomNote[i]] + 1 frequecy_m = {} for i in range(len(magazine)): if magazine[i] not in frequecy_m: frequecy_m[magazine[i]] = 1 else: frequecy_m[magazine[i]] = frequecy_m[magazine[i]] + 1 for i in ransomNote: if i not in frequecy_m: return False else: if frequecy_m[i] < frequecy_r[i]: return False return True
ransom-note
[ Python ] ✅✅ Simple Python Solution With Two Approach 🔥✌🥳👍
ASHOK_KUMAR_MEGHVANSHI
1
205
ransom note
383
0.576
Easy
6,546
https://leetcode.com/problems/ransom-note/discuss/1779868/Python-Easy-Step-by-Step-Solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: char_dict = {} for char in magazine: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 for char in ransomNote: if not char in char_dict or char_dict[char] == 0: return False else: char_dict[char] -= 1 return True
ransom-note
Python Easy Step by Step Solution
EnergyBoy
1
36
ransom note
383
0.576
Easy
6,547
https://leetcode.com/problems/ransom-note/discuss/1640283/Python3-super-easy-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: a = collections.Counter(ransomNote) b = collections.Counter(magazine) x = a - b return len(x) == 0
ransom-note
Python3 super easy solution
freakleesin
1
91
ransom note
383
0.576
Easy
6,548
https://leetcode.com/problems/ransom-note/discuss/1532796/WEEB-DOES-PYTHON
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: Note = Counter(ransomNote) Maga = Counter(magazine) for char in Note: if char not in Maga or Maga[char] < Note[char]: return False return True
ransom-note
WEEB DOES PYTHON
Skywalker5423
1
145
ransom note
383
0.576
Easy
6,549
https://leetcode.com/problems/ransom-note/discuss/353415/Solution-in-Python-3-(beats-~97)-(one-line)
class Solution: def canConstruct(self, r: str, m: str) -> bool: return not any(r.count(i) > m.count(i) for i in set(r)) - Junaid Mansuri (LeetCode ID)@hotmail.com
ransom-note
Solution in Python 3 (beats ~97%) (one line)
junaidmansuri
1
501
ransom note
383
0.576
Easy
6,550
https://leetcode.com/problems/ransom-note/discuss/2847994/Py-Hash-O(N)
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: dic_magazine = Counter(magazine) for char in ransomNote: dic_magazine[char] -= 1 if dic_magazine[char] < 0: return False return True
ransom-note
Py Hash O(N)
haly-leshchuk
0
2
ransom note
383
0.576
Easy
6,551
https://leetcode.com/problems/ransom-note/discuss/2839499/Python-using-Counter
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: r = Counter(ransomNote) m = Counter(magazine) for k in r.keys(): if r[k] > m.get(k,0): return False return True
ransom-note
Python using Counter
ajayedupuganti18
0
2
ransom note
383
0.576
Easy
6,552
https://leetcode.com/problems/ransom-note/discuss/2827103/python-easy-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: count = 0 for i in range(len(ransomNote)): if ransomNote[i] in magazine: magazine = magazine.replace(ransomNote[i], "", 1) count += 1 return count == len(ransomNote)
ransom-note
python easy solution
skywonder
0
6
ransom note
383
0.576
Easy
6,553
https://leetcode.com/problems/ransom-note/discuss/2818292/Using-dicts-and-list-of-flags
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: ransom_dict = {} magazine_dict = {} flags = [] for i in ransomNote: if i in ransom_dict: ransom_dict[i] += 1 continue ransom_dict[i] = 1 for i in magazine: if i in magazine_dict: magazine_dict[i] += 1 continue magazine_dict[i] = 1 for symbol in ransom_dict.keys(): if symbol not in magazine_dict.keys(): return False elif magazine_dict[symbol] >= ransom_dict[symbol]: flags.append(1) else: flags.append(0) for i in flags: if i != 1: return False return True
ransom-note
Using dicts and list of flags
pkozhem
0
4
ransom note
383
0.576
Easy
6,554
https://leetcode.com/problems/ransom-note/discuss/2814520/simple-python-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for x in list(ransomNote): if x not in list(magazine): return False for x in list(ransomNote): if list(ransomNote).count(x)>list(magazine).count(x): return False return True
ransom-note
simple python solution
sahityasetu1996
0
3
ransom note
383
0.576
Easy
6,555
https://leetcode.com/problems/ransom-note/discuss/2811939/Dictionary-count
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: letters = Counter(magazine) for letter in ransomNote: if letters[letter] == 0: return False letters[letter] -= 1 return True
ransom-note
Dictionary count
bourgeoibee
0
3
ransom note
383
0.576
Easy
6,556
https://leetcode.com/problems/ransom-note/discuss/2808000/Python-solutions-for-Ransom-Note
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: magazine_lettera = {i:magazine.count(i) for i in set(magazine)} for letter in ransomNote: if letter not in magazine_lettera.keys(): return False else: magazine_lettera[letter] -= 1 if magazine_lettera[letter] <= 0: magazine_lettera.pop(letter) return True
ransom-note
Python solutions for Ransom Note
Bassel_Alf
0
3
ransom note
383
0.576
Easy
6,557
https://leetcode.com/problems/ransom-note/discuss/2808000/Python-solutions-for-Ransom-Note
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: magazine_lettera = dict() for letter in magazine: magazine_lettera[letter] = magazine_lettera.get(letter, 0) + 1 for letter in ransomNote: if letter not in magazine_lettera.keys(): return False else: magazine_lettera[letter] -= 1 if magazine_lettera[letter] <= 0: magazine_lettera.pop(letter) return True
ransom-note
Python solutions for Ransom Note
Bassel_Alf
0
3
ransom note
383
0.576
Easy
6,558
https://leetcode.com/problems/ransom-note/discuss/2804911/Python-(runtime-98.31-memory-93.97)-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: originalMagazineLength = len(magazine) for c in ransomNote: magazine = magazine.replace(c, '', 1) return len(magazine) == originalMagazineLength - len(ransomNote)
ransom-note
Python (runtime 98.31%, memory 93.97%) solution
huseyinkeles
0
3
ransom note
383
0.576
Easy
6,559
https://leetcode.com/problems/ransom-note/discuss/2799026/PYTHON-Easy-Solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: a=Counter(ransomNote) #count the occurance of char of ransomnote b=Counter(magazine) #count the occurance of char of magazine if a &amp; b ==a: return True return False
ransom-note
[PYTHON] Easy Solution
user9516zM
0
1
ransom note
383
0.576
Easy
6,560
https://leetcode.com/problems/ransom-note/discuss/2797474/Python-solution-using-Counter-(short-and-simple)
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: counter_ransomNote = Counter(ransomNote) counter_magazine = Counter(magazine) for char in counter_ransomNote.keys(): if counter_ransomNote[char] > counter_magazine[char]: return False return True
ransom-note
Python solution using Counter (short and simple)
hungqpham
0
3
ransom note
383
0.576
Easy
6,561
https://leetcode.com/problems/ransom-note/discuss/2779474/Very-easy-solution-without-any-additional-method-but-beats-89.77
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: for char in ransomNote: char_found = False for i in range(len(magazine)): if char == magazine[i]: magazine = magazine[:i] + magazine[i+1:] char_found = True break if char_found == False: return False return True
ransom-note
Very easy solution without any additional method but beats 89.77%
sdsahil12
0
4
ransom note
383
0.576
Easy
6,562
https://leetcode.com/problems/ransom-note/discuss/2777466/Ransome-note-or-Easy
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: ransomNote = list(ransomNote) tracker = list(set(ransomNote)) magazine = list(magazine) while tracker: if tracker and ransomNote.count(tracker[0]) <= magazine.count(tracker[0]): tracker.remove(tracker[0]) else: return False return True
ransom-note
Ransome note | Easy
Gangajyoti
0
1
ransom note
383
0.576
Easy
6,563
https://leetcode.com/problems/ransom-note/discuss/2774991/Python-1-pointer
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: p_m = 0 note, mag = sorted(ransomNote), sorted(magazine) while p_m < len(magazine) and note[0] != mag[p_m]: p_m += 1 while len(note) and p_m < len(magazine): if note[0] == mag[p_m]: del note[0] p_m += 1 return not len(note)
ransom-note
Python, 1 pointer
Gagampy
0
5
ransom note
383
0.576
Easy
6,564
https://leetcode.com/problems/ransom-note/discuss/2768180/383.-Ransom-Note-or-Python
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: count = {} for c in magazine: count[c] = 1 + count.get(c,0) for ch in ransomNote: if ch not in count or count[ch]==0: return False else: count[ch]-=1 return True
ransom-note
383. Ransom Note | Python
rishabh_055
0
8
ransom note
383
0.576
Easy
6,565
https://leetcode.com/problems/ransom-note/discuss/2764531/Python3-oror-simple-solution-oror-easy-understanding
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: new = list(magazine) for r in ransomNote: if r not in new: return False i = new.index(r) new.remove(new[i]) return True
ransom-note
Python3 || simple solution || easy understanding
amangupta3073
0
2
ransom note
383
0.576
Easy
6,566
https://leetcode.com/problems/ransom-note/discuss/2750639/Easiest-solution-with-python-two-dictionaries-one-comparison
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: have = dict() for letter in magazine: have[letter] = have.get(letter,0) + 1 needed = dict() for letter in ransomNote: needed[letter] = needed.get(letter,0) + 1 total = 0 for key, value in needed.items(): total += max(value - have.get(key, 0),0) if total >0: return False return True
ransom-note
Easiest solution with python - two dictionaries one comparison
DavidCastillo
0
3
ransom note
383
0.576
Easy
6,567
https://leetcode.com/problems/ransom-note/discuss/2748373/Easy-python3-Counter-solution
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: note_freq = collections.Counter(ransomNote) mag_freq = collections.Counter(magazine) for letter in note_freq: if note_freq[letter] > mag_freq[letter]: return False return True
ransom-note
Easy python3 Counter solution
Delacrua
0
4
ransom note
383
0.576
Easy
6,568
https://leetcode.com/problems/shuffle-an-array/discuss/1673643/Python-or-Best-Optimal-Approach
class Solution: def __init__(self, nums: List[int]): self.arr = nums[:] # Deep Copy, Can also use Shallow Copy concept! # self.arr = nums # Shallow Copy would be something like this! def reset(self) -> List[int]: return self.arr def shuffle(self) -> List[int]: ans = self.arr[:] for i in range(len(ans)): swp_num = random.randrange(i, len(ans)) # Fisher-Yates Algorithm ans[i], ans[swp_num] = ans[swp_num], ans[i] return ans
shuffle-an-array
{ Python } | Best Optimal Approach ✔
leet_satyam
6
725
shuffle an array
384
0.577
Medium
6,569
https://leetcode.com/problems/shuffle-an-array/discuss/1354489/Partition-Array-into-Disjoint-Intervals-Python-Easy-solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: a = list(accumulate(nums, max)) b = list(accumulate(nums[::-1], min))[::-1] for i in range(1, len(nums)): if a[i-1] <= b[i]: return i
shuffle-an-array
Partition Array into Disjoint Intervals , Python , Easy solution
user8744WJ
1
120
shuffle an array
384
0.577
Medium
6,570
https://leetcode.com/problems/shuffle-an-array/discuss/1354450/Partition-Array-into-Disjoint-Intervals%3A-Simple-Python-Solution
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: n = len(nums) left_length = 1 left_max = curr_max = nums[0] for i in range(1, n-1): if nums[i] < left_max: left_length = i+1 left_max = curr_max else: curr_max = max(curr_max, nums[i]) return left_length
shuffle-an-array
Partition Array into Disjoint Intervals: Simple Python Solution
user6820GC
1
81
shuffle an array
384
0.577
Medium
6,571
https://leetcode.com/problems/shuffle-an-array/discuss/1350083/Shuffle-An-Array-Python-Easy-Solution
class Solution: def __init__(self, nums: List[int]): self.a = nums def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """ return list(self.a) def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ x = list(self.a) ans= [] while x: i = random.randint(0,len(x)-1) x[i],x[-1] = x[-1],x[i] ans.append(x.pop()) return ans # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
shuffle-an-array
Shuffle An Array , Python , Easy Solution
user8744WJ
1
144
shuffle an array
384
0.577
Medium
6,572
https://leetcode.com/problems/shuffle-an-array/discuss/1103904/Python-A-simple-O(N)-solution-that-is-NOT-Fisher-Yates-Algorithm
class Solution: def __init__(self, nums: List[int]): self.original = nums[:] self.nums = nums def reset(self) -> List[int]: return self.original def shuffle(self) -> List[int]: tmp = list(self.nums) # make a copy self.nums = [] while tmp: index = random.randint(0, len(tmp) - 1) # get random index tmp[-1], tmp[index] = tmp[index], tmp[-1] # switch places self.nums.append(tmp.pop()) # pop the last index return self.nums
shuffle-an-array
[Python] A simple O(N) solution that is NOT Fisher-Yates Algorithm
JummyEgg
1
390
shuffle an array
384
0.577
Medium
6,573
https://leetcode.com/problems/shuffle-an-array/discuss/2726092/Python-oror-Fisher-Yates-algorithm
class Solution: def __init__(self, nums: List[int]): self.nums = nums def reset(self) -> List[int]: return self.nums def shuffle(self) -> List[int]: # fisher yates shuffle copy = self.nums[:] m = len(self.nums) # while there remain elements to shuffle while(m): i = random.randint(0,m-1) # pick a random element from the remaining elements m-=1 copy[i],copy[m]=copy[m],copy[i] # swap current and random element return copy
shuffle-an-array
Python || Fisher-Yates algorithm
Graviel77
0
12
shuffle an array
384
0.577
Medium
6,574
https://leetcode.com/problems/shuffle-an-array/discuss/2710888/EXTREMELY-SIMPLE-and-EFFICIENT-python-solution
class Solution: def __init__(self, nums: List[int]): # "Contruct" the object: # Init the class variable(s) self.nums = nums def reset(self) -> List[int]: # Return the inital variable(s) # This assumes the variable(s) didn't change! return self.nums def shuffle(self) -> List[int]: # Pick a random index from the list &amp; add # it to a new list. Remove that item, then loop. # DON'T MODIFY THE ORIGINAL LIST! nums = [] temp = self.nums.copy() while True: length = len(temp) - 1 if length == -1: return nums index = random.randint(0, length) nums.append(temp[index]) temp.pop(index) # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
shuffle-an-array
EXTREMELY SIMPLE & EFFICIENT python solution
rosey003
0
7
shuffle an array
384
0.577
Medium
6,575
https://leetcode.com/problems/shuffle-an-array/discuss/2667750/FisherYates-shuffle
class Solution: def __init__(self, nums: List[int]): self.orig = list(nums) self.perm = nums def reset(self) -> List[int]: self.perm = list(self.orig) return self.perm def shuffle(self) -> List[int]: for i in range(0, len(self.perm)): j = randint(i, len(self.perm)-1) self.perm[i], self.perm[j] = self.perm[j], self.perm[i] return self.perm
shuffle-an-array
Fisher–Yates shuffle
tomfran
0
5
shuffle an array
384
0.577
Medium
6,576
https://leetcode.com/problems/shuffle-an-array/discuss/2652958/Python-and-Golang
class Solution: def __init__(self, nums: List[int]): self.nums = nums def reset(self) -> List[int]: return self.nums def shuffle(self) -> List[int]: import random return random.sample(self.nums, k=len(self.nums))
shuffle-an-array
Python and Golang答え
namashin
0
15
shuffle an array
384
0.577
Medium
6,577
https://leetcode.com/problems/shuffle-an-array/discuss/1819524/Python3-Solution-with-using-FisherYates-shuffle
class Solution: def __init__(self, nums: List[int]): self.arr = nums self.nums = nums[:] def reset(self) -> List[int]: self.arr = self.nums self.nums = self.nums[:] return self.arr def shuffle(self) -> List[int]: for i in range(len(self.arr)): rand_idx = random.randrange(i, len(self.arr)) self.arr[i], self.arr[rand_idx] = self.arr[rand_idx], self.arr[i] return self.arr
shuffle-an-array
[Python3] Solution with using Fisher–Yates shuffle
maosipov11
0
89
shuffle an array
384
0.577
Medium
6,578
https://leetcode.com/problems/shuffle-an-array/discuss/1813908/Python-solution-backtracking-and-shuffle
class Solution: def __init__(self, nums: List[int]): self.nums=nums self.lists=self.getList() def reset(self) -> List[int]: a=sorted(self.nums) return a def getList(self): nums=self.nums res=[] path=[] used=[0]*len(nums) def backtracking(nums): if len(path)==len(nums): res.append(path[:]) return for i in range(len(nums)): if used[i]==0: if i>0 and nums[i]==nums[i-1] and used[i-1]==0: continue used[i]=1 path.append(nums[i]) backtracking(nums) used[i]=0 path.pop() return res backtracking(nums) return res def shuffle(self) -> List[int]: n=random.randint(0,len(self.nums)-1) return self.lists[n]
shuffle-an-array
Python solution backtracking and shuffle
FangyuanXie
0
58
shuffle an array
384
0.577
Medium
6,579
https://leetcode.com/problems/shuffle-an-array/discuss/1813908/Python-solution-backtracking-and-shuffle
class Solution: def __init__(self, nums: List[int]): self.nums=nums self.orgin=nums[:] def reset(self) -> List[int]: self.nums=self.orgin[:] return self.nums def shuffle(self) -> List[int]: n=len(self.nums) for l in range(n): r=random.randint(l,n-1) self.nums[l],self.nums[r]=self.nums[r],self.nums[l] return self.nums
shuffle-an-array
Python solution backtracking and shuffle
FangyuanXie
0
58
shuffle an array
384
0.577
Medium
6,580
https://leetcode.com/problems/shuffle-an-array/discuss/1374919/Trapping-Rainwater-Python3-O(n)
class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 def addwater(range_): mx, out = 0, 0 for i in range_: if height[i] > mx: mx = height[i] else: out += mx - height[i] return out #Get midpoint mid = height.index(max(height)) #Add up all water values at each height left of mid left = addwater(range(mid)) #Add up all water value at each height right of mid right = addwater(range(len(height)-1, mid, -1)) return left + right
shuffle-an-array
Trapping Rainwater [Python3] O(n)
vscala
0
75
shuffle an array
384
0.577
Medium
6,581
https://leetcode.com/problems/shuffle-an-array/discuss/1374919/Trapping-Rainwater-Python3-O(n)
class Solution: def trap(self, height: List[int]) -> int: if len(height) < 3: return 0 l, r = 0, len(height)-1 lmax, rmax = height[l], height[r] out = 0 while l+1 != r: if lmax < rmax: l += 1 if height[l] > lmax: lmax = height[l] else: out += lmax - height[l] else: r -= 1 if height[r] > rmax: rmax = height[r] else: out += rmax - height[r] return out
shuffle-an-array
Trapping Rainwater [Python3] O(n)
vscala
0
75
shuffle an array
384
0.577
Medium
6,582
https://leetcode.com/problems/shuffle-an-array/discuss/1350445/Shuffle-Array-or-Python-Random-Swapping-Approach
class Solution: def __init__(self, nums: List[int]): self.original = nums def reset(self) -> List[int]: return self.original def shuffle(self) -> List[int]: result, n = self.original.copy(), len(self.original) for i in range(n): ind = random.randint(0, n - 1) result[i], result[ind] = result[ind], result[i] return result
shuffle-an-array
Shuffle Array | Python Random Swapping Approach
yiseboge
0
85
shuffle an array
384
0.577
Medium
6,583
https://leetcode.com/problems/shuffle-an-array/discuss/811552/Python3-Knuth-shuffle
class Solution: def __init__(self, nums: List[int]): self.nums = nums self.orig = nums.copy() # original array def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """ return self.orig def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ for i in range(1, len(self.nums)): ii = randint(0, i) self.nums[ii], self.nums[i] = self.nums[i], self.nums[ii] return self.nums
shuffle-an-array
[Python3] Knuth shuffle
ye15
0
141
shuffle an array
384
0.577
Medium
6,584
https://leetcode.com/problems/shuffle-an-array/discuss/603080/Python-sol-by-native-tools.-85%2B-w-Comment
class Solution: def __init__(self, nums: List[int]): self.size = len(nums) self.origin = nums self.array = [*nums] def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """ return self.origin def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ size, arr = self.size, self.array for i in range(size): j = randint(i, size-1) arr[i], arr[j] = arr[j], arr[i] return arr # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
shuffle-an-array
Python sol by native tools. 85%+ [w/ Comment ]
brianchiang_tw
0
285
shuffle an array
384
0.577
Medium
6,585
https://leetcode.com/problems/shuffle-an-array/discuss/514309/Python3-use-random-shuffle-function
class Solution: def __init__(self, nums: List[int]): self.nums=nums def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """ return self.nums def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ import random res = list(self.nums) random.shuffle(res) return res # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
shuffle-an-array
Python3 use random shuffle function
jb07
0
129
shuffle an array
384
0.577
Medium
6,586
https://leetcode.com/problems/shuffle-an-array/discuss/485921/Python-3-(six-lines)-(beats-~98)
class Solution: def __init__(self, n): self.array = n def reset(self): return self.array def shuffle(self): s = self.array[:] random.shuffle(s) return s - Junaid Mansuri - Chicago, IL
shuffle-an-array
Python 3 (six lines) (beats ~98%)
junaidmansuri
0
420
shuffle an array
384
0.577
Medium
6,587
https://leetcode.com/problems/shuffle-an-array/discuss/422655/EXACTLY-equally-likely-permutations
class Solution: def __init__(self, nums: List[int]): self.original = nums def reset(self) -> List[int]: return self.original def shuffle(self) -> List[int]: try: return next(self.perm) except: self.perm = itertools.permutations(self.original) return next(self.perm)
shuffle-an-array
EXACTLY equally likely permutations
SkookumChoocher
0
95
shuffle an array
384
0.577
Medium
6,588
https://leetcode.com/problems/shuffle-an-array/discuss/1365722/3Sum-Closest-Easy-Python-2-pointer-Binary-Search
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: a = nums[0]+nums[1]+nums[len(nums)-1] nums.sort() for i in range(len(nums)-2): l = i+1 h = len(nums)-1 while l<h: b = nums[i]+nums[l]+nums[h] if b > target: h -= 1 else: l += 1 if abs(target - b)<abs(target - a): a = b return a
shuffle-an-array
3Sum Closest , Easy , Python , 2 pointer , Binary Search
user8744WJ
-1
181
shuffle an array
384
0.577
Medium
6,589
https://leetcode.com/problems/mini-parser/discuss/875743/Python3-a-concise-recursive-solution
class Solution: def deserialize(self, s: str) -> NestedInteger: if not s: return NestedInteger() if not s.startswith("["): return NestedInteger(int(s)) # integer ans = NestedInteger() s = s[1:-1] # strip outer "[" and "]" if s: ii = op = 0 for i in range(len(s)): if s[i] == "[": op += 1 if s[i] == "]": op -= 1 if s[i] == "," and op == 0: ans.add(self.deserialize(s[ii:i])) ii = i+1 ans.add(self.deserialize(s[ii:i+1])) return ans
mini-parser
[Python3] a concise recursive solution
ye15
2
178
mini parser
385
0.366
Medium
6,590
https://leetcode.com/problems/mini-parser/discuss/1638534/Elegant-Python-One-Pass-Solution-(using-stack)
class Solution: def deserialize(self, s: str) -> NestedInteger: stack = [] integerStr = '' for c in s: if c == '[': stack.append(NestedInteger()) elif c == ']': if len(integerStr)>0: stack[-1].add(NestedInteger(int(integerStr))) integerStr = '' poppedList = stack.pop() if len(stack)==0: return poppedList stack[-1].add(poppedList) elif c == ',': if len(integerStr)>0: stack[-1].add(NestedInteger(int(integerStr))) integerStr = '' else: integerStr += c return NestedInteger(int(s))
mini-parser
Elegant Python One Pass Solution (using stack)
RG97
1
152
mini parser
385
0.366
Medium
6,591
https://leetcode.com/problems/lexicographical-numbers/discuss/2053392/Python-oneliner
class Solution: def lexicalOrder(self, n: int) -> List[int]: return sorted([x for x in range(1,n+1)],key=lambda x: str(x))
lexicographical-numbers
Python oneliner
StikS32
1
135
lexicographical numbers
386
0.608
Medium
6,592
https://leetcode.com/problems/lexicographical-numbers/discuss/1879853/Single-line-python-3-solution-98-faster
class Solution: def lexicalOrder(self, n: int) -> List[int]: return sorted(list(map(str,list(range(1,n+1)))))
lexicographical-numbers
Single line python 3 solution 98% faster
amannarayansingh10
1
112
lexicographical numbers
386
0.608
Medium
6,593
https://leetcode.com/problems/lexicographical-numbers/discuss/1787311/O(n)-time-O(1)-space-stack-solution-in-Python
class Solution: def lexicalOrder(self, n: int) -> List[int]: stack = [] for i in range(min(n, 9), 0, -1): stack.append(i) res = [] while stack: last = stack.pop() if last > n: continue else: res.append(last) for i in range(9, -1, -1): stack.append(last * 10 + i) return res
lexicographical-numbers
O(n) time, O(1) space stack solution in Python
kryuki
1
124
lexicographical numbers
386
0.608
Medium
6,594
https://leetcode.com/problems/lexicographical-numbers/discuss/817573/Python3-two-approaches-(sorting-and-dfs)
class Solution: def lexicalOrder(self, n: int) -> List[int]: return sorted(range(1, n+1), key=str)
lexicographical-numbers
[Python3] two approaches (sorting & dfs)
ye15
1
74
lexicographical numbers
386
0.608
Medium
6,595
https://leetcode.com/problems/lexicographical-numbers/discuss/817573/Python3-two-approaches-(sorting-and-dfs)
class Solution: def lexicalOrder(self, n: int) -> List[int]: def dfs(x): """Pre-order traverse the tree.""" if x <= n: ans.append(x) for xx in range(10): dfs(10*x + xx) ans = [] for x in range(1, 10): dfs(x) return ans
lexicographical-numbers
[Python3] two approaches (sorting & dfs)
ye15
1
74
lexicographical numbers
386
0.608
Medium
6,596
https://leetcode.com/problems/lexicographical-numbers/discuss/810448/Python-3-or-One-liner-cheat-or-Sort-String
class Solution: def lexicalOrder(self, n: int) -> List[int]: return [int(i) for i in sorted([str(i) for i in range(1, n+1)])]
lexicographical-numbers
Python 3 | One-liner cheat | Sort String
idontknoooo
1
290
lexicographical numbers
386
0.608
Medium
6,597
https://leetcode.com/problems/lexicographical-numbers/discuss/2848655/Brute-force-solution-from-empty-list
class Solution: def lexicalOrder(self, n: int) -> List[int]: out = [] i = 1 nlen = len(str(n)) while len(out) < n: out.append(i) if i*10 <= n: i = i*10 elif i < n and (i+1)//10 < (i//10)+1: i += 1 else: while str(i//10)[-1] == '9': i = i // 10 i = i // 10 + 1 return out
lexicographical-numbers
Brute force solution from empty list
yoyo10
0
1
lexicographical numbers
386
0.608
Medium
6,598
https://leetcode.com/problems/lexicographical-numbers/discuss/2829526/No-Trie-or-Recursion%3A-Beats-97.4-Time%3A-O(n)-Space%3A-O(1)O(n)
class Solution: def lexicalOrder(self, n: int) -> List[int]: r = [] a = 1 while a <= n and a < 10: r.append(a) b = a * 10 while b <= n and b < (a + 1) * 10: r.append(b) c = b * 10 while c <= n and c < (b + 1) * 10: r.append(c) d = c * 10 while d <= n and d < (c + 1) * 10: r.append(d) e = d * 10 while e <= n and e < (d + 1) * 10: r.append(e) e += 1 d += 1 c += 1 b += 1 a += 1 return r
lexicographical-numbers
No Trie or Recursion: Beats 97.4%, Time: O(n), Space: O(1)/O(n)
Squidster777
0
4
lexicographical numbers
386
0.608
Medium
6,599