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/prime-number-of-set-bits-in-binary-representation/discuss/2535240/Python-Solution-or-Count-Bits-and-Check-Prime-or-Simple-Simulation-Based
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: def count1s(num): return bin(num).count("1") def isPrime(bits): return bits in [2,3,5,7,11,13,17,19] ans = 0 for num in range(left,right+1): ans += 1 if isPrime(count1s(num)) else 0 return ans
prime-number-of-set-bits-in-binary-representation
Python Solution | Count Bits and Check Prime | Simple Simulation Based
Gautam_ProMax
0
22
prime number of set bits in binary representation
762
0.678
Easy
12,400
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/2053792/Using-format-as-binary
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primeBits = [2, 3, 5, 7, 11, 13, 17, 19] res = 0 for n in range(left, right + 1): binary = format(n, "b") count = binary.count("1") if count in primeBits: res += 1 return res
prime-number-of-set-bits-in-binary-representation
Using format as binary
andrewnerdimo
0
30
prime number of set bits in binary representation
762
0.678
Easy
12,401
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/2036147/Python-Clean-and-Simple!
class Solution: def countPrimeSetBits(self, left, right): primes = 0 for num in range(left, right+1): numBits = self.countBits(num) primes += self.isPrime(numBits) return primes def countBits(self, num): numBits = 0 while num: bit = num & 1 numBits += bit num >>= 1 return numBits def isPrime(self, num): return num in [2,3,5,7,11,13,17,19]
prime-number-of-set-bits-in-binary-representation
Python - Clean and Simple!
domthedeveloper
0
75
prime number of set bits in binary representation
762
0.678
Easy
12,402
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1893249/Python-easy-solution-for-beginners
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: count = 0 for i in range(left, right+1): set_bits = int(bin(i)[2:].count('1')) flag = 0 if set_bits == 1: flag = 1 else: for j in range(2, set_bits): if set_bits % j == 0: flag = 1 break if flag == 0: count += 1 flag = 0 return count
prime-number-of-set-bits-in-binary-representation
Python easy solution for beginners
alishak1999
0
43
prime number of set bits in binary representation
762
0.678
Easy
12,403
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1886430/python-3-oror-simple-two-line-solution
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: primes = {2, 3, 5, 7, 11, 13, 17, 19} return sum(bin(n).count('1') in primes for n in range(left, right + 1))
prime-number-of-set-bits-in-binary-representation
python 3 || simple two line solution
dereky4
0
48
prime number of set bits in binary representation
762
0.678
Easy
12,404
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1555429/Python-Easy-Solution-or-Using-Bit-Manipulation
class Solution: def countBits(self, n): c = 0 while n > 0: if n & 1: c += 1 n >>= 1 return c def primeBits(self, n): # prime = [False, False, True, True, False, True, False, True, False, # False, False, True, False, True, False, False, False, True, False, True] # return prime[n] # OR if n == 0 or n == 1: return False for i in range(2, (n//2)+1): if n % i == 0: return False return True def countPrimeSetBits(self, left: int, right: int) -> int: count = 0 for i in range(left, right+1, 1): if self.primeBits(self.countBits(i)): count += 1 return count
prime-number-of-set-bits-in-binary-representation
Python Easy Solution | Using Bit Manipulation
leet_satyam
0
86
prime number of set bits in binary representation
762
0.678
Easy
12,405
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1323060/Python3-dollarolution
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: count, co = 0, 0 def prime(c): if c == 2: return True if c % 2 == 0 or c == 1: return False for i in range(3,int(c/3) + 1,2): if c % i == 0: return False return True for i in range(left,right+1): x = bin(i)[2:] for j in x: if j == '1': count += 1 if prime(count): co += 1 count = 0 return co
prime-number-of-set-bits-in-binary-representation
Python3 $olution
AakRay
0
84
prime number of set bits in binary representation
762
0.678
Easy
12,406
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1057081/Python3-simple-solution
class Solution: def countPrimeSetBits(self, L: int, R: int) -> int: count = 0 x = [2,3,5,7,11,13,17,19] for i in range(L,R+1): i = sum(list(map(int, bin(i).replace('0b','')))) if i in x: count += 1 return count
prime-number-of-set-bits-in-binary-representation
Python3 simple solution
EklavyaJoshi
0
80
prime number of set bits in binary representation
762
0.678
Easy
12,407
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/925978/Python-2-lines-using-set
class Solution: def countPrimeSetBits(self, L: int, R: int) -> int: m = set([2, 3, 5, 7, 11, 13, 17, 19]) return sum([True if bin(i).count('1') in m else 0 for i in range(L, R+1)])
prime-number-of-set-bits-in-binary-representation
Python 2 lines using set
modusV
0
55
prime number of set bits in binary representation
762
0.678
Easy
12,408
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1306199/Easy-Python-Solution(84.53)
class Solution: def countPrimeSetBits(self, left: int, right: int) -> int: count=0 s=[2,3,5,7,11,13,17,19,23,29,31] for i in range(left,right+1): if(bin(i).count('1') in s): count+=1 return count
prime-number-of-set-bits-in-binary-representation
Easy Python Solution(84.53%)
Sneh17029
-1
132
prime number of set bits in binary representation
762
0.678
Easy
12,409
https://leetcode.com/problems/partition-labels/discuss/1868757/Python3-GREEDY-VALIDATION-(-)-Explained
class Solution: def partitionLabels(self, s: str) -> List[int]: L = len(s) last = {s[i]: i for i in range(L)} # last appearance of the letter i, ans = 0, [] while i < L: end, j = last[s[i]], i + 1 while j < end: # validation of the part [i, end] if last[s[j]] > end: end = last[s[j]] # extend the part j += 1 ans.append(end - i + 1) i = end + 1 return ans
partition-labels
✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained
artod
63
5,700
partition labels
763
0.798
Medium
12,410
https://leetcode.com/problems/partition-labels/discuss/861875/Python-3-or-Two-Pointer-Hash-Table-O(N)-or-Explanation
class Solution: def partitionLabels(self, S: str) -> List[int]: d = collections.defaultdict(int) for i, c in enumerate(S): d[c] = i ans, left, right = [], -1, -1 for i, c in enumerate(S): right = max(right, d[c]) if i == right: ans.append(right-left) left = i return ans
partition-labels
Python 3 | Two Pointer, Hash Table, O(N) | Explanation
idontknoooo
6
658
partition labels
763
0.798
Medium
12,411
https://leetcode.com/problems/partition-labels/discuss/1713599/Python-Easy-solutions-using-set()-method
class Solution: def partitionLabels(self, s: str) -> List[int]: i = 1 count = 0 res = [] while (i <len(s)+1): count += 1 # increasing count with every letter if not (set(s[:i]).intersection(set(s[i:]))): # converting the blocks of string to sets and checking their intersection with the other set res.append(count) # storing the count when we get no intersection between sets count = 0 # resetting count to zero i += 1 return res
partition-labels
Python Easy solutions using set() method
saurabh717
3
151
partition labels
763
0.798
Medium
12,412
https://leetcode.com/problems/partition-labels/discuss/1873043/Easy-understanding-Python-Iterative-solution-O(n)
class Solution: def partitionLabels(self, s: str) -> List[int]: last ={} res = [] for i in range(len(s)): last[s[i]] = i start = 0 end = last[s[start]] i=1 while(1): while( i < end): if last[s[i]] > end: end = last[s[i]] i += 1 res.append(end-start+1) if end < len(s)-1: start = end+1 end = last[s[start]] i = start + 1 else: break return res
partition-labels
Easy understanding Python Iterative solution O(n)
vs36
2
71
partition labels
763
0.798
Medium
12,413
https://leetcode.com/problems/partition-labels/discuss/1385700/Python-or-O(n)-or-With-comments-or-Better-than-98
class Solution(object): def partitionLabels(self, s): """ :type s: str :rtype: List[int] """ h={} ## storing last occurance of each letter in hashtable for i in range(len(s)): h[s[i]]=i m=0 a=[] ## 'a' stores the final result ## 'm' stores the largest value of letter's last occurance so far. ## if m equals i then it will be on sub array for i in range(len(s)): if h[s[i]]==i and m==i: a.append(i-sum(a)+1) m=i+1 else: if h[s[i]]>m: m=h[s[i]] return a
partition-labels
Python | O(n) | With comments | Better than 98%
nmk0462
2
176
partition labels
763
0.798
Medium
12,414
https://leetcode.com/problems/partition-labels/discuss/450208/Python-3-(five-lines)-(beats-~98)
class Solution: def partitionLabels(self, S: str) -> List[int]: D, A, p, e = {c:i for i,c in enumerate(S)}, [], -1, 0 for i,c in enumerate(S): e = max(e,D[c]) if e == i: p, _ = i, A.append(i-p) return A - Junaid Mansuri - Chicago, IL
partition-labels
Python 3 (five lines) (beats ~98%)
junaidmansuri
2
301
partition labels
763
0.798
Medium
12,415
https://leetcode.com/problems/partition-labels/discuss/2088408/Python-oror-Greedy-oror-dictionary-oror-with-comments
class Solution: def partitionLabels(self, s: str) -> List[int]: # To maintain partition , we take care of last-index of each alphabet # keeps n updating last index , if index==lastindex # append this size to ans &amp; make size=0 # keeps on doing this for all the string last_index={} for i,c in enumerate(s): last_index[c]=i ans=[] size=0 last=0 for i,c in enumerate(s): size+=1 last=max(last,last_index[c]) if i==last: ans.append(size) size=0 return ans
partition-labels
Python || Greedy || dictionary || with comments
Aniket_liar07
1
50
partition labels
763
0.798
Medium
12,416
https://leetcode.com/problems/partition-labels/discuss/1869940/Python-or-HashMap-or-O(N)-or-Simple-Comments
class Solution: def partitionLabels(self, s: str) -> List[int]: hsh = {} # generate indices for each character in the s for i,char in enumerate(s): if char in hsh: hsh[char].append(i) else: hsh[char] = [i] out = [] left,right = None,None # maintain a left right index to know the range of char under one partition for key in hsh: # initialize it for the first keys first occurence and last occurence. if left is None: left = hsh[key][0] right = hsh[key][-1] # if the current keys indices are bigger than right, we have reached a point where our left and right can be paritioned separately. # hence add the length to the output and update left, right to current key index elif hsh[key][0]>right: out.append(right-left+1) left = hsh[key][0] right = hsh[key][-1] # else, update the right to the max index between right and last occurence of the current key else: right = max(right,hsh[key][-1]) # finally add the last partition out.append(right-left+1) return out
partition-labels
Python | HashMap | O(N) | Simple Comments
vishyarjun1991
1
131
partition labels
763
0.798
Medium
12,417
https://leetcode.com/problems/partition-labels/discuss/1794763/Python-Easy-Solution-oror-Beats-96
class Solution: def partitionLabels(self, s: str) -> List[int]: last_occurance = {} for i in range(len(s)): last_occurance[s[i]] = i begin = end = 0 ans = [] for i in range(len(s)): ch = s[i] ch_last_occ = last_occurance[ch] if ch_last_occ > end: end = ch_last_occ if i == end: ans.append(end - begin + 1) print(ans) begin = i+1 return ans
partition-labels
Python Easy Solution || Beats 96%
dos_77
1
53
partition labels
763
0.798
Medium
12,418
https://leetcode.com/problems/partition-labels/discuss/1725873/Python3-Solution-%3A-Greedy
class Solution: def partitionLabels(self, s: str) -> List[int]: def findFL(c): first,last = 0,0 for i,x in enumerate(s): if x==c: first = i break for j in range(len(s)-1,-1,-1): if s[j]==c: last = j break return (first,last) h = {} for x in s: if x not in h: h[x] = findFL(x) res = [each for each in h.values()] ls = [] l,r = 0,0 for x,y in res: if l>=x or r>=y or r>=x: l,r = min(l,r,x,y),max(l,r,x,y) else: ls.append((l,r)) l,r = min(x,y),max(l,r,x,y) ls.append((l,r)) return [y-x+1 for x,y in ls]
partition-labels
Python3 Solution : Greedy
deleted_user
1
45
partition labels
763
0.798
Medium
12,419
https://leetcode.com/problems/partition-labels/discuss/1288424/Simple-or-Better-than-99.8-or-O(n)-Time-or-O(1)-Space
class Solution: def partitionLabels(self, s: str) -> List[int]: D = {} for letter_i in range(len(s)): letter = s[letter_i] D[letter]=letter_i L=[] cumulative_last = 0 start = -1 c=0 for i in range(len(s)): elem = s[i] elem_last = D[elem] if elem_last==i: c+=1 if elem_last >= cumulative_last: diff = cumulative_last-start if cumulative_last-start==0: diff = 1 L.append(c) c=0 elif elem_last>cumulative_last: cumulative_last = elem_last c+=1 else: c+=1 if L==[]: return [len(s)] return L
partition-labels
Simple | Better than 99.8% | O(n) Time | O(1) Space
shuklaeshita0209
1
98
partition labels
763
0.798
Medium
12,420
https://leetcode.com/problems/partition-labels/discuss/1144139/Python-easy-understanding-hash-map
class Solution: def partitionLabels(self, S: str) -> List[int]: data = {} for i in range(len(S)): if S[i] in data: data[S[i]].append(i) else: data[S[i]] = [i] list_data = [] for key in data: list_data.append(data[key]) res = [] for row in list_data: if not res or res[-1][1] < row[0]: res.append([row[0], row[-1]]) else: res[-1][1] = max(res[-1][1], row[-1]) result = [] for row in res: result.append((row[1]-row[0]) + 1) return result
partition-labels
Python easy understanding hash map
dlog
1
131
partition labels
763
0.798
Medium
12,421
https://leetcode.com/problems/partition-labels/discuss/828391/Python3-sliding-window
class Solution: def partitionLabels(self, s: str) -> List[int]: last = {ch : i for i, ch in enumerate(s)} ans = [] lo = hi = 0 for i, ch in enumerate(s): hi = max(hi, last[ch]) if i == hi: ans.append(hi - lo + 1) lo = hi + 1 return ans
partition-labels
[Python3] sliding window
ye15
1
46
partition labels
763
0.798
Medium
12,422
https://leetcode.com/problems/partition-labels/discuss/594146/Super-Easy-Python-Solution-Beats-96-submissions
class Solution: def partitionLabels(self, S: str) -> List[int]: maxi=0 initial=0 result=[] for i in range(len(S)): if S.rindex(S[i])>maxi: maxi=S.rindex(S[i]) if i==maxi: result.append(len(S[initial:maxi+1])) initial=i+1 return (result)
partition-labels
Super Easy Python Solution Beats 96% submissions
Ayu-99
1
99
partition labels
763
0.798
Medium
12,423
https://leetcode.com/problems/partition-labels/discuss/2817982/New-solution-please-explain-to-me-why-no-one-try-this-(-i-think-it-has-a-fault-)-but-accepted-100
class Solution: def partitionLabels(self, s: str) -> List[int]: def counter(s): d={} for i in s: if i in d: d[i]+=1 else: d[i]=1 return d def comp(d,d2): for i in d2: if d[i]!=d2[i]: return False return True n=len(s) d=counter(s) left=0 right=0 res=[] while left<n: a=s[left:right+1] d2=counter(a) if comp(d,d2): res.append(a) left=right+1 right=left else: right+=1 ok = [len(i) for i in res] return ok
partition-labels
New solution , please explain to me why no one try this ( i think it has a fault ) but accepted 100%
ahmedcove1
0
4
partition labels
763
0.798
Medium
12,424
https://leetcode.com/problems/partition-labels/discuss/2785966/Golang-Rust-Python-Solution
class Solution: def partitionLabels(self, s: str) -> List[int]: d={} for i in range(len(s)): d[s[i]] = i res = 0 out = 0 ls = [] for i,char in enumerate(s): res = max(d[char],res) if i == res: ls.append(len(s[out:res+1])) out = res+1 return ls
partition-labels
Golang Rust Python Solution
anshsharma17
0
3
partition labels
763
0.798
Medium
12,425
https://leetcode.com/problems/partition-labels/discuss/2767080/Simple-Approach
class Solution: def partitionLabels(self, s: str) -> List[int]: d = defaultdict(list) for i, c in enumerate(s): d[c].append(i) ans = [] cur, prv = 0, -1 for v in d.values(): if v[0] == cur + 1: ans.append(cur-prv) prv, cur = cur, v[-1] elif v[-1] > cur: cur = v[-1] ans.append(cur-prv) return ans
partition-labels
Simple Approach
Mencibi
0
3
partition labels
763
0.798
Medium
12,426
https://leetcode.com/problems/partition-labels/discuss/2724289/Amazon-Question-Solution-%2B-Explanation
class Solution: def partitionLabels(self, s: str) -> List[int]: lastIndex = {} for idx, char in enumerate(s): lastIndex[char] = idx result = [] size, end = 0, 0 for idx, char in enumerate(s): size += 1 end = max(end, lastIndex[char]) if idx == end: result.append(size) size = 0 return result
partition-labels
Amazon Question - Solution + Explanation
mdfaisalabdullah
0
5
partition labels
763
0.798
Medium
12,427
https://leetcode.com/problems/partition-labels/discuss/2703276/Python-Simple-Solution-without-using-enumerate-or-dictionary
class Solution: def partitionLabels(self, s: str) -> List[int]: curr = 0 last = s.rfind(s[0]) outputLen = [] while(curr <= len(s)): stringToCheck = s[curr:last+1] flag = True for i in stringToCheck: #check if any character is present beyond the current substring if i in s[last+1:]: last = s.rfind(i) flag = False break if flag == True: outputLen.append(len(stringToCheck)) curr = last+1 if curr < len(s): last = s.rfind(s[curr]) else: break return outputLen
partition-labels
Python Simple Solution without using enumerate or dictionary
sunnysharma03
0
3
partition labels
763
0.798
Medium
12,428
https://leetcode.com/problems/partition-labels/discuss/2702301/Python3-Sol-faster-then-80
class Solution: def partitionLabels(self, s: str) -> List[int]: d={} for i,j in enumerate(s): d[j]=i ans=[] start,end=0,0 for i,j in enumerate(s): end=max(end,d[j]) if end==i: ans.append(end+1-start) start=i+1 return ans
partition-labels
Python3 Sol faster then 80%
pranjalmishra334
0
3
partition labels
763
0.798
Medium
12,429
https://leetcode.com/problems/partition-labels/discuss/2701860/Python-Solution-or-Hashmap-or-Greedy-or-93-Faster
class Solution: def partitionLabels(self, s: str) -> List[int]: count=Counter(s) prev={} ans=[] n=len(s) last=0 for i in range(n): if s[i] in prev: prev[s[i]]+=1 else: prev[s[i]]=1 # check if all the occurences are done if prev[s[i]]==count[s[i]]: del prev[s[i]] # if dict is empty then we have a partition if len(prev)==0: ans.append(i-last+1) last=i+1 return ans
partition-labels
Python Solution | Hashmap | Greedy | 93% Faster
Siddharth_singh
0
9
partition labels
763
0.798
Medium
12,430
https://leetcode.com/problems/partition-labels/discuss/2658314/HashMap-solution-Python
class Solution: def partitionLabels(self, s: str) -> List[int]: freq_map = {} for ind, char in enumerate(s): freq_map[char] = ind count = 0 res = [] max_count = 0 for ind, c in enumerate(s): count +=1 max_count = max(max_count, freq_map[c]) if ind == max_count: res.append(count) count = 0 return res
partition-labels
HashMap solution - Python
asambatu
0
2
partition labels
763
0.798
Medium
12,431
https://leetcode.com/problems/partition-labels/discuss/2645675/Python
class Solution: def partitionLabels(self, s: str) -> List[int]: last = {c:i for i, c in enumerate(s)} start = end = 0 ans = [] for curr,m in enumerate(s): end = max(end,last[m]) if curr == end: ans.append(end-start+1) start = curr+1 return ans
partition-labels
Python
Brillianttyagi
0
18
partition labels
763
0.798
Medium
12,432
https://leetcode.com/problems/partition-labels/discuss/2429961/Partition-Labels-oror-Python3
class Solution: def partitionLabels(self, s: str) -> List[int]: last = [0] * 26 for i in range(len(s)): char = s[i] last[ord(char)-ord('a')] = i j = 0 start = 0 ans = [] for i in range(0, len(s)): char = s[i] j = max(j, last[ord(char)-ord('a')]) if(i==j): ans.append(i-start+1) start = i + 1 return ans
partition-labels
Partition Labels || Python3
vanshika_2507
0
12
partition labels
763
0.798
Medium
12,433
https://leetcode.com/problems/partition-labels/discuss/2404611/easy-python-solution
class Solution: def partitionLabels(self, s: str) -> List[int]: char_list = [i for i in s] ans = [] for i in range(len(s)) : first_part, second_part = char_list[:-(i+1)], char_list[-(i+1):] for char in second_part : if char in first_part : break else : # print(second_part) if len(ans) > 0 : ans.append(len(second_part) - sum(ans)) else : ans.append(len(second_part)) ans.reverse() return ans
partition-labels
easy python solution
sghorai
0
22
partition labels
763
0.798
Medium
12,434
https://leetcode.com/problems/partition-labels/discuss/2343673/Fast-Python-O(n).-Detailed-Explanation-in-steps-and-Debug-Output
class Solution: def partitionLabels(self, s: str) -> List[int]: seen = {} # Step 1 res=[] for letter in s: if letter in seen: # Step 2b letterPartition=seen[letter] res[letterPartition] = sum(res[letterPartition:])+1 # Step 4 if(len(res)!=letterPartition+1): # Step 3b res=res[:letterPartition+1] # Step 5 for key in seen.keys(): # Step 6 if seen[key]>letterPartition: seen[key] =letterPartition else: res.append(1) # Step 2a seen[letter]=len(res)-1 return res
partition-labels
✅ Fast Python O(n). ✅ Detailed Explanation in steps and ✅ Debug Output
arnavjaiswal149
0
33
partition labels
763
0.798
Medium
12,435
https://leetcode.com/problems/partition-labels/discuss/2327500/Python-or-Easy-and-Simple-Solution-or-Two-pointer
class Solution: def partitionLabels(self, s: str) -> List[int]: d = {c:i for i, c in enumerate(s)} l = 0 r = 0 ans = [] for i, c in enumerate(s): r = max(r, d[c]) if i == r: ans += [r - l + 1] l = r + 1 return ans
partition-labels
Python | Easy and Simple Solution | Two pointer
desalichka
0
35
partition labels
763
0.798
Medium
12,436
https://leetcode.com/problems/partition-labels/discuss/2285199/Python-Easy-Solution
class Solution: def partitionLabels(self, s: str) -> List[int]: rev_s = s[::-1] cur_part = [0,0] res = [] for i in range(len(s)): tail_idx = len(s) - 1 - rev_s.index(s[i]) if i > cur_part[1] or i == len(s)-1: res.append(cur_part[1] - cur_part[0] + 1) if cur_part[1] == len(s)-2: res.append(1) cur_part = [i, tail_idx] else: if tail_idx > cur_part[1]: cur_part[1] = tail_idx return res
partition-labels
Python Easy Solution
codeee5141
0
16
partition labels
763
0.798
Medium
12,437
https://leetcode.com/problems/partition-labels/discuss/2262441/Python3-O(n)-solution-with-brief-explaination
class Solution: def partitionLabels(self, s: str) -> List[int]: charCount = {} remaining = set() for c in s: charCount[c] = 1 + charCount.get(c,0) partitions = [] current = 0 for c in s: current+=1 charCount[c] -= 1 if charCount[c] > 0: remaining.add(c) elif c in remaining and charCount[c] == 0: remaining.remove(c) if not remaining: partitions.append(current) current = 0 return partitions
partition-labels
[Python3] O(n) solution with brief explaination
micktoying
0
21
partition labels
763
0.798
Medium
12,438
https://leetcode.com/problems/partition-labels/discuss/2254756/Runtime%3A-40-ms-faster-than-94.00-of-Python3
class Solution: def partitionLabels(self, s: str) -> List[int]: last = {} for i in range(len(s)): last[s[i]] = i start, end, res = 0, 0, [] for i in range(len(s)): end = max(end, last[s[i]]) if i == end: res.append((end-start)+1) start = i+1 return res
partition-labels
Runtime: 40 ms, faster than 94.00% of Python3
sagarhasan273
0
16
partition labels
763
0.798
Medium
12,439
https://leetcode.com/problems/partition-labels/discuss/2243305/Python-Overcomplicated-and-easy-solutions
class Solution: def partitionLabels(self, s: str) -> List[int]: letter_end_index_map = {letter: i for i, letter in enumerate(s)} i = 0 queue = collections.deque() seen_letters = set() result = [] while i < len(s): letter = s[i] partition_end = letter_end_index_map[letter] partition_letters = set(s[i:partition_end]) seen_letters |= partition_letters | {letter} queue.extend(partition_letters) seen_letters.add(letter) while len(queue) > 0: queue_letter = queue.popleft() current_partition_end = letter_end_index_map[queue_letter] partition_end = max(current_partition_end, partition_end) current_partition_letters = set(s[i:partition_end]) queue.extend(current_partition_letters - seen_letters) seen_letters |= current_partition_letters | {queue_letter} result.append(partition_end - i + 1) i = partition_end + 1 return result
partition-labels
[Python] Overcomplicated and easy solutions
julenn
0
25
partition labels
763
0.798
Medium
12,440
https://leetcode.com/problems/partition-labels/discuss/2243305/Python-Overcomplicated-and-easy-solutions
class Solution: def partitionLabels(self, s: str) -> List[int]: letter_end_index_map = {letter: i for i, letter in enumerate(s)} result = [] count = 0 max_end = 0 for i, letter in enumerate(s): max_end = max(letter_end_index_map[letter], max_end) count += 1 if max_end == i: result.append(count) count = 0 return result
partition-labels
[Python] Overcomplicated and easy solutions
julenn
0
25
partition labels
763
0.798
Medium
12,441
https://leetcode.com/problems/partition-labels/discuss/2141402/easy-greedy-solution-using-python-hashmapdictionary
class Solution: def partitionLabels(self, s: str) -> List[int]: h = {} for i,j in enumerate(s): h[j] = i i = 0 m = 0 ans = [] # print(h) while(i<len(s)): m = max(m, h[s[i]]) # print(m,i) if(h[s[i]] > i): i += 1 elif(h[s[i]] == i): if(h[s[i]] == m): if(ans): ans.append(i+1-sum(ans)) else: ans.append(i+1) del h[s[i]] i += 1 return ans
partition-labels
easy greedy solution using python hashmap/dictionary
jagdishpawar8105
0
16
partition labels
763
0.798
Medium
12,442
https://leetcode.com/problems/partition-labels/discuss/2076312/Python
class Solution: def partitionLabels(self, s: str) -> List[int]: n = len(s) l = [0 for i in range(n)] l1 = [[0 for i in range(26)]for j in range(n)] for i in range(n-1,-1,-1): if i!=n-1: for j in range(26): l1[i][j] += l1[i+1][j] l[i] = l1[i][ord(s[i])-ord("a")] l1[i][ord(s[i])-ord("a")] += 1 i = 0 t = 0 ans = [] d = set() while i<n: d.add(s[i]) if l[i] == 0: d.remove(s[i]) if not d: ans.append(i-t+1) t = i+1 i += 1 return ans
partition-labels
Python
Shivamk09
0
27
partition labels
763
0.798
Medium
12,443
https://leetcode.com/problems/partition-labels/discuss/1976014/Python-O(N)-time-complexity
class Solution: def partitionLabels(self, s: str) -> List[int]: lastIndex = {} for index, val in enumerate(s): lastIndex[val] = index res = [] size, end = 0, 0 for index, val in enumerate(s): size += 1 end = max(end, lastIndex[val]) if index == end: res.append(size) size = 0 return res
partition-labels
Python - O(N) time complexity
dayaniravi123
0
23
partition labels
763
0.798
Medium
12,444
https://leetcode.com/problems/partition-labels/discuss/1872135/Python3or-Inline-comment-for-the-standard-soln
class Solution: def partitionLabels(self, s: str) -> List[int]: # the dictionary {letter, index of last occurance} last_occurence = {c: i for i, c in enumerate(s)} # start and end of current partition start = end = 0 ans = [] for index, ch in enumerate(s): # possible end of the current partition # for each iteration, the possible end of current partion # could be extended, because next letter gets involved end = max(end, last_occurence[ch]) # if the current index == the possible end of current partition # then the end of current partition is confirmed if index == end: # find the length of current partition ans.append(index - start +1) # the start of next partition = the current index + 1 start = index + 1 return ans
partition-labels
Python3| Inline comment for the standard soln
user0270as
0
7
partition labels
763
0.798
Medium
12,445
https://leetcode.com/problems/partition-labels/discuss/1871302/python3-solution
class Solution: def partitionLabels(self, s: str) -> List[int]: sol = [] max_val = 0 for i in range(len(s)): max_val = max(max_val, s.rfind(s[i])) if max_val == i: sol.append(max_val+1) sol[1:] = [y - x for x,y in zip(sol,sol[1:])] return sol
partition-labels
python3 solution
alessiogatto
0
14
partition labels
763
0.798
Medium
12,446
https://leetcode.com/problems/partition-labels/discuss/1870391/Python-simple-solution-with-99.77-faster
class Solution: def partitionLabels(self, s: str) -> List[int]: d = {} for i, c in enumerate(s): if c in d: d[c][1] = i else: d[c] = [i, i] intervals = sorted(d.values()) res = [] left = 0 right = 0 for x,y in intervals: if x <= right: right = max(right, y) else: res.append(right-left+1) left, right = x, y res.append(right-left+1) return res
partition-labels
Python simple solution with 99.77% faster
belal_bh
0
40
partition labels
763
0.798
Medium
12,447
https://leetcode.com/problems/partition-labels/discuss/1870251/Easy-Python3-Solution-using-Map-in-O(n)
class Solution: def partitionLabels(self, s): n = len(s) d = {} # HASHMAP FOR LAST INDEX OF EACH CHARACTER IN STRING for i,c in enumerate(s): if c in d: d[c] = i else: d[c] = i ans = [] # STORE ALL SUB PARTS IN ONE ARRAY i = 0 while i < n : if ans and s[i] in ans[-1]: # CHECK IF CURRENT CHAR IN LAST APPENDED STRING if d[s[i]]> check: #IF LAST INDEX OF CUR CHAR IS FAR FROM CHECK THEM JOIN INBETWEEN PART ans[-1]+=s[check+1: d[s[i]]+1] check = d[s[i]] else: check = d[s[i]] ans.append(s[i:check+1]) # APPEND NEW PART IF CHAR IS NOT FOUND IN LAST APPENDED STRING i += 1 return [len(i) for i in ans]
partition-labels
Easy Python3 Solution using Map in O(n)
MEETcharola
0
19
partition labels
763
0.798
Medium
12,448
https://leetcode.com/problems/partition-labels/discuss/1869853/Python-or-Simple-solution
class Solution: def partitionLabels(self, s: str) -> List[int]: i = 0 ans = [] while i<=len(s)-1: rindex = s.rindex(s[i]) j = i while j<=rindex: if s[j] in s[rindex+1:] and s.rindex(s[j])>rindex: rindex = s.rindex(s[j]) j += 1 ans.append(rindex+1-i) i = rindex+1 return ans
partition-labels
Python | Simple solution
zouhair11elhadi
0
21
partition labels
763
0.798
Medium
12,449
https://leetcode.com/problems/partition-labels/discuss/1869827/Python-Simple-Python-Solution-Using-Greedy
class Solution: def partitionLabels(self, s: str) -> List[int]: last_index = {} result = [] start_index = 0 end_index = 0 for i in range(len(s)): last_index[s[i]] = i for i in range(len(s)): end_index = max(end_index,last_index[s[i]]) if end_index == i: result.append(end_index-start_index+1) start_index = i + 1 return result
partition-labels
[ Python ] ✔✔ Simple Python Solution Using Greedy 🔥✌
ASHOK_KUMAR_MEGHVANSHI
0
27
partition labels
763
0.798
Medium
12,450
https://leetcode.com/problems/partition-labels/discuss/1869770/Python3-working-solution-with-low-mem-usage
class Solution: def partitionLabels(self, s: str) -> List[int]: check = {} for index, val in enumerate(s): check[val]=index final_list = [] start = 0 first = None tmp = [] for index, val in enumerate(s): start+=1 if first is None: first = val start = 1 if index==check[first]: max_mid = -1 for mid_val in tmp: if check[mid_val]>index and max_mid<check[mid_val]: max_mid = check[mid_val] if max_mid!=-1: first = s[max_mid] continue else: first = None final_list.append(start) elif val!=first: tmp.append(val) return final_list
partition-labels
Python3 working solution with low mem usage
shubham3
0
5
partition labels
763
0.798
Medium
12,451
https://leetcode.com/problems/partition-labels/discuss/1869745/Python-Easy-Solution
class Solution: def partitionLabels(self, s: str) -> List[int]: prev, maxi, dic, ans = 0, -1, defaultdict(int), [] for i in range(len(s)): dic[s[i]] = i for i in range(len(s)): maxi = max(maxi, dic[s[i]]) if maxi == i: ans.append(i-prev+1) prev, maxi = i + 1, -1 return ans
partition-labels
✅ Python Easy Solution
dhananjay79
0
28
partition labels
763
0.798
Medium
12,452
https://leetcode.com/problems/partition-labels/discuss/1869432/Python3-Simple-two-pass-solution-using-a-hashmap-or-O(N)-time-and-O(1)-space
class Solution: def partitionLabels(self, s: str) -> List[int]: lookup = {} res = [] for i in range(len(s)): lookup[s[i]] = i start, end = 0, lookup[s[0]] for j in range(len(s)): end = max(end, lookup[s[j]]) if j == end: res.append(end - start + 1) start = end+1 return res
partition-labels
[Python3] Simple two pass solution using a hashmap | O(N) time and O(1) space
nandhakiran366
0
8
partition labels
763
0.798
Medium
12,453
https://leetcode.com/problems/partition-labels/discuss/1869392/Python3-Solution-with-using-two-pointers-with-comments
class Solution: def partitionLabels(self, s: str) -> List[int]: elem2last_idx = [0] * 26 # element to last index of this element in the s for i, c in enumerate(s): elem2last_idx[ord(c) - 97] = i res = [] left, right = 0, 0 for i, c in enumerate(s): # find right idx of the part right = max(right, elem2last_idx[ord(c) - 97]) # end of the part if i == right: res.append(right - left + 1) # find part len left = right + 1 # переместите левую границу в начало новой части return res
partition-labels
[Python3] Solution with using two-pointers with comments
maosipov11
0
11
partition labels
763
0.798
Medium
12,454
https://leetcode.com/problems/partition-labels/discuss/1869250/Simple-python-solution-10-lines-solution
class Solution: def partitionLabels(self, s: str) -> List[int]: dd = {} size, end = 0, 0 res = [] for i, n in enumerate(s): dd[n] = i for j, c in enumerate(s): size += 1 end = max(end, dd[c]) if j == end: res.append(size) size = 0 return res
partition-labels
Simple python solution 10 lines solution
ankurbhambri
0
20
partition labels
763
0.798
Medium
12,455
https://leetcode.com/problems/partition-labels/discuss/1869141/Python-or-TC-O(N)SC-O(1)-or-Easy-to-understand-Optimized
class Solution(object): def partitionLabels(self, s): lastOccurrence = {} # get the last occurance of eahj char n string for i,char in enumerate(s): lastOccurrence[char] = i result = [] size, end = 0, 0 #compare each char position with end position id index = end that is the end of substring and apend size to result and then size = 0 for i,char in enumerate(s): size += 1 end = max(end, lastOccurrence[char]) if i == end: result.append(size) size = 0 return result
partition-labels
Python | TC-O(N)/SC-O(1) | Easy to understand Optimized
Patil_Pratik
0
8
partition labels
763
0.798
Medium
12,456
https://leetcode.com/problems/partition-labels/discuss/1869042/Python-Easy-Solution-or-Beats-90
class Solution: def partitionLabels(self, s: str) -> List[int]: d = {} for i in range(len(s)): if s[i] not in d: d[s[i]] = [i,i] else: d[s[i]][1] = i l = list(d.values()) l.sort(key=lambda x:x[0]) a = l[0] x = [] for i in range(1,len(l)): if a[0]<=l[i][0] and l[i][0]<=a[1]: a[0] = min(l[i][0],a[0]) a[1] = max(l[i][1],a[1]) else: x.append(a[1]-a[0]+1) a = l[i] x.append(a[1]-a[0]+1) return x
partition-labels
Python Easy Solution | Beats 90%
AkashHooda
0
6
partition labels
763
0.798
Medium
12,457
https://leetcode.com/problems/partition-labels/discuss/1869030/Simple-Python3-Solution
class Solution: def partitionLabels(self, s: str) -> List[int]: L = len(s) last = {s[i]: i for i in range(L)} # last appearance of the letter i, ans = 0, [] while i < L: end, j = last[s[i]], i + 1 while j < end: # validation of the part [i, end] if last[s[j]] > end: end = last[s[j]] # extend the part j += 1 ans.append(end - i + 1) i = end + 1 return ans
partition-labels
Simple Python3 Solution
user6774u
0
6
partition labels
763
0.798
Medium
12,458
https://leetcode.com/problems/partition-labels/discuss/1868874/O(N)-solution-in-python3-or-beats-98
class Solution: def partitionLabels(self, s: str) -> List[int]: last_occurence={v:i for i,v in enumerate(s)} i=0 ans=[] while i<len(s): start=i sl=s[i] end=last_occurence[sl] while i<end: end=max(last_occurence[s[i]],end) i+=1 ans.append(end-start+1) i=end+1 return ans ``` 1. Created a dictionary which story last occurences of elements in the string. 2. Traverse the string, and keep updating the last_occurence of the string corresponding to current element. 3. Whenever current index (while traversing) becomes greater than last occurence of the string that means the we have got one partition. Append the partition length.
partition-labels
O(N) solution in python3 | beats 98%
prateek4463
0
9
partition labels
763
0.798
Medium
12,459
https://leetcode.com/problems/partition-labels/discuss/1868828/O(N)-Python3-Solution
class Solution: def partitionLabels(self, s: str) -> List[int]: # calculate last window index of each character in string # This will help to define the current window boundary last_idx = {c:i for i,c in enumerate(s)} # Start with window size 1 res = [1] # define the boundary based on first character end = last_idx[s[0]] # Following loop is similar to merge intervals # start the loop at index 1 for i in range(1, len(s)): if i <= end: # update current window boundary # and also the current window length end = max(end, last_idx[s[i]]) res[-1] += 1 else: # add the next window res.append(1) end = last_idx[s[i]] return res
partition-labels
O(N) Python3 Solution
constantine786
0
15
partition labels
763
0.798
Medium
12,460
https://leetcode.com/problems/largest-plus-sign/discuss/833937/Python-3-or-DP-Bomb-Enemy-or-Explanations
class Solution: def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int: mat = [[1]*N for _ in range(N)] for x, y in mines: mat[x][y] = 0 # create matrix with mine up = [[0]*N for _ in range(N)] # count 1s above mat[i][j] if mat[i][j] is 1 for i in range(N): for j in range(N): if mat[i][j]: up[i][j] = 1 if i > 0: up[i][j] += up[i-1][j] down = [[0]*N for _ in range(N)] # count 1s below mat[i][j] if mat[i][j] is 1 for i in range(N-1, -1, -1): for j in range(N): if mat[i][j]: down[i][j] = 1 if i < N-1: down[i][j] += down[i+1][j] left = [[0]*N for _ in range(N)] # count 1s on the left side of mat[i][j] if mat[i][j] is 1 for i in range(N): for j in range(N): if mat[i][j]: left[i][j] = 1 if j > 0: left[i][j] += left[i][j-1] right = [[0]*N for _ in range(N)] # count 1s on the right side of mat[i][j] if mat[i][j] is 1 for i in range(N): for j in range(N-1, -1, -1): if mat[i][j]: right[i][j] = 1 if j < N-1: right[i][j] += right[i][j+1] # find the largest + sign by using cached directions information return max(min([up[i][j], down[i][j], left[i][j], right[i][j]]) for i in range(N) for j in range(N))
largest-plus-sign
Python 3 | DP - Bomb Enemy | Explanations
idontknoooo
5
396
largest plus sign
764
0.484
Medium
12,461
https://leetcode.com/problems/largest-plus-sign/discuss/393943/Compact-Solution-in-Python-3-(nine-lines)
class Solution: def orderOfLargestPlusSign(self, N: int, M: List[List[int]]) -> int: DP, M, R, T, m = [[math.inf]*N for i in range(N)], {tuple(m) for m in M}, list(range(N)), (0,1), 0 for k,i in itertools.product(T,R): for _ in T: c, I, _ = 0, i, R.reverse() for j in R: if k: i,j = j,i c = 0 if (i,j) in M else c + 1 DP[i][j], i = min(DP[i][j],c), I return max(max(i) for i in DP)
largest-plus-sign
Compact Solution in Python 3 (nine lines)
junaidmansuri
3
383
largest plus sign
764
0.484
Medium
12,462
https://leetcode.com/problems/largest-plus-sign/discuss/393943/Compact-Solution-in-Python-3-(nine-lines)
class Solution: def orderOfLargestPlusSign(self, N: int, M: List[List[int]]) -> int: DP, M, m = [[0]*N for i in range(N)], {tuple(m) for m in M}, 0 for i in range(N): c = 0 for j in range(N): c = 0 if (i,j) in M else c + 1 DP[i][j] = c c = 0 for j in range(N-1,-1,-1): c = 0 if (i,j) in M else c + 1 DP[i][j] = min(DP[i][j],c) for j in range(N): c = 0 for i in range(N): c = 0 if (i,j) in M else c + 1 DP[i][j] = min(DP[i][j],c) c = 0 for i in range(N-1,-1,-1): c = 0 if (i,j) in M else c + 1 m = max(m,min(DP[i][j],c)) return m - Junaid Mansuri (LeetCode ID)@hotmail.com
largest-plus-sign
Compact Solution in Python 3 (nine lines)
junaidmansuri
3
383
largest plus sign
764
0.484
Medium
12,463
https://leetcode.com/problems/largest-plus-sign/discuss/922673/Python3-dp
class Solution: def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int: mines = {(x, y) for x, y in mines} # O(1) lookup top = [[0]*N for _ in range(N)] left = [[0]*N for _ in range(N)] for i in range(N): for j in range(N): if (i, j) in mines: continue top[i][j] = 1 + top[i-1][j] if i > 0 else 1 left[i][j] = 1 + left[i][j-1] if j > 0 else 1 right = [[0]*N for _ in range(N)] bottom = [[0]*N for _ in range(N)] for i in reversed(range(N)): for j in reversed(range(N)): if (i, j) in mines: continue right[i][j] = 1 + right[i][j+1] if j+1 < N else 1 bottom[i][j] = 1 + bottom[i+1][j] if i+1 < N else 1 return max(min(top[i][j], left[i][j], right[i][j], bottom[i][j]) for i in range(N) for j in range(N))
largest-plus-sign
[Python3] dp
ye15
1
96
largest plus sign
764
0.484
Medium
12,464
https://leetcode.com/problems/largest-plus-sign/discuss/922673/Python3-dp
class Solution: def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int: dp = [[n] * n for _ in range(n)] for i, j in mines: dp[i][j] = 0 for i in range(n): ll = dd = rr = uu = 0 for j in range(n): dp[i][j] = min(dp[i][j], ll := ll+1 if dp[i][j] else 0) dp[j][i] = min(dp[j][i], dd := dd+1 if dp[j][i] else 0) dp[i][~j] = min(dp[i][~j], rr := rr+1 if dp[i][~j] else 0) dp[~j][i] = min(dp[~j][i], uu := uu+1 if dp[~j][i] else 0) return max(map(max, dp))
largest-plus-sign
[Python3] dp
ye15
1
96
largest plus sign
764
0.484
Medium
12,465
https://leetcode.com/problems/largest-plus-sign/discuss/2839141/Python-(Simple-DP)
class Solution: def orderOfLargestPlusSign(self, n, mines): dp, ans = [[0]*n for _ in range(n)], 0 banned = {tuple(mine) for mine in mines} for i in range(n): count = 0 for j in range(n): count = count + 1 if (i,j) not in banned else 0 dp[i][j] = count count = 0 for j in range(n-1,-1,-1): count = count + 1 if (i,j) not in banned else 0 dp[i][j] = min(dp[i][j],count) for j in range(n): count = 0 for i in range(n): count = count + 1 if (i,j) not in banned else 0 dp[i][j] = min(dp[i][j],count) count = 0 for i in range(n-1,-1,-1): count = count + 1 if (i,j) not in banned else 0 dp[i][j] = min(dp[i][j],count) ans = max(ans,dp[i][j]) return ans
largest-plus-sign
Python (Simple DP)
rnotappl
0
2
largest plus sign
764
0.484
Medium
12,466
https://leetcode.com/problems/largest-plus-sign/discuss/2642826/Python-Dp-4-arrays
class Solution: def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int: s, res = set((x, y) for x, y in mines), 0 up, down, left, right = [[[0] * n for i in range(n)] for j in range(4)] # from top left for i in range(n): for j in range(n): if (i, j) not in s: if i == 0 or j == 0: up[i][j] = left[i][j] = 1 else: up[i][j] = up[i - 1][j] + 1 left[i][j] = left[i][j - 1] + 1 # from down right and find the max for i in range(n - 1, -1, -1): for j in range(n - 1, -1, -1): if (i, j) not in s: if i == n - 1 or j == n - 1: down[i][j] = right[i][j] = 1 else: down[i][j] = down[i + 1][j] + 1 right[i][j] = right[i][j + 1] + 1 res = max(res, min(up[i][j], left[i][j], down[i][j], right[i][j])) return res
largest-plus-sign
Python Dp 4 arrays
JasonDecode
0
6
largest plus sign
764
0.484
Medium
12,467
https://leetcode.com/problems/largest-plus-sign/discuss/2191850/python-3-or-simple-dp-or-O(n2)O(n2)
class Solution: def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int: dp = [[n] * n for _ in range(n)] for i, j in mines: dp[i][j] = 0 for i in range(n): left = up = right = down = 0 for j in range(n): if dp[i][j] == 0: left = 0 else: left += 1 dp[i][j] = min(dp[i][j], left) if dp[j][i] == 0: up = 0 else: up += 1 dp[j][i] = min(dp[j][i], up) j = ~j if dp[i][j] == 0: right = 0 else: right += 1 dp[i][j] = min(dp[i][j], right) if dp[j][i] == 0: down = 0 else: down += 1 dp[j][i] = min(dp[j][i], down) return max(val for row in dp for val in row)
largest-plus-sign
python 3 | simple dp | O(n^2)/O(n^2)
dereky4
0
40
largest plus sign
764
0.484
Medium
12,468
https://leetcode.com/problems/couples-holding-hands/discuss/1258087/Python3-a-few-approaches
class Solution: def minSwapsCouples(self, row: List[int]) -> int: loc = {x: i for i, x in enumerate(row)} ans = 0 for i in range(0, len(row), 2): p = row[i] - 1 if row[i]&amp;1 else row[i]+1 if row[i+1] != p: ans += 1 ii = loc[p] loc[row[i+1]], loc[row[ii]] = loc[row[ii]], loc[row[i+1]] # swap mappings row[i+1], row[ii] = row[ii], row[i+1] # swap values return ans
couples-holding-hands
[Python3] a few approaches
ye15
3
84
couples holding hands
765
0.569
Hard
12,469
https://leetcode.com/problems/couples-holding-hands/discuss/2815451/Python-Brute-Force%3A-O(n2)-time-O(1)-space-or-95-time-80-space
class Solution: def minSwapsCouples(self, row: List[int]) -> int: n = len(row) def swap(idx, tgt): for i in range(idx, n): if row[i] == tgt: row[idx], row[i] = row[i], row[idx] return 1 return 0 output = 0 for i in range(0, n, 2): num = row[i] if num % 2 == 0: target = num + 1 else: target = num - 1 if row[i + 1] != target: output += swap(i + 1, target) return output
couples-holding-hands
Python Brute Force: O(n^2) time, O(1) space | 95% time, 80% space
hqz3
0
7
couples holding hands
765
0.569
Hard
12,470
https://leetcode.com/problems/couples-holding-hands/discuss/2376270/python-3-or-union-find
class Solution: def minSwapsCouples(self, row: List[int]) -> int: n = len(row) // 2 parent = [i for i in range(n)] rank = [1] * n def union(x, y): x, y = find(x), find(y) if x == y: return if rank[x] >= rank[y]: parent[y] = x rank[x] += rank[y] else: parent[x] = y rank[y] += rank[x] def find(x): while x != parent[x]: parent[x] = x = parent[parent[x]] return x for i in range(n): union(row[2 * i] // 2, row[2*i + 1] // 2) return sum(rank[i] - 1 for i in range(n) if i == parent[i])
couples-holding-hands
python 3 | union find
dereky4
0
67
couples holding hands
765
0.569
Hard
12,471
https://leetcode.com/problems/couples-holding-hands/discuss/1065248/Easy-solution-with-the-help-of-Hash-Table-and-XOR
class Solution: def minSwapsCouples(self, row: List[int]) -> int: d = {v: k for k, v in enumerate(row)} # get the number->position dictionary count = 0 for i in range(0, len(row), 2): pair = row[i]^1 # use XOR to find pair number if row[i+1] == pair: continue pos = d[pair] row[i+1], row[pos] = row[pos], row[i+1] # find the pair of row[i] d[row[pos]] = pos # update row[pos] position in dictionary count += 1 return count
couples-holding-hands
Easy solution with the help of Hash Table and XOR
HeII0W0rId
0
72
couples holding hands
765
0.569
Hard
12,472
https://leetcode.com/problems/toeplitz-matrix/discuss/2761795/Python-Simple-and-Easy-Way-to-Solve-or-97-Faster
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]])->bool: r_len, c_len = len(matrix),len(matrix[0]) for r in range (1, r_len): for c in range (1, c_len): if matrix[r][c]!=matrix[r-1][c-1]: return False return True
toeplitz-matrix
✔️ Python Simple and Easy Way to Solve | 97% Faster 🔥
pniraj657
3
182
toeplitz matrix
766
0.688
Easy
12,473
https://leetcode.com/problems/toeplitz-matrix/discuss/2761427/Java-C%2B%2BPython-oror-Very-Easy-Solution-oror-Simple-with-Comments
class Solution(object): def isToeplitzMatrix(self, matrix): return all(i == 0 or j == 0 or matrix[i-1][j-1] == val for i, row in enumerate(matrix) for j, val in enumerate(row))
toeplitz-matrix
✅ Java /C++/Python || Very Easy Solution || Simple with Comments ✅
staywithsaksham
2
266
toeplitz matrix
766
0.688
Easy
12,474
https://leetcode.com/problems/toeplitz-matrix/discuss/1170866/Python3-Simple-And-Readable-Solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: arr = matrix[0] for i in range(1 , len(matrix)): arr = [matrix[i][0]] + arr[:-1] if(matrix[i] != arr): return False return True
toeplitz-matrix
[Python3] Simple And Readable Solution
VoidCupboard
2
92
toeplitz matrix
766
0.688
Easy
12,475
https://leetcode.com/problems/toeplitz-matrix/discuss/2763413/Simplest-Python-Solution-oror-O(n2)
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: row = len(matrix) col = len(matrix[0]) for i in range(col): first = matrix[0][i] j = i r = 0 while j<col and r<row: if first != matrix[r][j]: return False j += 1 r += 1 for i in range(1,row): first = matrix[i][0] j = 0 r = i while j<col and r<row: if first != matrix[r][j]: return False j += 1 r += 1 return True
toeplitz-matrix
Simplest Python Solution || O(n^2)
Hemratna_Sonar
1
7
toeplitz matrix
766
0.688
Easy
12,476
https://leetcode.com/problems/toeplitz-matrix/discuss/2762922/Python-Simple-Python-Solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: r= len(matrix) for i in range(1,r): for j in range(1,len(matrix[0])): if matrix[i-1][j-1] != matrix[i][j]: return False return True
toeplitz-matrix
[ Python ] Simple Python Solution ✅✅
sourav638
1
6
toeplitz matrix
766
0.688
Easy
12,477
https://leetcode.com/problems/toeplitz-matrix/discuss/2762638/Python-Solution-oror-October-Leetcoding
class Solution: def isToeplitzMatrix(self, m: List[List[int]]) -> bool: #storing the last row elements of the matrix a=m[0] for i in range(1,len(m)): #first element of the i th row z=m[i][0] #inserting the element z in matrix a and poping out the last element a.insert(0,z) a.pop() if m[i]!=a: return False return True
toeplitz-matrix
Python Solution || October Leetcoding
PAKEEJA
1
30
toeplitz matrix
766
0.688
Easy
12,478
https://leetcode.com/problems/toeplitz-matrix/discuss/2761936/SIMPLE-SOLUTION
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: m=len(matrix) n=len(matrix[0]) for i in range(m-2,-1,-1): curr=matrix[i][0] row=i col=0 while row<m and col<n: if curr!=matrix[row][col]: return False row+=1 col+=1 for i in range(1,n): curr=matrix[0][i] row=0 col=i while row<m and col<n: if curr!=matrix[row][col]: return False row+=1 col+=1 return True
toeplitz-matrix
SIMPLE SOLUTION
beneath_ocean
1
58
toeplitz matrix
766
0.688
Easy
12,479
https://leetcode.com/problems/toeplitz-matrix/discuss/2761626/Simple-Python-Solution-oror-Faster-than-94
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: flag = False for row in range(len(matrix)-1): for col in range(len(matrix[0])-1): if matrix[row][col] != matrix[row+1][col+1]: flag = True break return flag==False
toeplitz-matrix
Simple Python Solution || Faster than 94%
aniketbhamani
1
9
toeplitz matrix
766
0.688
Easy
12,480
https://leetcode.com/problems/toeplitz-matrix/discuss/2352607/python-Easy-solution-with-Explanation
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: dia_dict = defaultdict(set) for r in range(len(matrix)): for c in range(len(matrix[0])): dia_dict[r-c].add(matrix[r][c]) for value in dia_dict.values(): if len(value) > 1: return False return True
toeplitz-matrix
python Easy solution with Explanation
prejudice23
1
51
toeplitz matrix
766
0.688
Easy
12,481
https://leetcode.com/problems/toeplitz-matrix/discuss/1159357/Python3-Faster-Than-98-of-online-Python3-Submissions
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: copy = matrix[0] for i in matrix[1:]: copy = [i[0]] + copy[:-1] if(i != copy): return False return True
toeplitz-matrix
[Python3] Faster Than 98% of online Python3 Submissions
Lolopola
1
70
toeplitz matrix
766
0.688
Easy
12,482
https://leetcode.com/problems/toeplitz-matrix/discuss/2765786/Easy-python-solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(len(matrix) - 1): for j in range(len(matrix[i]) - 1): if matrix[i][j] != matrix[i + 1][j + 1]: return False return True
toeplitz-matrix
Easy python solution
internethero
0
4
toeplitz matrix
766
0.688
Easy
12,483
https://leetcode.com/problems/toeplitz-matrix/discuss/2764836/Python-Simple-one-loop-only
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: m = len(matrix) n = len(matrix[0]) for i in range(0, m-1): if matrix[i][0:n-1] != matrix[i+1][1:n]: return False return True
toeplitz-matrix
[Python] Simple one loop only
Maxsis
0
3
toeplitz matrix
766
0.688
Easy
12,484
https://leetcode.com/problems/toeplitz-matrix/discuss/2764653/Easy-Solution-oror-Python
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for row in range(1,len(matrix)): for col in range(1,len(matrix[0])): if(col-1>=0 and row-1>=0): if(matrix[row][col]!=matrix[row-1][col-1]): return False return True
toeplitz-matrix
Easy Solution || Python
hasan2599
0
3
toeplitz matrix
766
0.688
Easy
12,485
https://leetcode.com/problems/toeplitz-matrix/discuss/2764539/Python-Easy-to-understand-iterative
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: if len(matrix) < 2: return True for row_index in range(len(matrix)): for col_index in range(len(matrix[row_index])): row_idx = row_index col_idx = col_index while row_idx < len(matrix) and col_idx < len(matrix[row_idx]): if matrix[row_index][col_index] != matrix[row_idx][col_idx]: return False row_idx += 1 col_idx += 1 return True
toeplitz-matrix
[Python] Easy to understand iterative
dlog
0
2
toeplitz matrix
766
0.688
Easy
12,486
https://leetcode.com/problems/toeplitz-matrix/discuss/2764450/One-line-solution-in-Python
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: return all(matrix[i][j] == matrix[i-min(i, j)][j-min(i, j)] for i in range(len(matrix)) for j in range(len(matrix[0])))
toeplitz-matrix
One line solution in Python
metaphysicalist
0
8
toeplitz matrix
766
0.688
Easy
12,487
https://leetcode.com/problems/toeplitz-matrix/discuss/2764258/Python-Solution-by-comparing-Top-left-neighbour
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for row in range(1,len(matrix)): for col in range(1,len(matrix[0])): top_left=matrix[row-1][col-1] if top_left!=matrix[row][col]: return False return True
toeplitz-matrix
Python Solution by comparing Top left neighbour
ambeersaipramod
0
4
toeplitz matrix
766
0.688
Easy
12,488
https://leetcode.com/problems/toeplitz-matrix/discuss/2764185/Python-(Faster-than-98)-or-Check-previous-row
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: rows, cols = len(matrix), len(matrix[0]) for r in range(1, rows): for c in range(1, cols): if matrix[r][c] != matrix[r - 1][c - 1]: return False return True
toeplitz-matrix
Python (Faster than 98%) | Check previous row
KevinJM17
0
4
toeplitz matrix
766
0.688
Easy
12,489
https://leetcode.com/problems/toeplitz-matrix/discuss/2764133/OneLine-Python3-Solution
class Solution(object): def isToeplitzMatrix(self, matrix): return all(matrix[y-1][x-1] == matrix[y][x] for y in range(1, len(matrix)) for x in range(1, len(matrix[0])))
toeplitz-matrix
OneLine Python3 Solution
malegkin
0
4
toeplitz matrix
766
0.688
Easy
12,490
https://leetcode.com/problems/toeplitz-matrix/discuss/2763998/Easy-and-Understandable-Python-Soluiton
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: row = len(matrix); col = len(matrix[0]); for i in range(row): for j in range(col): if (i+1 < row and j+1 < col): if (matrix[i][j] != matrix[i+1][j+1]): return False return True
toeplitz-matrix
Easy and Understandable Python Soluiton
avinashdoddi2001
0
3
toeplitz matrix
766
0.688
Easy
12,491
https://leetcode.com/problems/toeplitz-matrix/discuss/2763933/Simple-and-Fast-Python-Solution-Easy-To-Understand
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(1, len(matrix)): # Get 2 rows for comparision a = matrix[i-1] b = matrix[i] # Compare the first list slice excluding last character with second list slice excluding the first character if a[:-1] != b[1:]: return False return True
toeplitz-matrix
Simple and Fast Python Solution [Easy To Understand]
hellboy7
0
5
toeplitz matrix
766
0.688
Easy
12,492
https://leetcode.com/problems/toeplitz-matrix/discuss/2763843/Python
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: m = len(matrix) n = len(matrix[0]) ret= {} for i in range(m): for j in range(n): a = i-j b = ret.get(a,matrix[i][j]) if b!= matrix[i][j]: return False ret[a] = matrix[i][j] return True
toeplitz-matrix
Python
Akhil_krish_na
0
2
toeplitz matrix
766
0.688
Easy
12,493
https://leetcode.com/problems/toeplitz-matrix/discuss/2763766/Python-oror-Easy-Hashmap-Solution
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: d = defaultdict(set) m = len(matrix) n = len(matrix[0]) for i in range(m): for j in range(n): d[i - j].add(matrix[i][j]) for key,value in d.items(): if len(value) > 1: return False return True
toeplitz-matrix
Python || Easy Hashmap Solution
iluvsneklanguage
0
7
toeplitz matrix
766
0.688
Easy
12,494
https://leetcode.com/problems/toeplitz-matrix/discuss/2763758/Very-Simple-Python3-Solution-(92-TC-98-MC)
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(len(matrix)-1): if matrix[i][:-1] != matrix[i+1][1:]: return False return True
toeplitz-matrix
Very Simple Python3 Solution (92% TC, 98% MC)
rschevenin
0
5
toeplitz matrix
766
0.688
Easy
12,495
https://leetcode.com/problems/toeplitz-matrix/discuss/2763750/simple-solu.-in-py3
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(1,len(matrix)): if matrix[i][1:]!=matrix[i-1][:-1]:return return 1
toeplitz-matrix
simple solu. in py3
bhargavikanchamreddy
0
1
toeplitz matrix
766
0.688
Easy
12,496
https://leetcode.com/problems/toeplitz-matrix/discuss/2763647/Python3-Solution-with-using-matrix-traversal
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(len(matrix) - 1): for j in range(len(matrix[i]) - 1): if matrix[i][j] != matrix[i + 1][j + 1]: return False return True
toeplitz-matrix
[Python3] Solution with using matrix traversal
maosipov11
0
1
toeplitz matrix
766
0.688
Easy
12,497
https://leetcode.com/problems/toeplitz-matrix/discuss/2763549/Python-EASY-solution-one-pass
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(1,len(matrix[0])): for j in range(1,len(matrix)): if(matrix[j][i] != matrix[j-1][i-1]): return False return True
toeplitz-matrix
Python EASY solution one pass
Pradyumankannan
0
4
toeplitz matrix
766
0.688
Easy
12,498
https://leetcode.com/problems/toeplitz-matrix/discuss/2763470/Python!-As-short-as-it-gets!
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: n , m = len(matrix), len(matrix[0]) for dff in range(-n + 1, m): thisDiag = None for y in range(n): x = dff + y if 0 <= x < m: if thisDiag is None: thisDiag = matrix[y][x] elif thisDiag != matrix[y][x]: return False return True
toeplitz-matrix
😎Python! As short as it gets!
aminjun
0
4
toeplitz matrix
766
0.688
Easy
12,499