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/longest-palindrome-by-concatenating-two-letter-words/discuss/2825459/Python-3-greedy-easy-to-understand-with-comments
class Solution: def longestPalindrome(self, words: List[str]) -> int: dct = {} sum_ = 0 cc_odd_ind = 0 # word that contains 2 identical letters (for instance, 'aa') - flag of odd number # create dictionary for wrd in words: dct[wrd] = dct.get(wrd, 0) + 1 # iterate through dictionary for k, v in dct.items(): # the first letter == the second letter if k[0] == k[1]: sum_ += v // 2 * 2 # add the nearest even number (7 --> 6, 6 --> 6, 5 --> 4, 4 --> 4) # odd number if v % 2 == 1: cc_odd_ind = 1 # create flag of odd number # the first letter == the second letter else: sum_ += min(dct.get(k, 0), \ dct.get(k[::-1], 0)) # add minimum of 2 pairs (for instance, 'cl' and 'lc') return (sum_ + cc_odd_ind) * 2
longest-palindrome-by-concatenating-two-letter-words
Python 3 - greedy - easy to understand - with comments
noob_in_prog
0
2
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,500
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2818612/Python-3-Simple-and-Intuitive-Explanation-beating-95.
class Solution: def longestPalindrome(self, words: List[str]) -> int: length = 0 seen = dict() middle_used = False for word in words: seen[word] = seen.get(word, 0) + 1 for word in seen.keys(): if word[1] + word[0] in seen.keys(): length += min(seen[word], seen[word[1] + word[0]]) if word[0] == word[1] and (seen[word] % 2) != 0: if middle_used: length -= 1 else: middle_used = True return length * 2
longest-palindrome-by-concatenating-two-letter-words
[Python 3] Simple and Intuitive Explanation beating 95%.
user7530s
0
1
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,501
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2786586/Pretty-Clear-Solution-Python-or-O(N)-Hashmap
class Solution: def longestPalindrome(self, words: List[str]) -> int: d=defaultdict(int) for word in words: d[word]+=1 cnt=0 if_odd=False vis=set() for key,val in d.items(): if key not in vis: if key[0]==key[1]: if d[key]%2!=0: if_odd=True cnt+=2*d[key]-2 else: cnt+=2*d[key] else: if key[::-1] in d: min_cnt=min(d[key],d[key[::-1]]) cnt+=4*min_cnt vis.add(key[::-1]) vis.add(key) if if_odd: return cnt+2 return cnt
longest-palindrome-by-concatenating-two-letter-words
Pretty Clear Solution Python | O(N) Hashmap
praveen0906
0
1
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,502
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2782874/Simple-yet-Best-Interview-Code-or-Python-Beginner-Friendly
class Solution: def longestPalindrome(self, words: List[str]) -> int: n = len(words) hashmap = {} LPCount = 0 for i in range(n): word = words[i] reverse_word = word[::-1] if reverse_word in hashmap: LPCount += 4 hashmap[reverse_word] -= 1 if hashmap[reverse_word] == 0: del hashmap[reverse_word] else: if word in hashmap: hashmap[word] += 1 else: hashmap[word] = 1 for word in hashmap: if word[0] == word[1]: LPCount += 2 break return LPCount
longest-palindrome-by-concatenating-two-letter-words
Simple yet Best Interview Code | Python Beginner Friendly
reinkarnation
0
5
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,503
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2778830/Easy-PYTHON
class Solution: def longestPalindrome(self, words: List[str]) -> int: x=Counter(words) count=0 mid=False for i,j in x.items(): if i[0]==i[1]: if j%2==0: count+=2*j else: count+=(j-1)*2 mid=True continue if i[1]+i[0] in x: count+=2*min(j,x[i[1]+i[0]]) return count+2 if mid else count
longest-palindrome-by-concatenating-two-letter-words
Easy PYTHON
Chetan_007
0
3
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,504
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2778535/Python-solution-using-set
class Solution: def longestPalindrome(self, words: List[str]) -> int: cnt = collections.Counter(words) aa, ab = 0, 0 cond = True st = set(words) for w in st: if w in cnt and w[::-1] in cnt: if w[0] == w[1]: if cnt[w] % 2 and cond: aa += min(cnt[w], cnt[w[::-1]]) cond = False elif cnt[w]% 2: aa += (min(cnt[w], cnt[w[::-1]]) - 1) else: aa += (min(cnt[w], cnt[w[::-1]])) else: ab += min(cnt[w], cnt[w[::-1]]) return (aa + ab) * 2
longest-palindrome-by-concatenating-two-letter-words
Python solution using set
EraCoding
0
3
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,505
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2777458/Python-Solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: count = 0 frequency = defaultdict(int) seen = set() for word in words: if frequency[word] > 0: frequency[word] -= 1 count += 4 else: frequency[word[::-1]] += 1 if word[0] == word[1]: if word in seen: seen.remove(word) else: seen.add(word) return count if len(seen) == 0 else count + 2
longest-palindrome-by-concatenating-two-letter-words
Python Solution
mansoorafzal
0
2
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,506
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2777252/Python-Simple-Python-Solution-Using-HashMap-or-Dictionary
class Solution: def longestPalindrome(self, words: List[str]) -> int: different = {} same = {} for word in words: if word[0] != word[1]: if word not in different: different[word] = 1 else: different[word] = different[word] + 1 else: if word not in same: same[word] = 1 else: same[word] = same[word] + 1 result = 0 visited = [] for key in different: if key not in visited and key[::-1] not in visited and key[::-1] in different: result = result + min(different[key], different[key[::-1]]) * 4 visited.append(key) visited.append(key[::-1]) odd_check = False for key in same: if same[key] % 2 == 0: result = result + same[key] * 2 else: if odd_check == False: result = result + (same[key] // 2) * 4 + 2 odd_check = True else: result = result + (same[key] // 2) * 4 return result
longest-palindrome-by-concatenating-two-letter-words
[ Python ] ✅✅ Simple Python Solution Using HashMap | Dictionary 🥳✌👍
ASHOK_KUMAR_MEGHVANSHI
0
10
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,507
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2775442/Longest-Palindrome-python-O(n)
class Solution: def longestPalindrome(self, words: List[str]) -> int: n = len(words) totalw = 0 waiting = collections.Counter() waiting_special = collections.Counter() for i in range(n): word = words[i] if word[-1] == word[0]: waiting_special[word] += 1 if waiting_special[word] == 2: totalw += 4 waiting_special.pop(word) continue if waiting[word[::-1]]>=1: word = word[::-1] waiting[word] -= 1 totalw += 4 else: waiting[word] += 1 if len(waiting_special) > 0: totalw += 2 return totalw
longest-palindrome-by-concatenating-two-letter-words
Longest Palindrome - python - O(n)
DavidCastillo
0
4
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,508
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2774926/Python.-As-short-as-it-gets!
class Solution: def longestPalindrome(self, words: List[str]) -> int: count = collections.Counter(words) diff, same, odd = 0, 0, 0 for word, c in count.items(): if word[0] == word[1]: same += (c // 2) * 2 odd = odd | (c & 1) else: diff += min(c, count[word[::-1]]) return (diff + same + odd) * 2
longest-palindrome-by-concatenating-two-letter-words
😎Python. As short as it gets!
aminjun
0
5
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,509
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2774695/beats-more-than-80
class Solution: def longestPalindrome(self, words: List[str]) -> int: dic = {} sum = 0 t = [] for i in words: if dic.get(i) == None and (dic.get(i[::-1]) == None or dic.get(i[::-1]) == 0) : if i == i[::-1]: t.append(i) dic[i] = 1 elif dic.get(i[::-1]) != None and dic.get(i[::-1]) != 0: dic[i[::-1]] -= 1 sum += 4 else: dic[i] += 1 for i in t: if dic[i]==1: sum+=2 break return sum
longest-palindrome-by-concatenating-two-letter-words
beats more than 80%
sivamani921124
0
5
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,510
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2774461/python3-hashtable-approach-O(n)-time
class Solution: def longestPalindrome(self, words: List[str]) -> int: d, res, centerWords = {}, 0, 0 for w in words: d[w] = d[w] + 1 if w in d else 1 for key in list(d.keys()): if key[0] == key[1]: res += 4 * (d[key] // 2) if not centerWords and d[key] % 2 == 1: centerWords = 2 elif key[::-1] in d: res += 4 * min(d[key], d[key[::-1]]) d[key[::-1]] = d[key] = 0 return res + centerWords
longest-palindrome-by-concatenating-two-letter-words
python3 hashtable approach, O(n) time
tinmanSimon
0
8
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,511
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2774404/python3-easily-understandeble-code-with-98-runtime
class Solution: def longestPalindrome(self, words: List[str]) -> int: l = Counter(words) p_len = 0 mid = 0 print(l) for word in l.keys(): if word[0] == word[1]: if l[word]%2 == 0: p_len += l[word] else: p_len += l[word]-1 mid = 1 elif word[::-1] in l: p_len += min(l[word], l[word[::-1]]) return (p_len + mid) * 2
longest-palindrome-by-concatenating-two-letter-words
python3 easily understandeble code with 98% runtime👍🙌
V_Bhavani_Prasad
0
8
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,512
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2774216/Python3-or-Runtime-95-or-Memory-Space-54
class Solution: def longestPalindrome(self, words: List[str]) -> int: result = max_padding = 0 # build a hashmap to reduce the search space hashmap = defaultdict(int) for word in words: hashmap[word] += 1 words = [w for w in hashmap.keys()] # search ignored_idx = set() for i, word in enumerate(words): if i in ignored_idx: continue # check self if len(set(word)) == 1: result += hashmap[word] // 2 * 2 * len(word) max_padding = max(max_padding, hashmap[word] % 2 * len(word)) continue # check pair rword = word[::-1] for j in range(i+1, len(words)): if j in ignored_idx: continue if rword == words[j]: result += len(word) * 2 * min(hashmap[word], hashmap[rword]) ignored_idx.add(j) break return result + max_padding
longest-palindrome-by-concatenating-two-letter-words
Python3 | Runtime 95% | Memory Space 54%
afunTW
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,513
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773850/Short-and-easy-code
class Solution: def longestPalindrome(self, words: List[str]) -> int: s = collections.defaultdict(int) l, pair = 0, 0 for w in words: k = w[::-1] if s[k]: pair -= 1 if k == w else 0 s[k] -= 1 l += 4 else: pair += 1 if k == w else 0 s[w] += 1 return l+2 if pair else l
longest-palindrome-by-concatenating-two-letter-words
Short and easy code
Opheodrys
0
12
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,514
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773723/Python-3-Solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: D = defaultdict(int) res = 0 p = False for x in words: D[x] += 1 for x in list(D.keys()): if x[0] == x[1]: if D[x]%2 == 1: p = True res += (D[x]//2)*4 else: res += 2*min(D[x],D[x[::-1]]) if p: return res + 2 return res
longest-palindrome-by-concatenating-two-letter-words
Python 3 Solution
mati44
0
7
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,515
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773639/python3-98-speed
class Solution: def longestPalindrome(self, words: List[str]) -> int: counter = collections.Counter(words) ans1, ans2, ans3 = 0, 0, False for i in list(counter): r = i[::-1] if i == r: ans2 += (counter[i] // 2) ans3 |= (counter[i] % 2) else: v = min(counter[i], counter[r]) ans1 += (2*v) counter[i] -= v counter[r] -= v return ans1*2+ans2*4+(2 if ans3 else 0)
longest-palindrome-by-concatenating-two-letter-words
python3, 98% speed
pjy953
0
10
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,516
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773627/3-hash-Solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: pair1, pair2, same = dict(), dict(), dict() for word in words: # case2, making "cc" dict(same) if len(set(word))==1: if word not in same: same[word] = 1 else: same[word] += 1 # case1, making "ab" dict(pair1) & "ba" dict(pair2) # if word already in pair2, then add 1 in pair2[word] elif word in pair2: pair2[word] += 1 else: # basic case, add 1 in pair1[word] if word not in pair1: pair1[word] = 1 else: pair1[word] += 1 # if word.reverse() not in pair2, then init to 0 in pair2[word] if word[::-1] not in pair2: pair2[word[::-1]] = 0 ans = 0 # calculate case1 : "ab" & "ba" for k, v in pair1.items(): ans += min(v, pair2[k[::-1]])*4 # calculate case2 : "cc" remain1 = False # check if there is any remaining "cc" for v in same.values(): ans += v//2*4 if v%2: # if any count("cc") is odd remain1 = True return ans+2 if remain1 else ans
longest-palindrome-by-concatenating-two-letter-words
3 hash Solution
child70370636
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,517
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773569/Simple-intuitive-solution-with-HashMap-counter-O(n)
class Solution: def longestPalindrome(self, words: List[str]) -> int: max_length = 0 word_counts = Counter() middles = set() for word in words: revword = word[::-1] if word_counts[revword] > 0: word_counts[revword] -= 1 max_length += 2 * 2 if revword == word: middles.remove(word) else: word_counts[word] += 1 if revword == word: middles.add(word) if middles: max_length += 2 return max_length
longest-palindrome-by-concatenating-two-letter-words
Simple intuitive solution with HashMap counter, O(n)
romansalin
0
8
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,518
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773478/Python3-Commented-and-Readable-Hashmap
class Solution: def longestPalindrome(self, words: List[str]) -> int: # we should go through each of the words and # check whether it is a palindrome itself or # we have a pair that forms a palindrome palindromes = set() opened = collections.Counter() result = 0 for idx, word in enumerate(words): # check whether it is in open pairs if opened[word] > 0: # we found a pair and can attach it to # the palindromes # also decrease the counter result += 4 opened[word] -= 1 # put it in opened pairs else: opened[word[::-1]] += 1 # check whether it self is a palindrome if word[1] == word[0]: palindromes.add(word) # check whether there is still one palindrome left return result + (2 if any(opened[pal] > 0 for pal in palindromes) else 0)
longest-palindrome-by-concatenating-two-letter-words
[Python3] - Commented and Readable Hashmap
Lucew
0
10
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,519
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773363/Python-or-beats-99-or-using-Counter-(dictionary)
class Solution: def longestPalindrome(self, words: List[str]) -> int: count = Counter(words) length = 0 central_word = False for key,value in count.items(): if key[0] == key[1]: if value%2 != 0: if central_word == False: length += value * 2 central_word = True else: length += (value - 1) * 2 else: length += value * 2 else: reversed_word = key[1] + key[0] if reversed_word in count and count[reversed_word] > 0: n = min(value, count[reversed_word]) length += n * 4 count[key] = 0 count[reversed_word] = 0 return length
longest-palindrome-by-concatenating-two-letter-words
Python | beats 99% | using Counter (dictionary)
anandanshul001
0
11
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,520
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773228/Python-(Faster-than-93)-or-O(N)-solution-using-HashMap
class Solution: def longestPalindrome(self, words: List[str]) -> int: wordCount = {} for word in words: wordCount[word] = wordCount.get(word, 0) + 1 palinLen = 0 for w in wordCount: if w == w[::-1]: if wordCount[w] % 2 == 0: palinLen += 2 * wordCount[w] wordCount[w] = 0 else: palinLen += 2 * (wordCount[w] - 1) wordCount[w] = 1 elif w[::-1] in wordCount: reflection = min(wordCount[w], wordCount[w[::-1]]) palinLen += reflection * 4 wordCount[w] -= reflection wordCount[w[::-1]] -= reflection for w in wordCount: if w == w[::-1] and wordCount[w] == 1: palinLen += 2 break return palinLen
longest-palindrome-by-concatenating-two-letter-words
Python (Faster than 93%) | O(N) solution using HashMap
KevinJM17
0
5
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,521
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773224/Simple-Descriptive-oror-Python-solution-oror-For-New-coders
class Solution: def longestPalindrome(self, words: List[str]) -> int: dict_2 = {} d = {} count = 0 # creating main_dictonary for i in range(0, len(words)): if words[i] not in d: d.update({words[i]: 1}) elif words[i] in d: d[words[i]] += 1 # creating new same_letter dict, as the operations performed on same_letter &amp; diff_letter dicts are different for k, v in d.items(): if k[0] == k[1]: dict_2.update({k: v}) # deleting same_letter dict from main dict. for key in dict_2.keys(): del d[key] # if same_letter dict has more than one key->value pairs than, # we will check for the no of keys with odd values. # if only 1 key has odd value and other keys have even value then we add twice as all the values # if more than 1 keys have odd values than we add twice as all the even values and max_odd value from all the odds. if len(dict_2) > 1: odd_counter = 0 for k, v in dict_2.items(): if dict_2[k] % 2 != 0: odd_counter += 1 if odd_counter > 1: max_odd_val = 0 for k, v in dict_2.items(): if dict_2[k] % 2 == 0: count += 2 * dict_2[k] else: if max_odd_val < dict_2[k]: max_odd_val = dict_2[k] pass_count = 0 for k, v in dict_2.items(): if dict_2[k] == max_odd_val and pass_count == 0: count += 2 * max_odd_val pass_count += 1 elif dict_2[k] % 2 != 0 or ( dict_2[k] == max_odd_val and pass_count != 0 ): count += 2 * (dict_2[k]) - 2 elif odd_counter == 1: for k, v in dict_2.items(): count += 2 * dict_2[k] elif odd_counter == 0: for k, v in dict_2.items(): count += 2 * dict_2[k] else: for k, v in dict_2.items(): count += 2 * dict_2[k] # here, we have diff_letter dict, # we will double nest loop for checking the reverse keys pairs ex-> 'ab':3 and 'ba':5 # if we find them, we will decrease value till one of thier values becomes 0, for above it will be -> 'ab':0 and 'ba':2 for k1, v1 in d.items(): for k2, v2 in d.items(): if k1[0] == k2[1] and k1[1] == k2[0]: while d[k1] > 0 and d[k2] > 0: d[k1] -= 1 d[k2] -= 1 count += 4 return count
longest-palindrome-by-concatenating-two-letter-words
✅ Simple Descriptive ||🐍 Python solution 🐍|| For New coders
1905761
0
4
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,522
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773155/Easy-to-understand-or-Python-or-dictionary
class Solution: def longestPalindrome(self, words: List[str]) -> int: dict_word=defaultdict(int) for i,word in enumerate(words): dict_word[word]+=1 ans=0 visited=set() odd_val=False for word in dict_word.keys(): if word not in visited: if word[0]!=word[1]: visited.add(word) if word[::-1] in dict_word: ans+=4*min(dict_word[word],dict_word[word[::-1]]) visited.add(word[::-1]) elif word[0]==word[1] and dict_word[word]%2==0: #if even number of times, then all considered ans+=2*dict_word[word] elif word[0]==word[1] and dict_word[word]%2!=0: #if odd times present, we need to remeber that #time-1 will always be present for all odd letters and set odd_val as True. odd_val=True ans+=2*(dict_word[word]-1) if odd_val: #as there is occurence of odd count, we will add 1 word with same leeters, which occurs idd #times ans+=2 return ans
longest-palindrome-by-concatenating-two-letter-words
Easy to understand | Python | dictionary
ankush_A2U8C
0
7
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,523
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773057/Python-O(n)-solution-Accepted
class Solution: def longestPalindrome(self, words: List[str]) -> int: hash_map = collections.Counter(words) ans = 0 central = 0 for word, cnt in hash_map.items(): if word[0] == word[1]: ans += cnt if cnt % 2 == 0 else cnt - 1 central |= cnt % 2 != 0 elif word[::-1] in hash_map: ans += min(cnt, hash_map[word[::-1]]) return (ans + central) * 2
longest-palindrome-by-concatenating-two-letter-words
Python O(n) solution [Accepted]
lllchak
0
5
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,524
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773036/Python3-Counting-the-reversed-word-%3A%3A-1-%3A-)
class Solution: def longestPalindrome(self, words: List[str]) -> int: mpp = defaultdict(lambda : 0) cnt = 0 for word in words: mpp[word]+=1 for word in words: if word in mpp and word[::-1] in mpp and mpp[word] != 0 and mpp[word[::-1]] != 0: if word[0] == word[1]: if mpp[word] > 1: cnt += 4 mpp[word] -= 2 else: cnt += 4 mpp[word] -= 1 mpp[word[::-1]] -= 1 for key in mpp: if mpp[key] >= 1: if key[0] == key[1]: cnt += 2 break return cnt
longest-palindrome-by-concatenating-two-letter-words
Python3 Counting the reversed word [::-1] :-)
DigantaC
0
6
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,525
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2773015/oror-Python-3-oror-hashing-oror-Easy-to-understand
class Solution: def longestPalindrome(self, words: List[str]) -> int: word_dict = {} ans = 0 center = False for item in words: word_dict[item] = word_dict.get(item, 0) + 1 for item in word_dict: reverse = item[::-1] if item[0] == item[1]: if word_dict[item] % 2 == 0: ans += word_dict[item] else: ans += (word_dict[item] - 1) center = True elif reverse in word_dict: reverse_count = word_dict[reverse] item_count = word_dict[item] ans += min(reverse_count, item_count) if center: ans += 1 return ans * 2
longest-palindrome-by-concatenating-two-letter-words
|| Python 3 || hashing || Easy to understand
parth_panchal_10
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,526
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772961/Python-or-Greedy-count-solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: s = defaultdict(int) for w in words: s[w] += 1 used = set() ans = 0 for word in s: if word in used: continue if word[0] != word[1]: if word[::-1] in s: ans += min(s[word]*2, s[word[::-1]]*2)*2 used.add(word) used.add(word[::-1]) else: carry = s[word] - 1 if s[word] % 2 else s[word] ans += carry*2 for word, val in s.items(): if word[0] == word[1] and val % 2: ans += 2 break return ans
longest-palindrome-by-concatenating-two-letter-words
Python | Greedy count solution
LordVader1
0
12
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,527
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772931/Space-optimized-2-Hashmap-based-solution-in-Python
class Solution: # Intuitive 2-Hashmap based solution def longestPalindrome(self, words: List[str]) -> int: mapper = defaultdict(int) seen = defaultdict(int) # Check for eligible words that can make a palindrome for word in words: if word[::-1] in seen and seen[word[::-1]] > 0: mapper[word] += 1 seen[word[::-1]] -= 1 else: seen[word] += 1 # Each word in mapper will give the res a 4 length palindrome adding palindromes in the right way # gives another palindrome of double length # Hence adding the length * 4 to res res = 0 for _, cnt in mapper.items(): res += cnt * 4 # Now seen has words which were in the words list and if we have some leftover # which is a palindrome in itself we can place it in the middle to increase the overall length by 2 # This can only be done once and hence i have exited the loop once i achieve this for word in seen: if seen[word] > 0 and word == word[::-1]: res += 2;break return res
longest-palindrome-by-concatenating-two-letter-words
Space optimized 2 Hashmap based solution in Python
shiv-codes
0
6
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,528
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772929/Hashmap-Fast-and-Easy-Solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: c = Counter(words) found = 0 temp = 0 for word in c.keys(): if word == word[::-1]: if c[word] % 2 == 1: found = 2 temp += (c[word] // 2 * 4) else: temp += min(c[word], c[word[::-1]]) * 2 return temp + found
longest-palindrome-by-concatenating-two-letter-words
Hashmap - Fast and Easy Solution
user6770yv
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,529
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772926/Easy-to-follow-python-3-Counter-Greedy-Solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: wordsCounter = collections.Counter(words) longestSameChar = 0 longestNonSameChar = 0 for word in wordsCounter: if word[0] == word[1]: if wordsCounter[word] == 1: if longestSameChar < 4: longestSameChar = 2 elif (longestSameChar//2) % 2 == 0: longestSameChar += 2 else: if (longestSameChar//2) % 2 == 1: longestSameChar += 2 * (wordsCounter[word] - wordsCounter[word] % 2) else: longestSameChar += 2 * wordsCounter[word] else: if word[::-1] in wordsCounter and wordsCounter[word[::-1]] != 0: minCounter = min(wordsCounter[word[::-1]], wordsCounter[word]) longestNonSameChar += 4 * minCounter wordsCounter[word[::-1]] -= minCounter wordsCounter[word] -= minCounter return longestSameChar + longestNonSameChar
longest-palindrome-by-concatenating-two-letter-words
Easy to follow python 3 - Counter, Greedy Solution
zxia545
0
4
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,530
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772722/python3-Solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: freq = Counter(words) # obtain frequencies pp, p = 0, 0 for w, f in freq.items(): if w[0] == w[1]: p = max(p, f % 2) # odd-count symmetric word detector pp += f//2 * 2 # count paired symmetric words else: pp += min(f, freq[w[::-1]]) # count paired asymmetric words return (pp + p) * 2
longest-palindrome-by-concatenating-two-letter-words
python3 Solution
rupamkarmakarcr7
0
12
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,531
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772696/python-solution-or-counter
class Solution: def longestPalindrome(self, words: List[str]) -> int: res = 0 mid = 0 counter = Counter(words) for key in counter.keys(): reverse = key[::-1] if reverse in counter: if key != reverse: res += 2 * min(counter[key], counter[reverse]) else: if counter[key] > 1: res += 4 * (counter[key]//2) if counter[key] % 2 == 1: mid = 2 return mid + res
longest-palindrome-by-concatenating-two-letter-words
python solution | counter
maomao1010
0
8
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,532
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772617/Easy-Python-or-Faster-or-Dictionary-%2B-Counter-or-O(n)-Time-or-O(n)-Space
class Solution: def longestPalindrome(self, words: List[str]) -> int: Map = Counter(words) ans = 0 center = False for word, count in Map.items(): if word[0]==word[1]: if count%2==0: ans += count else: ans += count-1 center = True elif word[0]<word[1]: ans += 2*min(count, Map[word[1]+word[0]]) if center: ans+=1 return 2*ans
longest-palindrome-by-concatenating-two-letter-words
Easy Python | Faster | Dictionary + Counter | O(n) Time | O(n) Space
coolakash10
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,533
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772545/Python3-Look-for-mirrored-entries
class Solution: def longestPalindrome(self, words: List[str]) -> int: single_found = False c = Counter(words) pairs = 0 for k in list(c.keys()): if c[k]<1: continue a, b = k[0], k[1] if a==b: if c[k]%2==1: single_found = True pairs+=c[k]//2 else: ns = (b+a) pairs += min(c[ns], c[k]) c[ns]=0 pairs *= 4 if single_found: pairs += 2 return pairs
longest-palindrome-by-concatenating-two-letter-words
Python3 Look for mirrored entries
godshiva
0
5
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,534
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772478/Python-Solution-With-Dictionary
class Solution: def longestPalindrome(self, words: List[str]) -> int: d = Counter(words) di = {} s = set() ans = 0 c = 0 for k,v in d.items(): # If any word is pallindrom store it in a different dictionary if k == k[::-1]: di[k] = v elif k[::-1] in d and k[::-1] not in s: ans += min(v,d[k[::-1]]) * 2 s.add(k[::-1]) # Sort the second dictionay according to frquency of words. # The first word has always maximum frequency. di = dict(sorted(di.items(),key = lambda x:x[1])[::-1]) od = 0 for k,v in di.items(): if c == 0: if v % 2 == 1: od += 1 ans += v * 2 c += 1 else: if v % 2 == 1 and od == 0: ans += v * 2 od += 1 elif v % 2 == 1 and od == 1: ans += (v - 1) * 2 else: ans += v * 2 return ans
longest-palindrome-by-concatenating-two-letter-words
Python Solution With Dictionary
a_dityamishra
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,535
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772448/Python-Counter-Aprroach-using-Set
class Solution: def longestPalindrome(self, words: List[str]) -> int: word_map = collections.Counter(words) odd_dbl_in_words, count = 0, 0 for word in set(words): if word[0] == word[1]: if word_map[word] % 2 == 0: count += 2 * word_map[word] else: odd_dbl_in_words = 1 count += 2 * (word_map[word] - 1) else: count += 2 * min(word_map[word], word_map[word[::-1]]) return count + odd_dbl_in_words * 2
longest-palindrome-by-concatenating-two-letter-words
Python Counter Aprroach using Set
gkpani97
0
18
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,536
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772442/Python-easy-to-read-and-understand-or-hashmap
class Solution: def longestPalindrome(self, words: List[str]) -> int: m = collections.defaultdict(int) res = 0 for word in words: if word[::-1] in m and m[word[::-1]] > 0: res += 4 m[word[::-1]] -= 1 else: m[word] += 1 for word in words: if word[0] == word[1] and m[word] == 1: res += 2 break return res
longest-palindrome-by-concatenating-two-letter-words
Python easy to read and understand | hashmap
sanial2001
0
8
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,537
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772425/WEEB-EXPLAINS-PYTHONC%2B%2B
class Solution: def longestPalindrome(self, words: List[str]) -> int: memo = Counter(words) visited = set() result = 0 flag = False for word, count in memo.items(): if word in visited: continue reverse = word[::-1] if reverse in memo: if reverse == word: if memo[word] % 2 == 1 and not flag: result += 2 * memo[word] flag = True elif memo[word] % 2 == 1 and flag: result += 2 * (memo[word] - 1) else: result += 2 * memo[word] else: result += 4 * min(memo[word], memo[reverse]) visited.add(reverse) return result
longest-palindrome-by-concatenating-two-letter-words
WEEB EXPLAINS PYTHON/C++
Skywalker5423
0
6
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,538
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772380/Simple-Python-Solution-Hashmaps
class Solution: def longestPalindrome(self, words: List[str]) -> int: hm=collections.defaultdict(lambda:0) res=0 for i in words: tmp=i[::-1] if hm[tmp]>=1: hm[tmp]-=1 res+=4 else: hm[i]+=1 for i in hm: if hm[i]>=1: if i[0]==i[1]: res+=2 break print(hm,res) return res
longest-palindrome-by-concatenating-two-letter-words
Simple Python Solution - Hashmaps
umarfarooqngm
0
6
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,539
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772277/Python3-or-intuitive-approach-or-hashmap
class Solution: def longestPalindrome(self, words: List[str]) -> int: hashmap = {} result = 0 picked = False for i in range(len(words)): hashmap[words[i]] = hashmap.get(words[i],0)+1 for word in words: revword = word[::-1] if word == revword and word in hashmap and hashmap[word] == 1: picked = True #Can be picked and added in the center' if word == revword and word in hashmap and hashmap[word] >= 2 : picked = False result += 4 #adding both revword and word count hashmap[word] -= 2 if hashmap[word] == 0: del hashmap[word] if word in hashmap and revword in hashmap and word != revword: result += 4 hashmap[word] -= 1 hashmap[revword] -= 1 if hashmap[word] == 0: del hashmap[word] if hashmap[revword] == 0: del hashmap[revword] if not result and not picked: return 0 if result and picked: return (result + 2) if result and not picked: return result if not result and picked: return 2
longest-palindrome-by-concatenating-two-letter-words
Python3 | intuitive approach | hashmap
Brutal7skull
0
13
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,540
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772227/Python-Intuitive-and-Easy-solution
class Solution: def longestPalindrome(self, words: List[str]) -> int: res = 0 oddFlag = False freq = {} for word in words: freq[word] = freq.get(word, 0) + 1 for word, frequency in freq.items(): if word[0] == word[1]: if frequency % 2 == 0: res += frequency else: oddFlag = True res += frequency - 1 elif word[0] < word[1]: res += 2 * min(frequency, freq.get(word[1] + word[0], 0)) if oddFlag: res += 1 return 2 * res
longest-palindrome-by-concatenating-two-letter-words
Python Intuitive and Easy solution
MaverickEyedea
0
10
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,541
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772211/Python-O(n)
class Solution: def longestPalindrome(self, words: List[str]) -> int: memo = defaultdict(int) for w in words: memo[w] += 1 added = 1 res = 0 for w in words: if memo[w] > 0: w_needed = w[1] + w[0] memo[w] -= 1 if memo[w_needed] > 0: res += 4 memo[w_needed] -= 1 elif w == w_needed and added == 1: added = 0 res += 2 return res
longest-palindrome-by-concatenating-two-letter-words
Python O(n)
chingisoinar
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,542
https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772154/Python3-or-Greedy-%2B-Counter-(hashmap)
class Solution: def longestPalindrome(self, words: List[str]) -> int: palindromicPairsFinder = collections.Counter(); count = 0 for word in words: reversedWord = word[::-1] if palindromicPairsFinder[reversedWord] > 0: count += 1 palindromicPairsFinder[reversedWord] -= 1 else: palindromicPairsFinder[word] += 1 return 2 * (2 * count + any(word[0] == word[1] for word in palindromicPairsFinder if palindromicPairsFinder[word] > 0))
longest-palindrome-by-concatenating-two-letter-words
Python3 | Greedy + Counter (hashmap)
sr_vrd
0
9
longest palindrome by concatenating two letter words
2,131
0.491
Medium
29,543
https://leetcode.com/problems/stamping-the-grid/discuss/2489712/Python3-solution%3A-faster-than-most-submissions-oror-Very-simple
class Solution: def prefix_sum(self, grid: List[List[int]]) -> List[List[int]]: ps = [[grid[row][col] for col in range(len(grid[0]))]for row in range(len(grid))] for row in range(len(grid)): for col in range(1, len(grid[0])): ps[row][col] = ps[row][col-1] + grid[row][col] for row in range(1, len(grid)): for col in range(len(grid[0])): ps[row][col] = ps[row-1][col] + ps[row][col] return ps def sumRegion(self, ps, row1: int, col1: int, row2: int, col2: int) -> int: ans = 0 if row1 == 0 and col1 == 0: ans = ps[row2][col2] elif row1 == 0: ans = ps[row2][col2] - ps[row2][col1-1] elif col1 == 0: ans = ps[row2][col2] - ps[row1-1][col2] else: ans = ps[row2][col2] - ps[row1-1][col2] - ps[row2][col1-1] + ps[row1-1][col1-1] return ans def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool: diff = [[0 for col in range(len(grid[0])+1)]for row in range(len(grid)+1)] ps = self.prefix_sum(grid) cover = 0 for row in range(len(grid)-(stampHeight-1)): for col in range(len(grid[0])-(stampWidth-1)): sub_sum = self.sumRegion(ps, row, col, row+stampHeight-1, col+stampWidth-1) if sub_sum == 0: diff[row][col] += 1 diff[row][col+stampWidth] -= 1 diff[row+stampHeight][col] -= 1 diff[row+stampHeight][col+stampWidth] = 1 pref_diff = self.prefix_sum(diff) m, n = len(grid), len(grid[0]) for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == 0 and pref_diff[row][col] == 0: return False return True
stamping-the-grid
✔️ Python3 solution: faster than most submissions || Very simple
Omegang
0
40
stamping the grid
2,132
0.309
Hard
29,544
https://leetcode.com/problems/stamping-the-grid/discuss/1684292/Python3-prefix-sum
class Solution: def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool: m, n = len(grid), len(grid[0]) prefix = [[0]*(n+1) for _ in range(m+1)] for i in range(m): for j in range(n): prefix[i+1][j+1] = grid[i][j] + prefix[i+1][j] + prefix[i][j+1] - prefix[i][j] seen = [[0]*n for _ in range(m)] for i in range(m-stampHeight+1): for j in range(n-stampWidth+1): diff = prefix[i+stampHeight][j+stampWidth] - prefix[i+stampHeight][j] - prefix[i][j+stampWidth] + prefix[i][j] if diff == 0: seen[i][j] = 1 prefix = [[0]*(n+1) for _ in range(m+1)] for i in range(m): for j in range(n): prefix[i+1][j+1] = seen[i][j] + prefix[i+1][j] + prefix[i][j+1] - prefix[i][j] for i in range(m): ii = max(0, i-stampHeight+1) for j in range(n): jj = max(0, j-stampWidth+1) if grid[i][j] == 0 and prefix[i+1][j+1] - prefix[i+1][jj] - prefix[ii][j+1] + prefix[ii][jj] == 0: return False return True
stamping-the-grid
[Python3] prefix sum
ye15
0
82
stamping the grid
2,132
0.309
Hard
29,545
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1775747/Python-3-or-7-Line-solution-or-87-Faster-runtime-or-92.99-lesser-memory
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: lst = [0]*len(matrix) for i in matrix: if len(set(i)) != len(matrix): return False for j in range(len(i)): lst[j] += i[j] return len(set(lst)) == 1
check-if-every-row-and-column-contains-all-numbers
✔Python 3 | 7 Line solution | 87% Faster runtime | 92.99% lesser memory
Coding_Tan3
6
855
check if every row and column contains all numbers
2,133
0.53
Easy
29,546
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1684643/A-simple-and-CORRECT-XOR-method
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: # bitmask n = len(matrix) for i in range(n): row_bit, col_bit, bitmask = 1, 1, 1 for j in range(n): row_bit ^= 1 << matrix[i][j] col_bit ^= 1 << matrix[j][i] bitmask |= 1 << j + 1 if row_bit ^ bitmask or col_bit ^ bitmask: return False return True
check-if-every-row-and-column-contains-all-numbers
A simple and CORRECT XOR method
pwang72
5
415
check if every row and column contains all numbers
2,133
0.53
Easy
29,547
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1684643/A-simple-and-CORRECT-XOR-method
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: # bitmask n = len(matrix) for i in range(n): row_bit, col_bit, bitmask = 1, 1, 1 for j in range(n): row_bit ^= 1 << matrix[i][j] col_bit ^= 1 << matrix[j][i] bitmask |= 1 << j + 1 if row_bit ^ bitmask or col_bit ^ bitmask: return False return True
check-if-every-row-and-column-contains-all-numbers
A simple and CORRECT XOR method
pwang72
5
415
check if every row and column contains all numbers
2,133
0.53
Easy
29,548
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1676835/Python3-1-line
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: return all(len(set(row)) == len(matrix) for row in matrix) and all(len(set(col)) == len(matrix) for col in zip(*matrix))
check-if-every-row-and-column-contains-all-numbers
[Python3] 1-line
ye15
4
838
check if every row and column contains all numbers
2,133
0.53
Easy
29,549
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1975051/Python-easy-or-Set-or-98-faster-and-memory-efficient
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: for r in range(len(matrix)): colSet = set() rowSet = set() for c in range(len(matrix)): if matrix[r][c] in colSet or matrix[c][r] in rowSet: return False colSet.add(matrix[r][c]) rowSet.add(matrix[c][r]) return True
check-if-every-row-and-column-contains-all-numbers
Python easy | Set | 98% faster and memory efficient
CSociety
3
233
check if every row and column contains all numbers
2,133
0.53
Easy
29,550
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2777852/use-DP-tabulation
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: dp_col = [[False for _ in range(len(matrix[0]))] for _ in range(len(matrix))] dp_row = [[False for _ in range(len(matrix[0]))] for _ in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): if dp_row[i][matrix[i][j]-1] or dp_col[j][matrix[i][j]-1]: return False dp_row[i][matrix[i][j]-1] = True dp_col[j][matrix[i][j]-1] = True return True
check-if-every-row-and-column-contains-all-numbers
use DP tabulation
harrychen1995
1
5
check if every row and column contains all numbers
2,133
0.53
Easy
29,551
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2077833/Python-Solution
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) vaild = set(range(1, n + 1)) for i in range(n): set1, set2 = set(), set() for j in range(n): set1.add(matrix[i][j]) set2.add(matrix[j][i]) if set1 != vaild or set2 != vaild: return False return True
check-if-every-row-and-column-contains-all-numbers
Python Solution
hgalytoby
1
151
check if every row and column contains all numbers
2,133
0.53
Easy
29,552
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2077833/Python-Solution
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) valid = set(range(1, n + 1)) return all(set(m) == valid for m in matrix + list(zip(*matrix)))
check-if-every-row-and-column-contains-all-numbers
Python Solution
hgalytoby
1
151
check if every row and column contains all numbers
2,133
0.53
Easy
29,553
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2848414/Easy-and-understandable-solution-beats-99.2
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: N = len(matrix) for row in matrix: if len(set(row)) != N: return False for i in range(N): for j in range(N): if i < j: matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for row in matrix: if len(set(row)) != N: return False return True
check-if-every-row-and-column-contains-all-numbers
Easy and understandable solution beats 99.2%
MaxYazev
0
2
check if every row and column contains all numbers
2,133
0.53
Easy
29,554
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2842805/Set-or-Python3
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: tran_matrix = list(zip(*matrix)) n = len(matrix) mat_sum = 0.5 * n * (n + 1) for i in range(n): s_1 = set(matrix[i]) s_2 = set(tran_matrix[i]) if len(s_1) != n or len(s_2) != n or sum(s_1) != mat_sum or sum(s_2) != mat_sum : return False return True
check-if-every-row-and-column-contains-all-numbers
Set | Python3
user8403D
0
3
check if every row and column contains all numbers
2,133
0.53
Easy
29,555
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2841145/python-code
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: for row in matrix: if set(row)!=set(range(1,len(matrix)+1)): return False for col in zip(*matrix): if set(col)!=set(range(1,len(matrix)+1)): return False return True
check-if-every-row-and-column-contains-all-numbers
python code
ayushigupta2409
0
5
check if every row and column contains all numbers
2,133
0.53
Easy
29,556
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2841115/Simple-solution-by-using-hashmap
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) for i in range(n): dic1 = {} dic2 = {} for j in range(n): if matrix[i][j] not in dic1: dic1[matrix[i][j]] = 1 else: return False if matrix[j][i] not in dic2: dic2[matrix[j][i]] = 1 else: return False return True
check-if-every-row-and-column-contains-all-numbers
Simple solution by using hashmap
Tonmoy-saha18
0
3
check if every row and column contains all numbers
2,133
0.53
Easy
29,557
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2840827/PythonTypescriptJavascript-Simple-intuitive-easy-to-understand-approach-(100-faster)
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) for i in range(0,n): arr = [False] * (n+1) arr[0] = None for j in range(0,n): num = matrix[i][j] if num >= 1 and num <= n: arr[num] = True for k in arr: if k == False: return False for i in range(0,n): arr = [False] * (n+1) arr[0] = None for j in range(0,n): num = matrix[j][i] if num >= 1 and num <= n: arr[num] = True for k in arr: if k == False: return False return True
check-if-every-row-and-column-contains-all-numbers
[Python/Typescript/Javascript] Simple, intuitive, easy-to-understand approach (100% faster)
KarmaRekts
0
2
check if every row and column contains all numbers
2,133
0.53
Easy
29,558
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2840469/Beats-90-Python3-Easy-to-understand-with-comments!
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: # We need to check each row and column, and keep track that each number from 1-n is included in each. n = len(matrix) valid_set = set() # Add valid numbers from 1 to n for i in range(1, n + 1): valid_set.add(i) # Check each row for i in range(0, n): curr_row_seen = set() for j in range(0, n): curr = matrix[i][j] if curr not in valid_set or curr in curr_row_seen: return False curr_row_seen.add(curr) for i in range(0, n): curr_column_seen = set() for j in range(0, n): curr = matrix[j][i] if curr not in valid_set or curr in curr_column_seen: return False curr_column_seen.add(curr) return True
check-if-every-row-and-column-contains-all-numbers
Beats 90% Python3 Easy to understand with comments!
BlueBoi904
0
1
check if every row and column contains all numbers
2,133
0.53
Easy
29,559
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2746168/Check-every-rows-and-colums.
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: """Constraint of n is small, so BF is ok. TC is O(n^2), SC is O(n^2)""" n = len(matrix) for row in matrix: if len(set(row)) != n: return False for col_idx in range(n): column = [row[col_idx] for row in matrix] if len(set(column)) != n: return False return True
check-if-every-row-and-column-contains-all-numbers
Check every rows and colums.
woora3
0
3
check if every row and column contains all numbers
2,133
0.53
Easy
29,560
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2691004/Python-easy-updated-solution-using-Zip
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) for item in matrix: if(n != len(set(item))): return False for i in zip(*matrix): if(n != len(set(i))): return False return True
check-if-every-row-and-column-contains-all-numbers
Python easy updated solution using Zip
user2800NJ
0
13
check if every row and column contains all numbers
2,133
0.53
Easy
29,561
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2492289/Python-simple-solution-using-a-hashset
class Solution: def checkValid(self, matrix: list[list[int]]) -> bool: n = len(matrix) matrix_cols = [[matrix[i][j] for i in range(len(matrix))] for j in range(len(matrix[0]))] def has_all_nums(nums: list[int]) -> bool: nums_needed = set(range(1,n+1)) for num in nums: nums_needed.discard(num) return len(nums_needed) == 0 for row, col in zip(matrix, matrix_cols): if not has_all_nums(row) or not has_all_nums(col): return False return True
check-if-every-row-and-column-contains-all-numbers
Python simple solution using a hashset
xgmichael
0
55
check if every row and column contains all numbers
2,133
0.53
Easy
29,562
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2492289/Python-simple-solution-using-a-hashset
class Solution: def checkValid(self, matrix: list[list[int]]) -> bool: n = len(matrix) row_nums: set[int] = set() col_nums: set[int] = set() for i in range(len(matrix)): row_nums.clear() col_nums.clear() for j in range(len(matrix[0])): row_nums.add(matrix[j][i]) col_nums.add(matrix[i][j]) if len(row_nums) != n or len(col_nums) != n: return False return True
check-if-every-row-and-column-contains-all-numbers
Python simple solution using a hashset
xgmichael
0
55
check if every row and column contains all numbers
2,133
0.53
Easy
29,563
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2467929/Python-Solution-or-Easy-and-Straightforward-Logic-or-Store-and-Check-or-Clean-Code
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: # define N n = len(matrix) # generate set of [1,N] store = set([i for i in range(1,n+1)]) # check in row for row in matrix: if set(row) != store: return False # check in column for col in zip(*matrix): if set(col) != store: return False # all good return True
check-if-every-row-and-column-contains-all-numbers
Python Solution | Easy and Straightforward Logic | Store and Check | Clean Code
Gautam_ProMax
0
71
check if every row and column contains all numbers
2,133
0.53
Easy
29,564
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2068671/Python-Easy-Understanding-or-Using-Set
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: # check in the row for i in range(len(matrix)): if len(matrix[i]) != len(set(matrix[i])): return False #chaeck in the column for i in range(len(matrix)): st=set() lt=[] for j in range(len(matrix)): st.add(matrix[j][i]) lt.append(matrix[j][i]) if len(st) != len(lt): return False return True
check-if-every-row-and-column-contains-all-numbers
[Python] Easy Understanding | Using Set 💥
imjenit
0
121
check if every row and column contains all numbers
2,133
0.53
Easy
29,565
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/2011111/Python-O(1)-space-single-pass-no-sorting-needed
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) for i in range(n): for j in range(n): # take absolute value since mod of a positive number is different from mod of its negative counterpart val = abs(matrix[i][j])%n # We'll mark the val-th element as negative once some "val" appears in a row i if matrix[i][val] < 0: return False # Make element negative to save the occurance of "val" in row i matrix[i][val] *= -1 # We'll make the absolute value of j-th element for row "val" greater than n to mark that "val" appeared in the column if abs(matrix[val][j]) > n: return False # Change the absolute value to mark the occurance of "val" in column j # Reduce n if negative, add n if positive. Don't add a negative and positive, since the absolute value will change if matrix[val][j] < 0: matrix[val][j] -= n else: matrix[val][j] += n return True
check-if-every-row-and-column-contains-all-numbers
Python O(1) space, single pass, no sorting needed
code_rookie
0
92
check if every row and column contains all numbers
2,133
0.53
Easy
29,566
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1992162/Python3-99-Faster-oror-100-Memory-efficient
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: N = len(matrix) arr = [i+1 for i in range(N)] #print(arr) for i in range(N): if sorted(matrix[i]) != arr: return False for i in range(N): temp = [] for j in range(N): temp.append(matrix[j][i]) if sorted(temp) != arr: return False return True
check-if-every-row-and-column-contains-all-numbers
Python3 - 99% Faster || 100% Memory efficient
dayaniravi123
0
78
check if every row and column contains all numbers
2,133
0.53
Easy
29,567
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1982596/Python3-one-line-faster-than-96.94-(757ms)
class Solution: def checkValid(self, matrix: list[list[int]]) -> bool: n = len(matrix) return all(set(matrix[i]) == set(range(1, n+1)) for i in range(n)) and all(set(matrix[i][j] for i in range(n)) == set(range(1,n+1)) for j in range(n))
check-if-every-row-and-column-contains-all-numbers
Python3 one-line faster than 96.94% (757ms)
Minh4893IT
0
105
check if every row and column contains all numbers
2,133
0.53
Easy
29,568
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1957724/Python3-or-Simple-or-93-Faster-runtime-or-O(1)-Space
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) def not_valid(block): return len(set(block)) != len(block) if any( not_valid([matrix[i][j] for j in range(n)]) or not_valid([matrix[j][i] for j in range(n)]) for i in range(n)): return False return True
check-if-every-row-and-column-contains-all-numbers
✅Python3 | Simple | 93% Faster runtime | O(1) Space
PaulOkewunmi
0
53
check if every row and column contains all numbers
2,133
0.53
Easy
29,569
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1940883/Python-dollarolution-(97-Faster)
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: m = list(zip(*matrix)) k = len(matrix) for i in range(k): if len(set(matrix[i])) != k or len(set(m[i])) != k: return False return True
check-if-every-row-and-column-contains-all-numbers
Python $olution (97% Faster)
AakRay
0
76
check if every row and column contains all numbers
2,133
0.53
Easy
29,570
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1938779/Python-Simple-and-Clean!-One-Liner-%2B-Bonus%3A-Space-Efficient-Version
class Solution: def checkValid(self, matrix): expected = set(range(1,len(matrix[0])+1)) for row in matrix: if set(row) != expected: return False for col in zip(*matrix): if set(col) != expected: return False return True
check-if-every-row-and-column-contains-all-numbers
Python - Simple and Clean! One Liner + Bonus: Space Efficient Version
domthedeveloper
0
75
check if every row and column contains all numbers
2,133
0.53
Easy
29,571
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1938779/Python-Simple-and-Clean!-One-Liner-%2B-Bonus%3A-Space-Efficient-Version
class Solution: def checkValid(self, matrix): s = set(range(1,len(matrix[0])+1)) return all(set(x)==s for x in matrix+list(zip(*matrix)))
check-if-every-row-and-column-contains-all-numbers
Python - Simple and Clean! One Liner + Bonus: Space Efficient Version
domthedeveloper
0
75
check if every row and column contains all numbers
2,133
0.53
Easy
29,572
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1938779/Python-Simple-and-Clean!-One-Liner-%2B-Bonus%3A-Space-Efficient-Version
class Solution: def checkValid(self, matrix): return all(set(x)==set(range(1,len(matrix[0])+1)) for x in matrix+list(zip(*matrix)))
check-if-every-row-and-column-contains-all-numbers
Python - Simple and Clean! One Liner + Bonus: Space Efficient Version
domthedeveloper
0
75
check if every row and column contains all numbers
2,133
0.53
Easy
29,573
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1938779/Python-Simple-and-Clean!-One-Liner-%2B-Bonus%3A-Space-Efficient-Version
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: m,n = len(matrix), len(matrix[0]) # mark rows for i in range(m): for j in range(n): v = abs(matrix[i][j])-1 matrix[i][v] *= -1 # check rows for i in range(m): for j in range(n): if matrix[i][j] > 0: return False # mark cols for j in range(n): for i in range(m): v = abs(matrix[i][j])-1 matrix[v][j] *= -1 # check cols for j in range(n): for i in range(m): if matrix[i][j] < 0: return False return True
check-if-every-row-and-column-contains-all-numbers
Python - Simple and Clean! One Liner + Bonus: Space Efficient Version
domthedeveloper
0
75
check if every row and column contains all numbers
2,133
0.53
Easy
29,574
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1932328/Python-(Simple-Approach-and-Beginner-Friendly)
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: a = [] for i in matrix: if len(i) != len(set(i)): return False for j in range(0, len(matrix)): for i in range(0, len(matrix)): a.append(matrix[i][j]) if len(a) != len(set(a)): return False a = [] return True
check-if-every-row-and-column-contains-all-numbers
Python (Simple Approach and Beginner-Friendly)
vishvavariya
0
63
check if every row and column contains all numbers
2,133
0.53
Easy
29,575
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1920539/Python-Solution-Using-Reference-Set-Comparison
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: cols, n = list(zip(*matrix)), len(matrix) test = set([i for i in range(1, n + 1)]) for item1, item2 in zip(matrix, cols): if set(item1) != test or set(item2) != test: return False return True
check-if-every-row-and-column-contains-all-numbers
Python Solution Using Reference Set Comparison
Hejita
0
32
check if every row and column contains all numbers
2,133
0.53
Easy
29,576
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1831836/5-Lines-Python-Solution-oror-70-Faster-oror-Memory-less-than-82
class Solution: def checkValid(self, M: List[List[int]]) -> bool: n=len(M) ; C=list(map(list, zip(*M))) ; REF=[i+1 for i in range(n)] for i in range(n): M[i].sort() ; C[i].sort() if M[i]!=REF or C[i]!=REF: return False return True
check-if-every-row-and-column-contains-all-numbers
5-Lines Python Solution || 70% Faster || Memory less than 82%
Taha-C
0
129
check if every row and column contains all numbers
2,133
0.53
Easy
29,577
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1793525/Python-easy-to-optimized-solution
class Solution: def checkValid(self, arr: List[List[int]]) -> bool: m, n = len(arr), len(arr[0]) row = defaultdict(set) col = defaultdict(set) for i in range(m): for j in range(n): if arr[i][j] in row[i]: return False else: row[i].add(arr[i][j]) if arr[i][j] in col[j]: return False else: col[j].add(arr[i][j]) return True
check-if-every-row-and-column-contains-all-numbers
Python easy to optimized solution
abkc1221
0
93
check if every row and column contains all numbers
2,133
0.53
Easy
29,578
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1793525/Python-easy-to-optimized-solution
class Solution: def checkValid(self, arr: List[List[int]]) -> bool: m, n = len(arr), len(arr[0]) # mark rows for i in range(m): for j in range(n): pos = abs(arr[i][j]) - 1 # valid since arr[i][j] is in range[1, n] if arr[i][pos] < 0: return False arr[i][pos] *= -1 # marking for future use # mark columns for i in range(m): for j in range(n): pos = abs(arr[j][i]) - 1 # valid since arr[i][j] is in range[1, n] if arr[pos][i] > 0: return False arr[pos][i] = abs(arr[pos][i]) return True
check-if-every-row-and-column-contains-all-numbers
Python easy to optimized solution
abkc1221
0
93
check if every row and column contains all numbers
2,133
0.53
Easy
29,579
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1788076/matrix
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n = len(matrix) m = len(matrix[0]) for i in range(n): s = set() for j in range(m): if matrix[i][j] in s: return False else: s.add(matrix[i][j]) for i in range(m): s = set() for j in range(n): if matrix[j][i] in s: return False else: s.add(matrix[j][i]) return True
check-if-every-row-and-column-contains-all-numbers
matrix
lucifer_110001
0
37
check if every row and column contains all numbers
2,133
0.53
Easy
29,580
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1771978/Python-3-index-marking-O(n2)-time-O(1)-space
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: for i, row in enumerate(matrix): for j, num in enumerate(row): num = abs(num) if matrix[i][num-1] < 0: return False matrix[i][num-1] *= -1 for i, row in enumerate(matrix): for j, num in enumerate(row): num = abs(num) if matrix[num-1][j] > 0: return False matrix[num-1][j] *= -1 return True
check-if-every-row-and-column-contains-all-numbers
Python 3, index marking, O(n^2) time, O(1) space
dereky4
0
70
check if every row and column contains all numbers
2,133
0.53
Easy
29,581
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1692346/Simple-Python-solution
class Solution: def checkValid(self, M: List[List[int]]) -> bool: n = len(M) nums = set(range(1, n+1)) def match(A): return all(set(row) == nums for row in A) return match(M) and match(zip(*M))
check-if-every-row-and-column-contains-all-numbers
Simple Python solution
emwalker
0
168
check if every row and column contains all numbers
2,133
0.53
Easy
29,582
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1681975/O(k2)-time-complexity-straightforward-solution.-K-is-row-size
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: # ROW CHECK # Check if every row has unique digits, by constraint (1 <= matrix[i][j] <= n) on the problem # if they are all unique, they should be between 1 to n for a row # Quit early if false for i in range(len(matrix)): if len(set(matrix[i])) != len(matrix[i]): return False # COLUMN CHECK # Create a temporary array of columns and check if it has unique numbers # Quit early if false for col in range(len(matrix)): temp = [] for row in range(len(matrix)): temp.append(matrix[row][col]) if len(set(temp)) != len(temp): return False # If all validations succeeded, matrix is valid return True
check-if-every-row-and-column-contains-all-numbers
O(k^2) time complexity straightforward solution. K is row size
snagsbybalin
0
54
check if every row and column contains all numbers
2,133
0.53
Easy
29,583
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1677109/Python3-Beginner-friendly-Solution
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n=len(matrix) for i in range(0,len(matrix)): map=set() for j in range(0,len(matrix)): map.add(matrix[i][j]) if len(map)!=n: return False for i in range(0,len(matrix)): map=set() for j in range(0,len(matrix)): map.add(matrix[j][i]) if len(map)!=n: return False return True
check-if-every-row-and-column-contains-all-numbers
Python3 Beginner friendly Solution
aryanagrawal2310
0
157
check if every row and column contains all numbers
2,133
0.53
Easy
29,584
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1676927/Python3-Solution-oror-Easy-to-understand-oror-For-beginner
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: def column(matrix, i): return [row[i] for row in matrix] n = len(matrix) for x in range(len(matrix)): i = 1 a = column(matrix, x) while i <= n: if i not in matrix[x] or i not in a: return False else: i+=1 return True
check-if-every-row-and-column-contains-all-numbers
[Python3] Solution || Easy to understand || For beginner
Cheems_Coder
0
90
check if every row and column contains all numbers
2,133
0.53
Easy
29,585
https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1729088/Easy-to-understand-python3-solution
class Solution: def checkValid(self, matrix: List[List[int]]) -> bool: n=len(matrix) return all(len(set(row))==n for row in matrix) and all(len(set(col))==n for col in zip(*matrix))
check-if-every-row-and-column-contains-all-numbers
Easy to understand python3 solution
Karna61814
-1
59
check if every row and column contains all numbers
2,133
0.53
Easy
29,586
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1677262/Sliding-window-with-comments-Python
class Solution: def minSwaps(self, nums: List[int]) -> int: width = sum(num == 1 for num in nums) #width of the window nums += nums res = width curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width] for i in range(width, len(nums)): curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists res = min(res, curr_zeros) #update if needed return res
minimum-swaps-to-group-all-1s-together-ii
Sliding window with comments, Python
kryuki
21
645
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,587
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1793862/Python-sliding-window-O(n)
class Solution: def minSwaps(self, nums: List[int]) -> int: ones = nums.count(1) n = len(nums) res = ones start = 0 end = ones-1 zeroesInWindow = sum(num==0 for num in nums[start:end+1]) while start < n: # print(start, end , zeroesInWindow) res = min(res, zeroesInWindow) if nums[start] == 0: zeroesInWindow -= 1 start += 1 end += 1 if nums[end%n] == 0: zeroesInWindow += 1 return res
minimum-swaps-to-group-all-1s-together-ii
Python sliding window O(n)
abkc1221
2
168
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,588
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/2628378/Sliding-window-approach
class Solution: def minSwaps(self, nums: List[int]) -> int: l = r = 0 zero = 0 k = nums.count(1) + 1 #our window size #O(n) nums+=nums #double the array mi = len(nums)*3 #just random higher number while r < len(nums): if (r - l + 1) == k: #if our window size is k increment left and add the minimum size mi = min(mi, zero) if nums[l] == 0: zero-=1 l+=1 if nums[r] == 0: zero+=1 r+=1 print(mi) return mi
minimum-swaps-to-group-all-1s-together-ii
Sliding window approach
pandish
1
50
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,589
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/2516892/Python3-Solution-or-Sliding-Window-or-O(n)-Time
class Solution: def minSwaps(self, nums): n, k, ans = len(nums), nums.count(1), float('inf') c = nums[:k].count(1) for i in range(n): ans = min(ans, k - c) c += nums[(i + k) % n] - nums[i] return ans
minimum-swaps-to-group-all-1s-together-ii
✔ Python3 Solution | Sliding Window | O(n) Time
satyam2001
1
61
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,590
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1947891/python-3-oror-sliding-window-oror-O(n)O(1)
class Solution: def minSwaps(self, nums: List[int]) -> int: n, ones = len(nums), sum(nums) window = max_window = sum(nums[i] for i in range(ones)) for i in range(n - 1): window += nums[(i + ones) % n] - nums[i] max_window = max(max_window, window) return ones - max_window
minimum-swaps-to-group-all-1s-together-ii
python 3 || sliding window || O(n)/O(1)
dereky4
1
110
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,591
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1710179/Python-3-Sliding-window.-Clean-and-concise
class Solution: def minSwaps(self, nums: List[int]) -> int: # The size of the sliding window max_size = sum(nums) # Create a window of max_size and count the number of ones and zeros i, j = max_size, 0 current_ones = sum(nums[:max_size]) # Number of ones in the window. minimum_number_of_zeros = max_size - current_ones # Number of zeros in the window. WE WANT TO MINIMIZE THIS. # now we just need to add a new number from the right and remove one from the left while i < len(nums)*2: # * 2 because the array is circular # Add from the right current_ones += nums[i % len(nums)] # Remove from the left current_ones -= nums[j % len(nums)] # By writting the previous two lines we maintain the size of sliding window. # Minimize the number of zeros minimum_number_of_zeros = min(minimum_number_of_zeros, max_size - current_ones) i += 1 j += 1 return minimum_number_of_zeros
minimum-swaps-to-group-all-1s-together-ii
[Python 3] Sliding window. Clean & concise
asbefu
1
132
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,592
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1676843/Python3-sliding-window
class Solution: def minSwaps(self, nums: List[int]) -> int: rsm = 0 ans = inf ones = nums.count(1) for i in range(len(nums) + ones): rsm += nums[i % len(nums)] if i >= ones: rsm -= nums[i - ones] ans = min(ans, ones - rsm) return ans
minimum-swaps-to-group-all-1s-together-ii
[Python3] sliding window
ye15
1
146
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,593
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/2778352/Accumulating-sliding-window-(possibly-one-liner)
class Solution: def minSwaps(self, nums: List[int]) -> int: window_size = sum(nums) return min(itertools.accumulate( iterable=range(1, len(nums)), func=lambda acc, i: acc + nums[i % len(nums) - 1] - nums[(i+window_size-1) % len(nums)], initial=window_size - sum(nums[:window_size])))
minimum-swaps-to-group-all-1s-together-ii
Accumulating sliding window (possibly one-liner)
illyatawgerchuk
0
2
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,594
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/2140392/Python-sliding-window-O(N)O(1)
class Solution: def minSwaps(self, nums: List[int]) -> int: num1 = sum(nums) s = sum(nums[:num1]) result = num1 - s n = len(nums) for i in range(num1, 2*n - 2): s += nums[i % n] s -= nums[(i-num1) % n] result = min(result, num1 - s) return result
minimum-swaps-to-group-all-1s-together-ii
Python, sliding window O(N)/O(1)
blue_sky5
0
96
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,595
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1681192/Linear-solution-87-speed
class Solution: def minSwaps(self, nums: List[int]) -> int: ones = nums.count(1) if ones < 2 or ones == len(nums): return 0 nums.extend(nums[:ones - 1]) max_ones = sliding_ones = nums[:ones].count(1) for i in range(ones, len(nums)): sliding_ones += nums[i] - nums[i - ones] max_ones = max(max_ones, sliding_ones) return ones - max_ones
minimum-swaps-to-group-all-1s-together-ii
Linear solution, 87% speed
EvgenySH
0
36
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,596
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1679478/python3-Sliding-window-with-appending-the-array-to-self-for-ref.
class Solution: def minSwaps(self, nums: List[int]) -> int: # sliding window swindowlen = nums.count(1) nums += nums # number of zeros in the sliding window. number_of_zeros_in_window = nums[:swindowlen].count(0) ans = number_of_zeros_in_window for x in range(swindowlen, swindowlen+(len(nums)//2)): if nums[x-swindowlen] == 0: number_of_zeros_in_window -= 1 if nums[x] == 0: number_of_zeros_in_window += 1 ans = min(ans, number_of_zeros_in_window) return ans
minimum-swaps-to-group-all-1s-together-ii
[python3] Sliding window with appending the array to self for ref.
vadhri_venkat
0
45
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,597
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1678771/Python3-Sliding-Window-Approach
class Solution: def minSwaps(self, nums: List[int]) -> int: k = nums.count(1) combined_array = nums + nums l, r = 0, 0 current_count = 0 min_count = float("inf") while r < len(combined_array): while (r - l) < k: if combined_array[r] == 0: current_count += 1 r = r + 1 min_count = min(min_count, current_count) if combined_array[r] == 0: current_count += 1 if combined_array[l] == 0: current_count -= 1 r += 1 l += 1 return min_count
minimum-swaps-to-group-all-1s-together-ii
[Python3] Sliding Window Approach
venkateshyadava
0
39
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,598
https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1677039/Python-3-Circular-Sliding-Window
class Solution: def minSwaps(self, data: List[int]) -> int: ones = sum(data) cntOne = maxOne = 0 l = r = 0 n = len(data) while r < n*2: cntOne += data[r%n] r += 1 while r - l > ones: cntOne -= data[l%n] l += 1 maxOne = max(maxOne,cntOne) return ones - maxOne
minimum-swaps-to-group-all-1s-together-ii
Python 3 Circular Sliding Window
ezcat
0
56
minimum swaps to group all 1s together ii
2,134
0.507
Medium
29,599