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/sorting-the-sentence/discuss/1492510/1-line-solution-in-Python
class Solution: def sortSentence(self, s: str) -> str: words = s.split() ans, uni_one = [""] * len(words), ord('1') for word in words: ans[ord(word[-1]) - uni_one] = word[:-1] return " ".join(ans)
sorting-the-sentence
1-line solution in Python
mousun224
2
292
sorting the sentence
1,859
0.844
Easy
26,400
https://leetcode.com/problems/sorting-the-sentence/discuss/1233500/Python-Without-Explicit-Sorting
class Solution: def sortSentence(self, s: str) -> str: string_map = {} for w in s.split(): string_map[int(w[-1])] = w[:-1] return ' '.join(string_map[i] for i in range(1, len(string_map)+1))
sorting-the-sentence
Python Without Explicit Sorting
hpar
2
255
sorting the sentence
1,859
0.844
Easy
26,401
https://leetcode.com/problems/sorting-the-sentence/discuss/1210393/PythonPython3-solution-with-explanation-and-easy-understanding
class Solution: def sortSentence(self, s: str) -> str: #Soting the given string (Converting it to list using split function) according the numbers given. s=sorted(s.split(),key = lambda x: x[-1]) #To store the string lis = [] #Traverse the sorted s list for i in s: #append the element by ignoring the last character (i.e) numbers. lis.append(i[:-1]) #return the list by joining it with space. return " ".join(lis)
sorting-the-sentence
Python/Python3 solution with explanation and easy understanding
prasanthksp1009
2
245
sorting the sentence
1,859
0.844
Easy
26,402
https://leetcode.com/problems/sorting-the-sentence/discuss/2330924/Solution-(96-Faster-)-Without-using-sort
class Solution: def sortSentence(self, s: str) -> str: indices = [] ss = list(s.split(" ")) sss = list(s.split(" ")) for i in range(len(ss)): indices.append(int(ss[i][-1])-1) for j in range(len(ss)): sss[indices[j]] = ss[j] s= "" s = ("".join(sss)) for k in range(1,len(ss)+1): if k == len(ss): s = s.replace(f"{k}","") return (s) s = s.replace(f"{k}"," ")
sorting-the-sentence
Solution (96 % Faster ) Without using sort
fiqbal997
1
71
sorting the sentence
1,859
0.844
Easy
26,403
https://leetcode.com/problems/sorting-the-sentence/discuss/2284757/Solution-(96-Faster)
class Solution: def sortSentence(self, s: str) -> str: indices = [] ss = list(s.split(" ")) sss = list(s.split(" ")) for i in range(len(ss)): indices.append(int(ss[i][-1])-1) for j in range(len(ss)): sss[indices[j]] = ss[j] s= "" s = ("".join(sss)) for k in range(1,len(ss)+1): if k == len(ss): s = s.replace(f"{k}","") return (s) s = s.replace(f"{k}"," ")
sorting-the-sentence
Solution (96% Faster)
fiqbal997
1
57
sorting the sentence
1,859
0.844
Easy
26,404
https://leetcode.com/problems/sorting-the-sentence/discuss/2264489/Python3-O(n)-oror-O(n)-Runtime%3A-41ms-65.21-oror-memory%3A-14mb-9.82
class Solution: # O(n) || O(n) # Runtime: 41ms 65.21% || memory: 14mb 9.82% def sortSentence(self, string: str) -> str: newString = [0] * len(string.split()) for chars in string.split(): newString[int(chars[-1])-1] = chars[:-1] return ' '.join(newString)
sorting-the-sentence
Python3 O(n) || O(n) # Runtime: 41ms 65.21% || memory: 14mb 9.82%
arshergon
1
65
sorting the sentence
1,859
0.844
Easy
26,405
https://leetcode.com/problems/sorting-the-sentence/discuss/2254458/Python-3-easy-3-step-solution
class Solution: def sortSentence(self, s: str) -> str: sentence = s.split(' ') # 1. split the string into list sentence.sort(key = lambda x: x[-1]) # 2. sort each word on the basis of last character return ' '.join([i[:-1] for i in sentence]) # 3. rejoin the string leaving the last character of each word and return it
sorting-the-sentence
[Python 3] easy 3 step solution
Priyanshu_srivastava
1
101
sorting the sentence
1,859
0.844
Easy
26,406
https://leetcode.com/problems/sorting-the-sentence/discuss/1921152/Python-3-Simple-sorting-based-on-numbers-using-zip
class Solution: def sortSentence(self, s: str) -> str: new = [int(y) for x in s.split() for y in x if y.isnumeric()] # Isnumeric is used since the numbers are connected to the letters and we only go up to 9 so no worry of double digits being split up. res = [x[:-1] for _, x in sorted(zip(new, s.split()))] return " ".join(x for x in res)
sorting-the-sentence
[Python 3] Simple sorting based on numbers using zip
IvanTsukei
1
154
sorting the sentence
1,859
0.844
Easy
26,407
https://leetcode.com/problems/sorting-the-sentence/discuss/1921152/Python-3-Simple-sorting-based-on-numbers-using-zip
class Solution: def sortSentence(self, s: str) -> str: new = [x[-1] for x in s.split()] res = [x[:-1] for _, x in sorted(zip(new, s.split()))] return " ".join(x for x in res)
sorting-the-sentence
[Python 3] Simple sorting based on numbers using zip
IvanTsukei
1
154
sorting the sentence
1,859
0.844
Easy
26,408
https://leetcode.com/problems/sorting-the-sentence/discuss/1914651/Python3-or-4-lines-of-code-or-Split-or-Join
class Solution: def sortSentence(self, s: str) -> str: slist = s.split(" ") res = [str()] * len(slist) for word in slist: res[int(word[-1]) - 1] = word[:-1] return " ".join(res)
sorting-the-sentence
Python3 | 4 lines of code | Split | Join
milannzz
1
80
sorting the sentence
1,859
0.844
Easy
26,409
https://leetcode.com/problems/sorting-the-sentence/discuss/1864870/Python3-Easy-and-Fast-Solution
class Solution: def sortSentence(self, s: str) -> str: l = s.split() sentence = '' i = 1 while i<=len(l): for word in l: if word[-1] == str(i): w = word[:-1] + ' ' sentence += w i += 1 return sentence[:-1]
sorting-the-sentence
[Python3] Easy and Fast Solution
natscripts
1
140
sorting the sentence
1,859
0.844
Easy
26,410
https://leetcode.com/problems/sorting-the-sentence/discuss/1857831/Python-Easy-Solution-Faster-than-93
class Solution: def sortSentence(self, s: str) -> str: wordList = [i for i in s.split()] res = ["0" for i in range(len(wordList))] for word in wordList: res[int(word[-1])-1] = word[:-1] sortSentence = " ".join(res) return sortSentence
sorting-the-sentence
Python Easy Solution, Faster than 93%,
harshitb93
1
87
sorting the sentence
1,859
0.844
Easy
26,411
https://leetcode.com/problems/sorting-the-sentence/discuss/1594077/Python-Simple-O(n)-solution
class Solution: def sortSentence(self, s: str) -> str: tmp = '' res = [''] * len(s.split()) for i in range(len(s)): if s[i].isdigit(): res[int(s[i]) - 1] = tmp tmp = '' elif s[i] != ' ': tmp += s[i] return (' '.join(res))
sorting-the-sentence
[Python] Simple O(n) solution
erictang10634
1
171
sorting the sentence
1,859
0.844
Easy
26,412
https://leetcode.com/problems/sorting-the-sentence/discuss/1533121/Dictionary-of-words-99-speed
class Solution: def sortSentence(self, s: str) -> str: words = {int(w[-1]): w[:-1] for w in s.split()} return " ".join(words[key] for key in range(1, max(words.keys()) + 1))
sorting-the-sentence
Dictionary of words, 99% speed
EvgenySH
1
172
sorting the sentence
1,859
0.844
Easy
26,413
https://leetcode.com/problems/sorting-the-sentence/discuss/1351023/Python-96-faster-24-ms
class Solution: def sortSentence(self, s: str) -> str: arr_len=s.split() res=[None]*len(arr_len) for i in arr_len: res[int(i[-1])-1]=i[:-1] return ' '.join(res)
sorting-the-sentence
Python 96 % faster 24 ms
prajwal_vs
1
144
sorting the sentence
1,859
0.844
Easy
26,414
https://leetcode.com/problems/sorting-the-sentence/discuss/1277301/Easy-Python-Solution-or-O(N)-Time-using-dicitionary
class Solution: def sortSentence(self, s: str) -> str: d = {} for i in s.split(): d[int(i[-1])] = i[:-1] ans = "" for i in range(1, len(s.split()) + 1): ans += d[i] + " " return ans[:-1]
sorting-the-sentence
Easy Python Solution | O(N) Time using dicitionary
vanigupta20024
1
229
sorting the sentence
1,859
0.844
Easy
26,415
https://leetcode.com/problems/sorting-the-sentence/discuss/1211293/Explanation-with-Example
class Solution(object): def sortSentence(self, s): """ :type s: str :rtype: str """ s=s.split(" ") p=[None]*len(s) for i in s: p[int(i[-1])-1]=i[:len(i)-1] return " ".join(p)
sorting-the-sentence
Explanation with Example
paul_dream
1
76
sorting the sentence
1,859
0.844
Easy
26,416
https://leetcode.com/problems/sorting-the-sentence/discuss/2847770/Fast-and-Simple-Python-Solution-(-One-Liner-)
class Solution: def sortSentence(self, s: str) -> str: s = s.split() ; l = [int(i[-1]) for i in s] ; return " ".join([(i[1][:-1]) for i in sorted(zip(l,s))])
sorting-the-sentence
Fast & Simple Python Solution ( One Liner )
SouravSingh49
0
1
sorting the sentence
1,859
0.844
Easy
26,417
https://leetcode.com/problems/sorting-the-sentence/discuss/2842629/Easy-Python-Solution
class Solution: def sortSentence(self, s: str) -> str: index = [] sl = s.split(" ") new = [] for i in sl: index.append(int(i[-1])) new.append(i[:-1]) so = [x for _,x in sorted(zip(index, new))] return " ".join(so)
sorting-the-sentence
Easy Python Solution
Shagun_Mittal
0
2
sorting the sentence
1,859
0.844
Easy
26,418
https://leetcode.com/problems/sorting-the-sentence/discuss/2824405/Python-or-Easy-Solution-or-HashMaps-or-Sorting
class Solution: def sortSentence(self, s: str) -> str: maps = {} s = s.split() for i in s: maps[int(i[-1])] = i[:len(i)-1] res = [v for k, v in sorted(maps.items(), key=lambda a:a[0], reverse=False)] return " ".join(res)
sorting-the-sentence
Python | Easy Solution | HashMaps | Sorting
atharva77
0
4
sorting the sentence
1,859
0.844
Easy
26,419
https://leetcode.com/problems/sorting-the-sentence/discuss/2821417/Python3-Solution-oror-Slicing-and-Joining-oror-Lists
class Solution: def sortSentence(self, s: str) -> str: new = s.split() new1 = [None] * len(new) for i in new: new1[int(i[-1])-1] = i[:-1] return ' '.join(new1)
sorting-the-sentence
Python3 Solution || Slicing & Joining || Lists
shashank_shashi
0
3
sorting the sentence
1,859
0.844
Easy
26,420
https://leetcode.com/problems/sorting-the-sentence/discuss/2818012/Python-simple-sorting-solution
class Solution: def sortSentence(self, s: str) -> str: bucket = [""]*10 s = s.split(" ") for wr in s: bucket[int(wr[-1])] += wr res = "" for wr in bucket: if wr != "": res += wr[:-1] + " " return res[:-1]
sorting-the-sentence
Python simple sorting solution
ankurkumarpankaj
0
6
sorting the sentence
1,859
0.844
Easy
26,421
https://leetcode.com/problems/sorting-the-sentence/discuss/2813029/Optimal-and-Clean-O(n)-time-and-O(n)-space
class Solution: # 1. split sentence into words # 2. re-wire the words to their original indicies in a new string array # 3. join the string array into a string. # O(n) time : O(n) space def sortSentence(self, s: str) -> str: words = s.split() res = [' '] * len(words) for word in words: res[int(word[-1]) - 1] = word[:-1] return " ".join(res)
sorting-the-sentence
Optimal and Clean - O(n) time and O(n) space
topswe
0
4
sorting the sentence
1,859
0.844
Easy
26,422
https://leetcode.com/problems/sorting-the-sentence/discuss/2812240/Python-90-Solution
class Solution: def sortSentence(self, s: str) -> str: spli = s.split() res = "" temp = [] for i in range(len(spli)): index = spli[i][-1] temp.append([index,spli[i][0:len(spli[i])-1]]) sor = sorted(temp) print(sor) for i in range(len(sor)): if i != len(sor)-1: res += sor[i][1] + " " else: res += sor[i][1] return res
sorting-the-sentence
Python 90% Solution
Jashan6
0
4
sorting the sentence
1,859
0.844
Easy
26,423
https://leetcode.com/problems/sorting-the-sentence/discuss/2752837/Simple-python3-solution-using-dictionary
class Solution: def sortSentence(self, s: str) -> str: tempdict = { int(x[-1]): x[0: len(x)-1] for x in s.split()} return " ".join([tempdict[x] for x in sorted(tempdict)])
sorting-the-sentence
Simple python3 solution using dictionary
vivekrajyaguru
0
6
sorting the sentence
1,859
0.844
Easy
26,424
https://leetcode.com/problems/sorting-the-sentence/discuss/2750600/python-solution
class Solution: def sortSentence(self, s: str) -> str: li_words = s.split() new_li = sorted(li_words, key=lambda x: x[-1]) result = [] for word in new_li: result.append(word[:-1]) return " ".join(result)
sorting-the-sentence
python solution
samanehghafouri
0
5
sorting the sentence
1,859
0.844
Easy
26,425
https://leetcode.com/problems/sorting-the-sentence/discuss/2704814/Beginner-level-and-only-22ms
class Solution: def sortSentence(self, s: str) -> str: l = ['0']* (s.count(' ')+1) number = ['1','2','3','4','5','6','7','8','9'] a = "" for i in s: if i in number: l[number.index(i)] = a elif i==' ': a="" else: a+=i return " ".join(l)
sorting-the-sentence
Beginner level and only 22ms
Tushar_051
0
2
sorting the sentence
1,859
0.844
Easy
26,426
https://leetcode.com/problems/sorting-the-sentence/discuss/2671832/Python-split-rearrange-and-join
class Solution: def sortSentence(self, s: str) -> str: ans = [""] * len(s) for i in s.split(" "): ans[int(i[-1])] = i[:-1] return " ".join(ans).strip()
sorting-the-sentence
Python - split, rearrange, and join
phantran197
0
3
sorting the sentence
1,859
0.844
Easy
26,427
https://leetcode.com/problems/sorting-the-sentence/discuss/2662018/Counting-Sort-Without-Using-Split
class Solution: def sortSentence(self, s: str) -> str: if len(s) <= 4: return s[0:-1] result, count = [""] * 9, 0 i, j = 0, 1 while j < len(s): if not s[j].isdigit(): j += 1 continue result[int(s[j]) - 1] = s[i:j] count += 1 j += 3 i = j - 1 return ' '.join(result[0:count])
sorting-the-sentence
Counting Sort Without Using Split
kcstar
0
9
sorting the sentence
1,859
0.844
Easy
26,428
https://leetcode.com/problems/sorting-the-sentence/discuss/2660661/Python-easy-Solution-With-Comments-or-String-Split-and-Join-Methodsor
class Solution: def sortSentence(self, s: str) -> str: # reversing the string s = s[::-1] # spliting the string to make a list l = s.split(" ") # sorting interms of the first character # the first is a number as a result of step 1 and 2 l.sort() # print(l) lst = list() # removing the appended extra number and making it a string for s in l: s1 = s[1:] lst.append(s1[::-1]) ans = ' '.join(lst) # print(lst) return ans
sorting-the-sentence
Python easy Solution With Comments | String Split and Join Methods|
mohammed_2006
0
30
sorting the sentence
1,859
0.844
Easy
26,429
https://leetcode.com/problems/sorting-the-sentence/discuss/2657502/Python-1-liner-with-explanation
class Solution: def sortSentence(self, s: str) -> str: return ' '.join([word[:-1] for word in sorted(s.split(), key=lambda end_num: end_num[-1])])
sorting-the-sentence
Python 1 liner with explanation
code_snow
0
27
sorting the sentence
1,859
0.844
Easy
26,430
https://leetcode.com/problems/sorting-the-sentence/discuss/2657414/Python3-Solution
class Solution: def sortSentence(self, s: str) -> str: word_list = s.split() word_list.sort(key=lambda x: int(x[-1])) return " ".join([i[:-1] for i in word_list])
sorting-the-sentence
Python3 Solution
sipi09
0
3
sorting the sentence
1,859
0.844
Easy
26,431
https://leetcode.com/problems/sorting-the-sentence/discuss/2631004/Python-easy-solution-with-split-and-Join-function
class Solution: def sortSentence(self, s: str) -> str: s=s.split() output=[None]*len(s) for i in s: y=int(i[-1]) output[y-1]=i[:-1] return ' '.join(output)
sorting-the-sentence
Python easy solution with split and Join function
dnrkcharan
0
17
sorting the sentence
1,859
0.844
Easy
26,432
https://leetcode.com/problems/sorting-the-sentence/discuss/2624020/Python3-Simple-fast-with-explanation
class Solution: def sortSentence(self, s: str) -> str: # Split the string into a list, with each item being a word # -> 'is2 sentence4 This1 a3' -> ['is2', 'sentence4', 'This1', 'a3'] words = s.split(' ') # Make an empty list with as many items as the one we just made # -> ['', '', '', ''] new_sentence = [''] * len(words) # Loop through each word in the first list # Take the last character (the number) and use it as the index of the word in the new list. # At this index, simply place the word! (With the number removed using [:-1]) # (Note: need to subtract one since the list is 0-indexed, but the sentence is not) # -> 'is2'[-1] - 1 = 2 - 1 = 1 -> 'is' must go in the '1' position in the new sentence! for word in words: new_sentence[int(word[-1])-1] = word[:-1] # Finally, turn the list back into one string using .join and return! return ' '.join(new_sentence) ```
sorting-the-sentence
[Python3] Simple, fast with explanation
connorthecrowe
0
26
sorting the sentence
1,859
0.844
Easy
26,433
https://leetcode.com/problems/sorting-the-sentence/discuss/2572991/Python-using-indices-no-sort
class Solution: def sortSentence(self, s: str) -> str: string = s.split() lookup = {int(word[-1]): idx for idx, word in enumerate(string)} result = "" for idx in range(len(string)): result += string[lookup[idx+1]].replace(f'{idx+1}', ' ') return result[:-1]
sorting-the-sentence
Python - using indices, no sort
heildever
0
29
sorting the sentence
1,859
0.844
Easy
26,434
https://leetcode.com/problems/sorting-the-sentence/discuss/2545227/EASY-PYTHON3-SOLUTION
class Solution: def sortSentence(self, s: str) -> str: st = s.split() temp = [0]*len(st) for i in range(len(st)): temp[int(st[i][-1])-1] = st[i][:-1] return ' '.join(temp)
sorting-the-sentence
🔥 EASY PYTHON3 SOLUTION 🔥
rajukommula
0
63
sorting the sentence
1,859
0.844
Easy
26,435
https://leetcode.com/problems/sorting-the-sentence/discuss/2531672/Python3-1-line
class Solution(object): def sortSentence(self, s): return ' '.join(dict(sorted({int(x[-1]): x[:-1] for x in s.split(' ')}.items())).values())
sorting-the-sentence
Python3 1 line
shel18
0
55
sorting the sentence
1,859
0.844
Easy
26,436
https://leetcode.com/problems/sorting-the-sentence/discuss/2485713/Python-or-Sort-and-lambda
class Solution: def sortSentence(self, s: str) -> str: words = s.split(' ') # sort based on last char ex. is2 this1 nice3 words.sort(key=lambda x: x[-1]) return ' '.join(i[:-1] for i in words)
sorting-the-sentence
Python | Sort & lambda
ashrestha11
0
26
sorting the sentence
1,859
0.844
Easy
26,437
https://leetcode.com/problems/incremental-memory-leak/discuss/1210088/JavaC%2B%2BPython-Solution
class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: i = 1 while max(memory1, memory2) >= i: if memory1 >= memory2: memory1 -= i else: memory2 -= i i += 1 return [i, memory1, memory2]
incremental-memory-leak
[Java/C++/Python] Solution
lokeshsenthilkumar
27
1,800
incremental memory leak
1,860
0.718
Medium
26,438
https://leetcode.com/problems/incremental-memory-leak/discuss/1210088/JavaC%2B%2BPython-Solution
class Solution: def memLeak(self, m1: int, m2: int) -> List[int]: res = [1,m1,m2] while 1: if res[2] > res[1]: mx = 2 else: mx = 1 if res[0] > res[mx]: return res else: res[mx] -= res[0] res[0]+=1
incremental-memory-leak
[Java/C++/Python] Solution
lokeshsenthilkumar
27
1,800
incremental memory leak
1,860
0.718
Medium
26,439
https://leetcode.com/problems/incremental-memory-leak/discuss/1210083/Python3-simulation
class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: k = 1 while k <= memory1 or k <= memory2: if memory1 < memory2: memory2 -= k else: memory1 -= k k += 1 return [k, memory1, memory2]
incremental-memory-leak
[Python3] simulation
ye15
4
174
incremental memory leak
1,860
0.718
Medium
26,440
https://leetcode.com/problems/incremental-memory-leak/discuss/1611768/Python-or-Very-Easy-to-Understand
class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: count = 0 while memory1 or memory2: count +=1 if memory1 >= memory2: if memory1-count >= 0: memory1 -= count else: return [count, memory1, memory2] else: if memory2-count >= 0: memory2 -= count else: return [count, memory1, memory2] return [1,0,0]
incremental-memory-leak
Python | Very Easy to Understand
JimmyJammy1
0
80
incremental memory leak
1,860
0.718
Medium
26,441
https://leetcode.com/problems/incremental-memory-leak/discuss/1358081/Simulate-the-process-91-speed
class Solution: def memLeak(self, memory1: int, memory2: int) -> List[int]: for sec in range(1, memory1 + memory2 + 2): if memory1 >= memory2: if sec <= memory1: memory1 -= sec else: return [sec, memory1, memory2] else: if sec <= memory2: memory2 -= sec else: return [sec, memory1, memory2]
incremental-memory-leak
Simulate the process, 91% speed
EvgenySH
0
78
incremental memory leak
1,860
0.718
Medium
26,442
https://leetcode.com/problems/incremental-memory-leak/discuss/1210584/Python3-100-Faster-Finding-largest-using-if-and-Substracting
class Solution(object): def memLeak(self, m1, m2): i=1 while(1): if(m1>=m2): if(m1>=i): m1-=i else: break else: if(m2>=i): m2-=i else: break i+=1 return [i,m1,m2]
incremental-memory-leak
Python3, 100% Faster, Finding largest using if and Substracting
unKNOWN-G
0
54
incremental memory leak
1,860
0.718
Medium
26,443
https://leetcode.com/problems/rotating-the-box/discuss/1622675/Python-Easy-explanation
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: # move stones to right, row by row for i in range(len(box)): stone = 0 for j in range(len(box[0])): if box[i][j] == '#': # if a stone stone += 1 box[i][j] = '.' elif box[i][j] == '*': # if a obstacle for m in range(stone): box[i][j-m-1] = '#' stone = 0 # if reaches the end of j, but still have stone if stone != 0: for m in range(stone): box[i][j-m] = '#' # rotate box, same as leetcode #48 box[:] = zip(*box[::-1]) return box
rotating-the-box
[Python] Easy explanation
sashaxx
10
1,100
rotating the box
1,861
0.647
Medium
26,444
https://leetcode.com/problems/rotating-the-box/discuss/1579309/Python%3A-Simple-Two-Pointer
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: R,C = len(box), len(box[0]) new_box = [[0 for _ in range(R)] for _ in range(C)] for r in range(R): for c in range(C): new_box[c][~r] = box[r][c] #(2,0) becomes (0,0) if 2 is the last row. R,C = C,R for c in range(C): last = R - 1 # If we find a stone, we move it here for r in reversed(range(R)): # iterate from bottom to top if new_box[r][c] == '*': # if its a barrier, last is now above this barrier last = r - 1 elif new_box[r][c] == '.': # if its empty, we don't care continue elif new_box[r][c] == '#': # we hit a stone. Where do we move it? To last of course. new_box[r][c] = '.' # set current location to empty as stone is no longer here new_box[last][c] = '#' # stone is now at last place. last -= 1 # decrement last return new_box
rotating-the-box
Python: Simple Two Pointer
MapleKandoya
1
191
rotating the box
1,861
0.647
Medium
26,445
https://leetcode.com/problems/rotating-the-box/discuss/1560036/Python-3-Simple-Solution
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: m, n = len(box), len(box[0]) output = [["" for _ in range(m)] for _ in range(n)] for row in box: prevCount = 0 for i in range(len(row)): if row[i] == "#": prevCount += 1 row[i] = "." elif row[i] == "*": for j in range(prevCount): row[i-j-1] = "#" prevCount = 0 for j in range(prevCount): row[n-j-1] = "#" for i in range(n): for j in range(m): output[i][j] = box[m-1-j][i] return output
rotating-the-box
Python 3 Simple Solution
zhanz1
1
192
rotating the box
1,861
0.647
Medium
26,446
https://leetcode.com/problems/rotating-the-box/discuss/1502830/Simple-python-solution
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: R=len(box) C=len(box[0]) G=box for i in range(R): j=k=C-1 while j>=0 and k>=0: if G[i][j] == '#' and G[i][k] == '.': G[i][j] , G[i][k] = G[i][k] , G[i][j] k-=1 ; j-=1 elif G[i][j] == '*' and G[i][k] == '.': k = j-1 ; j-=1 elif G[i][j] == '.' and G[i][k] == '.': j-=1 else: k-=1 ; j-=1 lis=[] for i in range(C): nls=[] for j in range(R-1,-1,-1): nls.append(G[j][i]) lis.append(nls) return lis
rotating-the-box
Simple python solution
_YASH_
1
220
rotating the box
1,861
0.647
Medium
26,447
https://leetcode.com/problems/rotating-the-box/discuss/1210094/Python3-rotate-and-precipitate
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: m, n = len(box), len(box[0]) # dimensions for i in range(m//2): box[i], box[~i] = box[~i], box[i] box = [list(x) for x in zip(*box)] for j in range(m): count = 0 for i in range(n): if box[i][j] == "#": count += 1 box[i][j] = "." if i+1 == n or box[i+1][j] == "*": for k in range(count): box[i-k][j] = "#" count = 0 return box
rotating-the-box
[Python3] rotate and precipitate
ye15
1
128
rotating the box
1,861
0.647
Medium
26,448
https://leetcode.com/problems/rotating-the-box/discuss/2801516/Python-3-2-pointers-in-place-easy-to-understand
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: col_l = len(box[0]) for row in box: l, r = 0, 0 while r < col_l: if row[r] == '*': # obstacle -> move left pointer l = r + 1 # to place after obstacle elif row[r] == '.': # if left pointer stay on rock # and right pointer stay on empty cell # we can swap them if row[l] == '#': row[l], row[r] = row[r], row[l] l += 1 # move left pointer regardless of swap r += 1 # move right pointer every iteration return zip(*box[::-1])
rotating-the-box
Python 3 - 2 pointers - in place - easy to understand
noob_in_prog
0
9
rotating the box
1,861
0.647
Medium
26,449
https://leetcode.com/problems/rotating-the-box/discuss/2697555/Python3-Two-Pointers-with-clear-Comments
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: # make the new matrix result = [["."]*len(box) for _ in range(len(box[0]))] original_rows = len(box) - 1 original_colums = len(box[0]) - 1 # go through each row of the original and swap obstacles and stones # while keeping track of falling stones for rx, row in enumerate(box): # set the index stones fall to fall = original_colums for cx in range(len(row)-1, -1, -1): # check whether we hit an obstacle if row[cx] == '*': # put the obstacle in the new matrix result[cx][original_rows-rx] = '*' # update the fall to index fall = cx - 1 # check whether we hit a rock elif row[cx] == '#': # place the rock at the falling index result[fall][original_rows-rx] = '#' # update the fall index fall = fall - 1 return result
rotating-the-box
[Python3] - Two Pointers with clear Comments
Lucew
0
12
rotating the box
1,861
0.647
Medium
26,450
https://leetcode.com/problems/rotating-the-box/discuss/2691303/Python-or-Two-Pointers
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: m = len(box) n = len(box[0]) EMPTY = '.' STONE = '#' OBSTACLE = '*' ans = [[EMPTY for _ in range(m)] for _ in range(n)] def write_stones (i, j, stones): for r in range(j, j - stones, -1): ans[r][m-i-1] = STONE for i in range(m): j, k = n-1, n-1 stones = 0 while k >= -1: if k == -1: write_stones(i, j, stones) break if box[i][k] == OBSTACLE: write_stones(i, j, stones) ans[k][m-i-1] = OBSTACLE stones = 0 j = k - 1 elif box[i][k] == STONE: stones += 1 k -= 1 return ans
rotating-the-box
Python | Two Pointers
on_danse_encore_on_rit_encore
0
6
rotating the box
1,861
0.647
Medium
26,451
https://leetcode.com/problems/rotating-the-box/discuss/2501235/Python-Easy-to-Understand
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: rows, columns = len(box), len(box[0]) # iterate through each row for row in range(rows): # Place a pointer (elem) at the very end of the row (R->L) for elem in range(columns-1,-1,-1): # Move the pointer to the left until a rock (#) is found if (box[row][elem] == "#"): # Create a new pointer (obs) at the newly found rock's position obs = elem + 1 # Move right (L->R) until an obstacle (or another rock) is found while (obs < columns and box[row][obs] == "."): obs += 1 # Cange the original rock's position to empty (".") box[row][elem] = "." # Mark cell left of the obstacle (obs) as a rock box[row][obs-1] = "#" # Rotation rotBox = [[None for _ in range(rows)] for _ in range(columns)] curCol = rows - 1 for r in range(rows): for c in range(columns): rotBox[c][curCol] = box[r][c] curCol -= 1 return rotBox
rotating-the-box
[Python] Easy to Understand
gabrielchasukjin
0
126
rotating the box
1,861
0.647
Medium
26,452
https://leetcode.com/problems/rotating-the-box/discuss/2176486/Python3-logic-explained
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: ## RC ## ## TIME COMPLEXITY: O(N) ## ## LOGIC ## ## 1. For each row, go through all columns till you hit blocker/end ## 2. when you hit that, rearrange the row till that position ## 3. repeat and finally rotate by 90 def rearrange(stones, arr): if len(arr) == stones: return arr if stones == 0: return arr empty = len(arr) - stones for i in range(empty): arr[i] = "." for i in range(empty, len(arr)): arr[i] = "#" return arr def transpose(rows, cols, box): res = [ [ "" for _ in range(rows) ] for _ in range(cols) ] for x in range(rows): for y in range(cols): res[y][rows - x - 1] = box[x][y] return res rows, cols = len(box), len(box[0]) r = 0 while( r < rows ): c = 0 while( c < cols): stones = 0 start = c while( c < cols and box[r][c] != "*"): if box[r][c] == "#": stones += 1 c += 1 box[r][start:c] = rearrange(stones, box[r][start:c]) c += 1 r += 1 return transpose(rows, cols, box)
rotating-the-box
[Python3] logic explained
101leetcode
0
105
rotating the box
1,861
0.647
Medium
26,453
https://leetcode.com/problems/rotating-the-box/discuss/2112729/python-3-oror-simple-solution
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: n = len(box[0]) for row in box: last = n - 1 for j in range(n - 1, -1, -1): if row[j] == '#': row[j] = '.' row[last] = '#' last -= 1 elif row[j] == '*': last = j - 1 return list(zip(*reversed(box)))
rotating-the-box
python 3 || simple solution
dereky4
0
94
rotating the box
1,861
0.647
Medium
26,454
https://leetcode.com/problems/rotating-the-box/discuss/2060810/Python
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: m, n = len(box), len(box[0]) for row in box: r = w = n - 1 while r >= 0: if row[r] == '*': w = r - 1 elif row[r] == '#': if r < w: row[r] = '.' row[w] = '#' w -= 1 r -= 1 return [list(col)[::-1] for col in zip(*box)]
rotating-the-box
Python
blue_sky5
0
81
rotating the box
1,861
0.647
Medium
26,455
https://leetcode.com/problems/rotating-the-box/discuss/1902357/Easy-to-understand-python-solution
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: n = len(box) m = len(box[0]) result = [['.'] * n for i in range(m)] for i in range(n): slow = m - 1 for fast in range(m - 1, -1, -1): if box[i][fast] == '#': result[slow][n - i - 1] = '#' slow -= 1 elif box[i][fast] == '*': result[fast][n - i - 1] = '*' slow = fast - 1 return result
rotating-the-box
Easy to understand python solution
vladimir_polyakov
0
144
rotating the box
1,861
0.647
Medium
26,456
https://leetcode.com/problems/rotating-the-box/discuss/1762203/python-O(MN)-easy-to-read-with-comments
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: m, n = len(box), len(box[0]) for i in range(m): space = n - 1 # find the rightmost stone and update position, until all stones in this row is updated for j in range(n - 1, -1, -1): if box[i][j] == '.': continue # stone stops on obstacle if box[i][j] == '*': space = j - 1 continue if box[i][j] == '#': # invariant: space to the right of stone; space is the rightmost legal space while space > j and box[i][space] != '.': space -= 1 box[i][j] = '.' box[i][space] = '#' # construct new matrix res = [[] for _ in range(n)] for j in range(n): for i in range(m-1, -1, -1): res[j].append(box[i][j]) return res
rotating-the-box
python O(MN) easy to read with comments
user9051K
0
153
rotating the box
1,861
0.647
Medium
26,457
https://leetcode.com/problems/rotating-the-box/discuss/1726715/Sliding-Window
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: for line in box: l, r = 0, 0 while l < len(line): if line[l] == '.' or line[l] == '*': l += 1 r = l continue # search the end index of continuous rocks while r < len(line) and line[r] == '#': r += 1 # moving the group of rocks ahead step by step while r < len(line) and line[r] == '.': line[r], line[l] = line[l], line[r] l += 1 r += 1 # cannot move further if r < len(line): if line[r] == '#': # because we need to merge a new rock while r < len(line) and line[r] == '#': r += 1 else: # because we hit an obstacle l = r else: # because we reach the bottom break # rotate the box box = box[::-1] res = [['.']*len(box) for _ in range(len(box[0]))] for i in range(len(box[0])): for j in range(len(box)): res[i][j] = box[j][i] return res
rotating-the-box
Sliding Window
hl2425
0
69
rotating the box
1,861
0.647
Medium
26,458
https://leetcode.com/problems/rotating-the-box/discuss/1628741/Python3-Solution-with-using-two-pointers
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: for i in range(len(box)): rptr = len(box[0]) lptr = len(box[0]) - 1 while lptr >= 0: if box[i][lptr] == '*': rptr = lptr elif box[i][lptr] == '#': box[i][rptr - 1], box[i][lptr] = box[i][lptr], box[i][rptr - 1] rptr -= 1 lptr -= 1 res = [] for j in range(len(box[0])): row = [] for i in range(len(box) - 1, -1, -1): row.append(box[i][j]) res.append(row) return res
rotating-the-box
[Python3] Solution with using two-pointers
maosipov11
0
129
rotating the box
1,861
0.647
Medium
26,459
https://leetcode.com/problems/rotating-the-box/discuss/1370448/Python3-solution
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: newbox = [] for i in zip(*box): newbox.append(list(i)[::-1]) for i in range(len(newbox)-1,-1,-1): for j in range(len(newbox[0])): if newbox[i][j] == "#": z = i+1 while z < len(newbox): if newbox[z][j] == "#" or newbox[z][j] == "*": break else: z += 1 newbox[i][j] = "." newbox[z-1][j] = "#" return newbox
rotating-the-box
Python3 solution
EklavyaJoshi
0
97
rotating the box
1,861
0.647
Medium
26,460
https://leetcode.com/problems/rotating-the-box/discuss/1369720/Python-solution-backwards-range
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: m = len(box) #2 n = len(box[0]) #4 new_box = [['.' for _ in range(m)] for _ in range(n)] j = n-1 i = 0 for y in range(m-1,-1,-1): for x in range(n-1,-1,-1): if box[y][x] == '*': j = x if box[y][x] in {'#', '*'}: new_box[j][i] = box[y][x] j -= 1 i += 1 j = n-1 return new_box
rotating-the-box
Python solution - backwards range
5tigerjelly
0
118
rotating the box
1,861
0.647
Medium
26,461
https://leetcode.com/problems/rotating-the-box/discuss/1210323/Python3-10-line-solution-using-sorting-faster-and-less-memory-usage-than-100-of-solutions
class Solution: def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]: rows=[] for i in box: row = "".join(i).split("*") for j in range(len(row)): row[j]="".join(sorted(row[j], reverse=True)) row="*".join(row) rows.append(row) return zip(*rows[::-1])
rotating-the-box
Python3 10-line solution using sorting, faster and less memory usage than 100% of solutions
TheBicPen
0
110
rotating the box
1,861
0.647
Medium
26,462
https://leetcode.com/problems/sum-of-floored-pairs/discuss/1218305/PythonPython3-solution-BruteForce-and-Optimized-solution-using-Dictionary
class Solution: def sumOfFlooredPairs(self, nums: List[int]) -> int: sumP = 0 #To store the value of Sum of floor values for i in nums: #Traverse every element in nums for j in nums: #Traverse every element in nums sumP += (j//i) #Simply do floor division and add the number to sumP return sumP % (10**9 +7)#return the sumof the pairs
sum-of-floored-pairs
Python/Python3 solution BruteForce & Optimized solution using Dictionary
prasanthksp1009
7
279
sum of floored pairs
1,862
0.282
Hard
26,463
https://leetcode.com/problems/sum-of-floored-pairs/discuss/1218305/PythonPython3-solution-BruteForce-and-Optimized-solution-using-Dictionary
class Solution: def sumOfFlooredPairs(self, nums: List[int]) -> int: maxi = max(nums) + 1 dic = {} prefix=[0]*maxi for i in nums: if i in dic: dic[i] += 1 else: dic[i] = 1 #print(dic) for i in range(1,maxi): if i not in dic: prefix[i] = prefix[i-1] else: prefix[i] = prefix[i-1]+dic[i] #print(prefix,dic) sumP = 0 for i in set(nums): for j in range(i,maxi,i): sumP += dic[i]*(prefix[-1]-prefix[j-1]) #print(sumP,end = " ") return sumP % (10**9 +7)
sum-of-floored-pairs
Python/Python3 solution BruteForce & Optimized solution using Dictionary
prasanthksp1009
7
279
sum of floored pairs
1,862
0.282
Hard
26,464
https://leetcode.com/problems/sum-of-floored-pairs/discuss/1210858/Python-8-lines-frequency-prefix-sum
class Solution: def sumOfFlooredPairs(self, nums: List[int]) -> int: ans, hi, n, c = 0, max(nums)+1, len(nums), Counter(nums) pre = [0] * hi for i in range(1, hi): pre[i] = pre[i-1] + c[i] for num in set(nums): for i in range(num, hi, num): ans += c[num] * (pre[-1] - pre[i-1]) return ans % (10**9 + 7)
sum-of-floored-pairs
Python - 8 lines frequency prefix sum
leetcoder289
3
204
sum of floored pairs
1,862
0.282
Hard
26,465
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1211232/Python3-power-set
class Solution: def subsetXORSum(self, nums: List[int]) -> int: ans = 0 for mask in range(1 << len(nums)): val = 0 for i in range(len(nums)): if mask &amp; 1 << i: val ^= nums[i] ans += val return ans
sum-of-all-subset-xor-totals
[Python3] power set
ye15
8
1,100
sum of all subset xor totals
1,863
0.79
Easy
26,466
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1211232/Python3-power-set
class Solution: def subsetXORSum(self, nums: List[int]) -> int: ans = 0 for x in nums: ans |= x return ans * 2 ** (len(nums)-1)
sum-of-all-subset-xor-totals
[Python3] power set
ye15
8
1,100
sum of all subset xor totals
1,863
0.79
Easy
26,467
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1212570/PythonPython3-Solution-Brute-Force-and-Optimized
class Solution: def XoRSum(self,lis): if lis == []: return 0 if len(lis) == 1: return lis[0] xor = 0 for i in lis: xor ^= i return xor def subset(self,seq): if len(seq) <= 0: yield [] else: for item in self.subset(seq[1:]): yield [seq[0]]+item yield item def subsetXORSum(self, nums: List[int]) -> int: lis = [x for x in self.subset(nums)] sumXor = 0 lis.sort() #print(lis) for i in lis: sumXor += self.XoRSum(i) return sumXor
sum-of-all-subset-xor-totals
Python/Python3 Solution Brute Force & Optimized
prasanthksp1009
4
736
sum of all subset xor totals
1,863
0.79
Easy
26,468
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1212570/PythonPython3-Solution-Brute-Force-and-Optimized
class Solution: def subsetXORSum(self, nums: List[int]) -> int: sumXor = 0 for i in nums: sumXor |= i return sumXor * 2 ** (len(nums)-1)
sum-of-all-subset-xor-totals
Python/Python3 Solution Brute Force & Optimized
prasanthksp1009
4
736
sum of all subset xor totals
1,863
0.79
Easy
26,469
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2575329/Python-oneliner
class Solution: def subsetXORSum(self, nums: List[int]) -> int: return sum(reduce(operator.xor, comb) for i in range(1, len(nums)+1) for comb in combinations(nums, i))
sum-of-all-subset-xor-totals
Python oneliner
Vigneswar_A
2
105
sum of all subset xor totals
1,863
0.79
Easy
26,470
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1906814/Python-Solution-using-combinations-and-reduce
class Solution: def subsetXORSum(self, nums: List[int]) -> int: lst=[] for i in range(len(nums)+1): x=list(itertools.combinations(nums,i)) for j in x: lst.append(j) # print(lst) add=0 for i in lst: # print(i,len(i)) if len(i)==0: continue elif len(i)==1: add+=i[0] else: res = reduce(lambda x, y: x ^ y, i) # print(res) add+=res # print(add) return add
sum-of-all-subset-xor-totals
Python Solution using combinations and reduce
amannarayansingh10
2
174
sum of all subset xor totals
1,863
0.79
Easy
26,471
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1611783/Python-Backtracking-with-template-super-easy-to-understand
class Solution: def subsetXORSum(self, nums: List[int]) -> int: self.res = 0 def dfs(path, start): curSum = 0 for n in path: curSum = curSum ^ n self.res += curSum for i in range(start, len(nums)): num = nums[i] path.append(num) dfs(path, i + 1) path.pop() dfs([], 0) return self.res
sum-of-all-subset-xor-totals
[Python] Backtracking with template, super easy to understand
songz2
2
308
sum of all subset xor totals
1,863
0.79
Easy
26,472
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1211210/Python-Simple-Solution-or-Logic-explanation
class Solution: def subsetXORSum(self, nums: List[int]) -> int: lst = [] output = 0 for i in range(1, len(nums)): comb = list(itertools.combinations(nums, i)) for j in comb: xor = 0 for k in j: xor ^= k output += xor xor = 0 for i in nums: xor ^= i return output + xor
sum-of-all-subset-xor-totals
Python Simple Solution | Logic explanation
VijayantShri
2
421
sum of all subset xor totals
1,863
0.79
Easy
26,473
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2772219/python-solution-using-itertools
class Solution: def subsetXORSum(self, nums: List[int]) -> int: list_subsets = [] for i in range(len(nums)+1): for subset in itertools.combinations(nums, i): list_subsets.append(list(subset)) sum_xor = 0 for li in list_subsets: if len(li) == 0: continue if len(li) == 1: sum_xor += li[0] else: subset_xor = reduce(lambda x, y: x ^ y, li) sum_xor += subset_xor return sum_xor
sum-of-all-subset-xor-totals
python solution using itertools
samanehghafouri
0
1
sum of all subset xor totals
1,863
0.79
Easy
26,474
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2760607/1-Line-using-itertools.combinations
class Solution: def subsetXORSum(self, nums: List[int]) -> int: return sum(reduce(lambda x, y: x^y, subset) for l in range(1, len(nums) + 1) for subset in itertools.combinations(nums, l))
sum-of-all-subset-xor-totals
1-Line using itertools.combinations
Mencibi
0
3
sum of all subset xor totals
1,863
0.79
Easy
26,475
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2583086/SIMPLE-PYTHON3-SOLUTION-using-itertools
class Solution: def subsetXORSum(self, nums: List[int]) -> int: finalAns = 0 subsets = chain(chain.from_iterable([combinations(nums,i) for i in range(len(nums)+1)])) for subs in subsets: ans = 0 for i in subs: ans ^= i finalAns += ans return finalAns
sum-of-all-subset-xor-totals
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ using itertools
rajukommula
0
64
sum of all subset xor totals
1,863
0.79
Easy
26,476
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2482905/Python-simple-solution
class Solution: def subsetXORSum(self, nums: List[int]) -> int: from itertools import chain, combinations def xor_of_arr(arr): ans = 0 for i in arr: ans = ans ^ i return ans def powerset(iterable): s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) ans = 0 for i in powerset(nums): ans += xor_of_arr(i) return ans
sum-of-all-subset-xor-totals
Python simple solution
StikS32
0
126
sum of all subset xor totals
1,863
0.79
Easy
26,477
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2445094/Python3-or-Solved-Using-Recursion-%2B-Backtracking(brute-force)
class Solution: #Time-Complexity: O(2^n), where bulk of runtime is determined by rec. helper function #that generates all subsets 2^n of them, including duplicates! #Space-Complexity: O(2^n), store that many stack frames for call stack due to #recursion! def subsetXORSum(self, nums: List[int]) -> int: #Since the problem wants to take exclusive or for duplicate subsets, #we just have to generate all 2^n number of subsets, where n is the number #of elements in the input array or set nums! #Once we hit base case, we can simply take exclusive or and add it to running #total! ans = 0 #helper rec. function to generate all subsets! def helper(i, cur): nonlocal nums, ans #base case: i == len(nums) if(i == len(nums)): if(len(cur) == 0): return elif(len(cur) == 1): ans += cur[0] return else: initial = cur[0] for a in range(1, len(cur)): initial = initial ^ cur[a] ans += initial return #make 2 rec. calls: one to generate all subsets that contain nums[i] #and other that does not contain nums[i]! cur.append(nums[i]) helper(i+1, cur) cur.pop() helper(i+1, cur) helper(0, []) return int(ans)
sum-of-all-subset-xor-totals
Python3 | Solved Using Recursion + Backtracking(brute force)
JOON1234
0
102
sum of all subset xor totals
1,863
0.79
Easy
26,478
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2420303/Python-Solution-or-90-%2B-Faster-or-Two-Ways-Backtracking-Combinations-and-Chain
class Solution: def subsetXORSum(self, nums: List[int]) -> int: def generate(index,store): if index >= self.n: # if store is not empty if len(store) > 0: # calculate XOR sum curr = 0 for ele in store: curr ^= ele # update ans variable self.ans += curr return None # take element store.append(self.nums[index]) generate(index+1,store) # not take element store.remove(self.nums[index]) generate(index+1,store) self.nums = nums self.n = len(nums) store = [] self.ans = 0 generate(0,store) return self.ans
sum-of-all-subset-xor-totals
Python Solution | 90% + Faster | Two Ways - Backtracking / Combinations and Chain
Gautam_ProMax
0
146
sum of all subset xor totals
1,863
0.79
Easy
26,479
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2420303/Python-Solution-or-90-%2B-Faster-or-Two-Ways-Backtracking-Combinations-and-Chain
class Solution: def subsetXORSum(self, nums: List[int]) -> int: finalAns = 0 subsets = chain(chain.from_iterable([combinations(nums,i) for i in range(len(nums)+1)])) for subs in subsets: ans = 0 for i in subs: ans ^= i finalAns += ans return finalAns
sum-of-all-subset-xor-totals
Python Solution | 90% + Faster | Two Ways - Backtracking / Combinations and Chain
Gautam_ProMax
0
146
sum of all subset xor totals
1,863
0.79
Easy
26,480
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2291058/Python-Easy-solution-with-backtracking-and-explanation
class Solution: def subsetXORSum(self, nums: List[int]) -> int: result = 0 def dfs(i, subset): nonlocal result if i == len(nums): subset_xor = 0 for n in subset: subset_xor ^= n result += subset_xor return subset.append(nums[i]) dfs(i+1, subset) subset.pop() dfs(i+1, subset) dfs(0, []) return result
sum-of-all-subset-xor-totals
[Python] Easy solution with backtracking and explanation
julenn
0
108
sum of all subset xor totals
1,863
0.79
Easy
26,481
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/2171191/Python-Backtracking
class Solution: def subsetXORSum(self, nums: List[int]) -> int: self.res = 0 def dfs(index, subset): if len(subset) > 0: self.res += reduce(lambda x, y: x ^ y, subset) if index >= len(nums): return for i in range(index, len(nums)): dfs(i+1, subset + [nums[i]]) dfs(0, []) return self.res
sum-of-all-subset-xor-totals
[Python] Backtracking
Gp05
0
71
sum of all subset xor totals
1,863
0.79
Easy
26,482
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1868784/Python-dollarolution-(faster-than-90)
class Solution: def subsetXORSum(self, nums: List[int]) -> int: count = 0 for i in range(len(nums)): count += nums[i] v = [nums[i]] for j in range(i+1,len(nums)): x = len(v) for k in range(len(v)): count += v[k] ^ nums[j] v.append(v[k] ^ nums[j]) return count
sum-of-all-subset-xor-totals
Python $olution (faster than 90%)
AakRay
0
180
sum of all subset xor totals
1,863
0.79
Easy
26,483
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1795984/Simple-Python-Solution-oror-60-Faster-oror-Memory-less-than-50
class Solution: def subsetXORSum(self, nums: List[int]) -> int: def XOR(nums): ans = 0 for num in nums: ans ^= num return ans def powerset(nums): return list(chain.from_iterable(combinations(nums, r) for r in range(len(nums)+1))) subsets, ans = powerset(nums), 0 for subset in subsets: ans += XOR(subset) return ans
sum-of-all-subset-xor-totals
Simple Python Solution || 60% Faster || Memory less than 50%
Taha-C
0
111
sum of all subset xor totals
1,863
0.79
Easy
26,484
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1606241/Backtracking-in-Python-3
class Solution: def subsetXORSum(self, nums: List[int]) -> int: def bt(prev, k): if k < len(nums): yield prev for j in range(k + 1, len(nums)): yield from bt(prev ^ nums[j], j) return sum(sum(bt(n, i)) for i, n in enumerate(nums))
sum-of-all-subset-xor-totals
Backtracking in Python 3
mousun224
0
211
sum of all subset xor totals
1,863
0.79
Easy
26,485
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1229105/Python3-simple-solution
class Solution: def subsetXORSum(self, nums: List[int]) -> int: n = len(nums) res = 0 for i in range(1,2**n): x = bin(i)[2:].zfill(n) z = 0 for j,k in enumerate(x): if k == '1': z = z ^ int(nums[j]) res += z return res
sum-of-all-subset-xor-totals
Python3 simple solution
EklavyaJoshi
0
318
sum of all subset xor totals
1,863
0.79
Easy
26,486
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1556526/Python-Easy-Solution-or-Subsets-using-Bit-Manipulation
class Solution: def subsetXORSum(self, nums: List[int]) -> int: n = len(nums) length = (1 << n)-1 total = 0 for i in range(1, length+1): res = 0 for j in range(n): if i &amp; (1 << j): res ^= int(nums[j]) total += res return total
sum-of-all-subset-xor-totals
Python Easy Solution | Subsets using Bit Manipulation
leet_satyam
-1
225
sum of all subset xor totals
1,863
0.79
Easy
26,487
https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1591964/Python-3-recursion
class Solution: def subsetXORSum(self, nums: List[int]) -> int: n = len(nums) def helper(i): if i == n: return [0] xors = helper(i + 1) return xors + [nums[i] ^ xor for xor in xors] return sum(helper(0))
sum-of-all-subset-xor-totals
Python 3 recursion
dereky4
-2
234
sum of all subset xor totals
1,863
0.79
Easy
26,488
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1211146/Python3-greedy
class Solution: def minSwaps(self, s: str) -> int: ones = s.count("1") zeros = len(s) - ones if abs(ones - zeros) > 1: return -1 # impossible def fn(x): """Return number of swaps if string starts with x.""" ans = 0 for c in s: if c != x: ans += 1 x = "1" if x == "0" else "0" return ans//2 if ones > zeros: return fn("1") elif ones < zeros: return fn("0") else: return min(fn("0"), fn("1"))
minimum-number-of-swaps-to-make-the-binary-string-alternating
[Python3] greedy
ye15
23
963
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,489
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1492366/Python-3-or-Greedy-or-Explanation
class Solution: def minSwaps(self, s: str) -> int: ans = n = len(s) zero, one = 0, 0 for c in s: # count number of 0 &amp; 1s if c == '0': zero += 1 else: one += 1 if abs(zero - one) > 1: return -1 # not possible when cnt differ over 1 if zero >= one: # '010101....' s1 = '01' * (n // 2) # when zero == one s1 += '0' if n % 2 else '' # when zero > one cnt = sum(c1 != c for c1, c in zip(s1, s)) ans = cnt // 2 if zero <= one: # '101010....' s2 = '10' * (n // 2) # when zero == one s2 += '1' if n % 2 else '' # when one > zero cnt = sum(c2 != c for c2, c in zip(s2, s)) ans = min(ans, cnt // 2) return ans
minimum-number-of-swaps-to-make-the-binary-string-alternating
Python 3 | Greedy | Explanation
idontknoooo
9
395
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,490
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1220105/Greedy-oror-Well-explained-with-Example-oror-98.3-Faster-oror
class Solution: def minSwaps(self, st: str) -> int: def swap(st,c): n = len(st) mis = 0 for i in range(n): if i%2==0 and st[i]!=c: mis+=1 if i%2==1 and st[i]==c: mis+=1 return mis//2 dic = Counter(st) z = dic['0'] o = dic['1'] res=0 if abs(z-o)>1: return -1 elif z>o: res = swap(st,'0') elif o>z: res = swap(st,'1') else: res = min(swap(st,'0'),swap(st,'1')) return res
minimum-number-of-swaps-to-make-the-binary-string-alternating
🐍 {Greedy} || Well-explained with Example || 98.3% Faster ||
abhi9Rai
3
352
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,491
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1216029/Python-Solution-O(N)
class Solution: def minSwaps(self, s: str) -> int: # for odd length string with number of 1s > number of 0s it should be starting with 1 # while for number of 0s > number of 1s it should be starting with 0 # If abs diff of number of 1s and 0s is greater than 1 then we can't make it alternating one = s.count("1") zero = s.count("0") if (abs(one-zero) > 1): return -1 def solve(s, ch): res = 0 for i in range(len(s)): if (ch!= s[i]): res += 1 if ch == "1": ch = "0" else: ch = "1" return res // 2 if zero > one: return solve(s, "0") elif (one > zero): return solve(s, "1") else: return min(solve(s, "0"), solve(s, "1"))
minimum-number-of-swaps-to-make-the-binary-string-alternating
Python Solution - O(N)
dkamat01
2
226
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,492
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/2823501/Python-one-and-only-loop
class Solution: def minSwaps(self, s): ones_counts = [0, 0] # number of ones in odd indecies and even indecies for i in range(len(s)): if s[i] == '1': ones_counts[i%2] += 1 num_ones = ones_counts[0] + ones_counts[1] num_zeros = len(s) - num_ones if num_zeros - num_ones > 1 or num_zeros - num_ones < -1: return -1 elif num_zeros - num_ones == 1: # num zeroes are num ones + 1 #return num_ones - ones_counts[1] return ones_counts[0] elif num_ones - num_zeros == 1: return ones_counts[1] else: return min(ones_counts[0], ones_counts[1])
minimum-number-of-swaps-to-make-the-binary-string-alternating
Python, one and only loop
bison_a_besoncon
0
2
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,493
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/2727947/Python3-or-Short-or-Easy-to-Understand
class Solution: def minSwaps(self, s: str) -> int: zo1 = {"0": 0, "1": 0} # Pattern 1: 01010... zo2 = {"0": 0, "1": 0} # Pattern 2: 10101... case1, case2 = "0", "1" for i in s: # Pattern 1 mismatch if i != case1: zo1[i] += 1 # Pattern 2 mismatch if i != case2: zo2[i] += 1 case1, case2 = case2, case1 # Case 1) Neither Pattern Possible if zo1["1"] != zo1["0"] and zo2["1"] != zo2["0"]: return -1 # Case 2) Both Patterns are possible if zo1["1"] == zo1["0"] and zo2["1"] == zo2["0"]: return min(zo1["1"], zo2["1"]) # Case 3) 1 valid Pattern / 1 invalid Pattern return zo1["1"] if zo1["1"] == zo1["0"] else zo2["1"]
minimum-number-of-swaps-to-make-the-binary-string-alternating
Python3 | Short | Easy to Understand
PartialButton5
0
15
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,494
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/2648371/Simple-python-solution
class Solution: def minSwaps(self, s: str) -> int: def swaps(cur): mismatch = 0 for c in s: if c != cur: mismatch += 1 cur = "1" if cur == "0" else "0" return mismatch // 2 zeros, ones = 0, 0 for c in s: if c == "0": zeros += 1 else: ones += 1 if abs(zeros - ones) > 1: return -1 if zeros > ones: return swaps("0") elif zeros < ones: return swaps("1") else: return min(swaps("0"), swaps("1"))
minimum-number-of-swaps-to-make-the-binary-string-alternating
Simple python solution
shubhamnishad25
0
25
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,495
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/2510581/simple-python-solution
class Solution: def minSwaps(self, s: str) -> int: zeros, ones = 0, 0 for c in s: if c == "0": zeros += 1 else: ones += 1 if abs(zeros - ones) > 1: return -1 first = "1" if ones > zeros else "0" invalid = 0 for c in s[::2]: if c != first: invalid += 1 return invalid if ones != zeros else min(invalid, (len(s)//2) - invalid)
minimum-number-of-swaps-to-make-the-binary-string-alternating
simple python solution
jingxianchai
0
124
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,496
https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1211241/Python-Count-incorrect-positions-or-Step-by-step-explanation
class Solution: def minSwaps(self, s: str) -> int: if abs(s.count('1') - s.count('0')) > 1: return -1 ln = len(s) x, y = "10"*(ln//2), "01"*(ln//2) cnt = 0 if s.count('1') > s.count('0'): x = x + "1" for i in range(ln): if s[i]!=x[i]: cnt+=1 elif s.count('1') < s.count('0'): y = y + "0" for i in range(ln): if s[i]!=y[i]: cnt+=1 else: cntx = cnty = 0 for i in range(ln): if s[i]!=x[i]: cntx+=1 for i in range(ln): if s[i]!=y[i]: cnty+=1 cnt = min(cntx, cnty) return cnt//2
minimum-number-of-swaps-to-make-the-binary-string-alternating
[Python]- Count incorrect positions | Step by step explanation
VijayantShri
0
86
minimum number of swaps to make the binary string alternating
1,864
0.425
Medium
26,497
https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/discuss/1211157/Python3-top-down-dp
class Solution: def rearrangeSticks(self, n: int, k: int) -> int: @cache def fn(n, k): """Return number of ways to rearrange n sticks to that k are visible.""" if n == k: return 1 if k == 0: return 0 return ((n-1)*fn(n-1, k) + fn(n-1, k-1)) % 1_000_000_007 return fn(n, k)
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
[Python3] top-down dp
ye15
4
253
number of ways to rearrange sticks with k sticks visible
1,866
0.558
Hard
26,498
https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/discuss/1261757/Short-O(n)-Solution(python).
class Solution: def checkZeroOnes(self, s: str) -> bool: zero_in=temp=0 for i in s: if i=="0": temp+=1 if temp>zero_in: zero_in=temp else: temp=0 # Longest contiguous 0 in s is zero_in return "1"*(zero_in+1) in s #return boolean value
longer-contiguous-segments-of-ones-than-zeros
Short O(n) Solution(python).
_jorjis
3
183
longer contiguous segments of ones than zeros
1,869
0.603
Easy
26,499