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/game-of-life/discuss/771534/Python3-overshot-encoding
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: m, n = len(board), len(board[0]) # dimensions for i, j in product(range(m), range(n)): cnt = 0 for ii, jj in product(range(i-1, i+2), range(j-1, j+2)): if 0 <= ii < m and 0 <= jj < n and (i, j) != (ii, jj) and abs(board[ii][jj]) == 1: cnt += 1 if board[i][j] and (cnt < 2 or cnt > 3): board[i][j] = -1 # live to dead elif not board[i][j] and cnt == 3: board[i][j] = 2 # dead to live for i, j in product(range(m), range(n)): board[i][j] = int(board[i][j] > 0)
game-of-life
[Python3] overshot encoding
ye15
0
59
game of life
289
0.668
Medium
5,200
https://leetcode.com/problems/game-of-life/discuss/750088/Python-Easy-Solution-...-Feels-Cheating-...
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ rows, cols = len(board), len(board[0]) def transform(row, col, temp_board): nonlocal rows, cols neighbors = 0 for r, c in [(row-1, col-1), (row, col-1), (row+1, col-1), (row-1, col), (row+1, col), (row-1, col+1), (row, col+1), (row+1, col+1)]: if 0 <= c < cols and 0 <= r < rows: neighbors += temp_board[r][c] if board[row][col] == 1: if neighbors < 2 or neighbors > 3: return 0 else: return 1 else: return 1 if neighbors == 3 else 0 # Take a snapshot of the current board for calculation temp_board = [row[:] for row in board] for row in range(rows): for col in range(cols): board[row][col] = transform(row, col, temp_board)
game-of-life
Python Easy Solution ... Feels Cheating ...
sexylol
-1
68
game of life
289
0.668
Medium
5,201
https://leetcode.com/problems/word-pattern/discuss/1696590/Simple-Python-Solution-oror-Faster-than-99.34
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: li = s.split(' ') di = {} if len(li) != len(pattern): return False for i, val in enumerate(pattern): if val in di and di[val] != li[i]: return False elif val not in di and li[i] in di.values(): return False elif val not in di: di[val] = li[i] return True
word-pattern
Simple Python Solution || Faster than 99.34%
KiranUpase
4
509
word pattern
290
0.404
Easy
5,202
https://leetcode.com/problems/word-pattern/discuss/1470489/Character-Mapping-oror-Dictionary-oror-Easy-to-understand
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: #i/p : pattern = "abba" and s = "dog cat cat dog" arr1 = list(pattern) #arr1 = ["a", "b", "b", "a"] arr2 = s.split() #arr2 = ["dog", "cat", "cat", "dog"] n = len(arr2) #len(arr1) == len(arr2) in all cases where True is possible if len(arr1) != len(arr2): #we will never be able to map all characters return False d1 = {} #to handle character mapping from arr1 to arr2 d2 = {} #to handle character mapping from arr2 to arr1 #Below is our character mapping logic for i in range(0, n): if arr1[i] in d1 and d1[arr1[i]] != arr2[i]: return False if arr2[i] in d2 and d2[arr2[i]] != arr1[i]: return False d1[arr1[i]] = arr2[i] #after all loops : d1 = {"a" : "dog", "b" : "cat"} d2[arr2[i]] = arr1[i] #after all loops : d2 = {"dog" : "a", "cat" : "b"} #if none of the above condition returns False #it means that all characters of arr1 can be legally mapped to arr2, so, return True return True
word-pattern
Character Mapping || Dictionary || Easy to understand
aarushsharmaa
3
198
word pattern
290
0.404
Easy
5,203
https://leetcode.com/problems/word-pattern/discuss/1007935/Easy-and-Clear-Solution-Python3
class Solution: def wordPattern(self, p: str, s: str) -> bool: x=s.split(' ') if len(x)!=len(p) : return False return len(set(zip(p,x)))==len(set(p))==len(set(x))
word-pattern
Easy & Clear Solution Python3
moazmar
2
139
word pattern
290
0.404
Easy
5,204
https://leetcode.com/problems/word-pattern/discuss/2277610/Easy-PYTHON-Solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(' ') ma = {} rev = {} if len(s) != len(pattern) : return False for i in range(len(pattern)) : if pattern[i] in ma : if ma[pattern[i]]!=s[i] : return False elif s[i] in rev : return False else : ma[pattern[i]] = s[i] rev[s[i]] = pattern[i] return True
word-pattern
⬆️ Easy PYTHON Solution ⬆️
soorajks2002
1
137
word pattern
290
0.404
Easy
5,205
https://leetcode.com/problems/word-pattern/discuss/2097578/Python3-O(n%2Bm)-in-runtime-and-memory-Runtime%3A-26ms-96.19
class Solution: # O(n+m) runtime; # O(n+m) space; where n is the string present in pattern # and m is the string present in the string # runtime: 26ms 96.19% def wordPattern(self, pattern: str, string: str) -> bool: patternMap = dict() stringMap = dict() stringList = string.split(" ") if len(stringList) != len(pattern): return False for char, word in zip(pattern, stringList): if char in patternMap and patternMap[char] != word: return False if word in stringMap and stringMap[word] != char: return False patternMap[char] = word stringMap[word] = char return True
word-pattern
Python3 O(n+m) in runtime and memory; Runtime: 26ms 96.19%
arshergon
1
108
word pattern
290
0.404
Easy
5,206
https://leetcode.com/problems/word-pattern/discuss/1870857/Python-3-line-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: if len(s.split()) == len(pattern): return len(set(zip(s.split(), list(pattern)))) == len(set(pattern)) == len(set(s.split())) return False
word-pattern
Python 3 line solution
alishak1999
1
139
word pattern
290
0.404
Easy
5,207
https://leetcode.com/problems/word-pattern/discuss/1697471/python3-solution-using-dictionary-mapping
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: mapping = {} word = list(s.split(" ")) if (len(set(pattern)) != len(set(word))) or (len(pattern) != len(word)): return False else: for x in range(len(pattern)): if pattern[x] not in mapping: mapping[pattern[x]] = word[x] elif mapping[pattern[x]] != word[x]: return False return True
word-pattern
python3 solution using dictionary mapping
KratikaRathore
1
59
word pattern
290
0.404
Easy
5,208
https://leetcode.com/problems/word-pattern/discuss/1696929/Python3-Simple-intuitive-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split() if len(pattern) != len(s): return False n = len(pattern) d = dict() rev = dict() for i in range(n): if pattern[i] not in d and s[i] not in rev: d[pattern[i]] = s[i] rev[s[i]] = pattern[i] else: if d.get(pattern[i], '') != s[i]: return False if rev.get(s[i], '') != pattern[i]: return False return True
word-pattern
[Python3] Simple intuitive solution
BrijGwala
1
36
word pattern
290
0.404
Easy
5,209
https://leetcode.com/problems/word-pattern/discuss/1489071/Easy-python-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: cache = {} words = s.split(" ") if len(words) != len(pattern): return False if len(set(pattern)) != len(set(words)): return False for j in range(len(words)): if pattern[j] in cache: if cache[pattern[j]] != words[j]: return False else: cache[pattern[j]] = words[j] return True
word-pattern
Easy python solution
prashantpandey9
1
84
word pattern
290
0.404
Easy
5,210
https://leetcode.com/problems/word-pattern/discuss/1384886/Using-Dictionary-Python
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split() mapping_p_s = {} mapping_s_p = {} if len(s) != len(pattern): return False for index,element in enumerate(pattern): if element in mapping_p_s and s[index] in mapping_s_p: if mapping_p_s[element] == s[index]: pass else: return False elif element not in mapping_p_s and s[index] not in mapping_s_p: mapping_p_s[element] = s[index] mapping_s_p[s[index]] = element else: return False return True
word-pattern
Using Dictionary - Python
_Mansiii_
1
125
word pattern
290
0.404
Easy
5,211
https://leetcode.com/problems/word-pattern/discuss/1246603/Easy-python-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: d=dict() s=s.split() if(len(pattern)!=len(s)): return False for i in range(len(pattern)): if(pattern[i] not in d): if(s[i] not in d.values()): d[pattern[i]]=s[i] continue return False else: if(d[pattern[i]]==s[i]): continue return False return True
word-pattern
Easy python solution
Sneh17029
1
373
word pattern
290
0.404
Easy
5,212
https://leetcode.com/problems/word-pattern/discuss/880459/Python3-solution-using-1-hash-map.-Beats-90
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split(' ') pattern_dict = {} if len(pattern) != len(words): return False for p, w in zip(pattern, words): if pattern_dict.get(p): if pattern_dict[p] != w: return False else: if w in pattern_dict.values(): return False pattern_dict[p] = w return True
word-pattern
Python3 solution using 1 hash map. Beats 90%
n0execution
1
321
word pattern
290
0.404
Easy
5,213
https://leetcode.com/problems/word-pattern/discuss/771187/Python3-3-approaches
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: string = str.split() if len(pattern) != len(string): return False mpp, mps = {}, {} for i, (p, s) in enumerate(zip(pattern, string)): if mpp.get(p) != mps.get(s): return False mpp[p] = mps[s] = i return True
word-pattern
[Python3] 3 approaches
ye15
1
103
word pattern
290
0.404
Easy
5,214
https://leetcode.com/problems/word-pattern/discuss/771187/Python3-3-approaches
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: string = str.split() return len(pattern) == len(string) and len(set(zip(pattern, string))) == len(set(pattern)) == len(set(string))
word-pattern
[Python3] 3 approaches
ye15
1
103
word pattern
290
0.404
Easy
5,215
https://leetcode.com/problems/word-pattern/discuss/771187/Python3-3-approaches
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split() return len(set(pattern)) == len(set(words)) == len(set(zip_longest(pattern, words)))
word-pattern
[Python3] 3 approaches
ye15
1
103
word pattern
290
0.404
Easy
5,216
https://leetcode.com/problems/word-pattern/discuss/771187/Python3-3-approaches
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: f = lambda s: tuple(map({}.setdefault, s, range(len(s)))) return f(pattern) == f(str.split())
word-pattern
[Python3] 3 approaches
ye15
1
103
word pattern
290
0.404
Easy
5,217
https://leetcode.com/problems/word-pattern/discuss/280525/Python-3-Lines-Simple
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: from collections import Counter pattern = [val for val in Counter(pattern).values()] s = [val for val in Counter(str.split()).values()] return pattern == s
word-pattern
Python 3 Lines Simple
wejungle
1
149
word pattern
290
0.404
Easy
5,218
https://leetcode.com/problems/word-pattern/discuss/2844148/Python-Solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: dic = {} s = s.split(" ") result = [] if len(set(s)) != len(set(pattern)): return False else: for idx, letter in enumerate(pattern): dic[letter] = s[idx] for letter in pattern: result.append(dic[letter]) return result == s
word-pattern
Python Solution
corylynn
0
3
word pattern
290
0.404
Easy
5,219
https://leetcode.com/problems/word-pattern/discuss/2837399/Intuitive-solution-in-Python
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split() if len(pattern) != len(words): return False map = {} for letter, word in zip(pattern, words): if letter not in map: if word in map.values(): return False map[letter] = word elif map[letter] != word: return False return True
word-pattern
Intuitive solution in Python
vitaliiPsl
0
3
word pattern
290
0.404
Easy
5,220
https://leetcode.com/problems/word-pattern/discuss/2829275/python-or-just-three-lines
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(" ") if len(pattern) != len(s): return False return len(set(pattern))==len(set(zip(pattern, s)))==len(set(s))
word-pattern
python | just three lines
SimonEE
0
4
word pattern
290
0.404
Easy
5,221
https://leetcode.com/problems/word-pattern/discuss/2828949/Python-Solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s=s.split(" ") m1={} m2={} if(len(s)!=len(pattern)): return False for i in range(len(s)): if(s[i] in m1.keys() and pattern[i] not in m2.keys()): return False if(s[i] not in m1.keys() and pattern[i] in m2.keys()): return False if(s[i] in m1.keys() and pattern[i] in m2.keys()): if(m1.get(s[i])!=pattern[i] or m2.get(pattern[i])!=s[i]): return False else: m1[s[i]]=pattern[i] m2[pattern[i]]=s[i] return True
word-pattern
Python Solution
CEOSRICHARAN
0
3
word pattern
290
0.404
Easy
5,222
https://leetcode.com/problems/word-pattern/discuss/2797633/Simple-Python3-Solution-Improved-RunTime
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(' ') hash_tbl = {} if len(pattern) != len(s): return False if len(set(pattern)) != len(set(s)): return False for i in range(len(pattern)): if s[i] not in hash_tbl: hash_tbl[s[i]] = pattern[i] elif hash_tbl[s[i]] != pattern[i]: return False return True
word-pattern
Simple Python3 Solution Improved RunTime
vivekrajyaguru
0
6
word pattern
290
0.404
Easy
5,223
https://leetcode.com/problems/word-pattern/discuss/2797624/Simple-Python3-Solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(' ') hash_tbl = {} if len(pattern) != len(s): return False for i in range(len(pattern)): if pattern[i] not in hash_tbl and s[i] not in hash_tbl.values(): hash_tbl[pattern[i]] = s[i] if pattern[i] not in hash_tbl and s[i] in hash_tbl.values(): return False if pattern[i] in hash_tbl and hash_tbl[pattern[i]] != s[i]: return False return True
word-pattern
Simple Python3 Solution
vivekrajyaguru
0
5
word pattern
290
0.404
Easy
5,224
https://leetcode.com/problems/word-pattern/discuss/2795362/Python
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words=s.split() if len(pattern) != len(words): return False d1={} d2={} for i in range(0,len(words)): if pattern[i] not in d1: d1[pattern[i]] = words[i] elif pattern[i] in d1: value = d1[pattern[i]] if value == words[i]: continue else: return False if words[i] not in d2: d2[words[i]] =pattern[i] elif words[i] in d2: value = d2[words[i]] if value == pattern[i]: continue else: return False return True
word-pattern
Python
mahimari
0
3
word pattern
290
0.404
Easy
5,225
https://leetcode.com/problems/word-pattern/discuss/2749399/word-pattern-python3
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: arr_pattren = [i for i in pattern] arr_s = [i for i in s.split()] return Pen(arr_pattren, Translate(FilterPattern(arr_pattren))) == Pen(arr_s, Translate(FilterPattern(arr_s))) def Translate(iter : list)->dict: data = {} for key, val in zip(iter, range(0,26)): data[key] = val return data def Pen(pattern : str,data : dict)->str: result = "" for i in pattern: result+=str(data[i]) return result def FilterPattern(pattern: list)->list: result = [] for i in pattern: if i not in result: result.append(i) else: for i in pattern: if i not in result: result.append(i) return result
word-pattern
word pattern , python3
http_master
0
8
word pattern
290
0.404
Easy
5,226
https://leetcode.com/problems/word-pattern/discuss/2749177/Python3-fast-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: arr_pattren = [i for i in pattern] arr_s = [i for i in s.split()] return Pen(arr_pattren, Translate(FilterPattern(arr_pattren))) == Pen(arr_s, Translate(FilterPattern(arr_s))) def Translate(iter : list)->dict: data = {} for key, val in zip(iter, range(1,40)): data[key] = val return data def Pen(pattern : str,data : dict)->str: result = "" for i in pattern: result+=str(data[i]) return result def FilterPattern(pattern: list)->list: result = [] for i in pattern: if i not in result: result.append(i) else: for i in pattern: if i not in result: result.append(i) return result
word-pattern
Python3 fast solution
http_master
0
4
word pattern
290
0.404
Easy
5,227
https://leetcode.com/problems/word-pattern/discuss/2749152/Python3-NeetCode-Solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split() if len(words) != len(pattern) or len(set(pattern)) != len(set(words)): return False charToWord = {} wordToChar = {} for char, word in zip(pattern, words): if char in charToWord and charToWord[char] != word : return False if word in wordToChar and wordToChar[word] != char: return False charToWord[char] = word wordToChar[word] = char return True
word-pattern
Python3 NeetCode Solution
paul1202
0
5
word pattern
290
0.404
Easy
5,228
https://leetcode.com/problems/word-pattern/discuss/2723049/Python-O(m%2Bn)-easy-to-understand-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: mapPS,mapSP={},{} st=s.split(" ") if len(st)!=len(pattern): return False for i,j in zip(pattern,st): if i in mapPS and mapPS[i]!=j: return False if j in mapSP and mapSP[j]!=i: return False mapPS[i]=j mapSP[j]=i return True
word-pattern
Python-O(m+n), easy to understand solution
kartikchoudhary96
0
3
word pattern
290
0.404
Easy
5,229
https://leetcode.com/problems/word-pattern/discuss/2690901/Python-2-liner-with-explanation
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: #Add the words of the string in a list str_list = s.split(' ') # TRUE condition : When the length of set of all combinations, matches with length of pattern and that of list. # P.S. - Combination means each char of pattern combined with each word of the list # FALSE condition : Everything else and also when lengths of pattern and list are mismatched return False if len(pattern) != len(str_list) else len(set(zip(pattern, str_list))) == len(set(pattern)) == len(set(str_list))
word-pattern
Python 2 liner with explanation
code_snow
0
11
word pattern
290
0.404
Easy
5,230
https://leetcode.com/problems/word-pattern/discuss/2673950/My-approach-in-Python3-using-dictionary
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: k, v=[*pattern], s.split(" ") dict={} if len(k)!=len(v): return False for i in range(len(k)): if k[i] in dict.keys(): if dict.get(k[i])!=v[i]: return False else: dict[k[i]]=v[i] if len(set(dict.keys()))!=len(set(dict.values())): return False return True
word-pattern
My approach in Python3 using dictionary
SayaniBiswas
0
8
word pattern
290
0.404
Easy
5,231
https://leetcode.com/problems/word-pattern/discuss/2671944/Easy
class Solution: def wordPattern(self, pattern: str, p: str) -> bool: s=p.split(" ") k=list(pattern) if len(s)!=len(k): return False d=dict() for i in range(len(k)): d[k[i]]=s[i] ans="" for i in k: ans+=d[i]+" " if ans[:-1]==p: if len(set(s))==len(set(k)): return True return False
word-pattern
Easy
sonusahu050502
0
7
word pattern
290
0.404
Easy
5,232
https://leetcode.com/problems/word-pattern/discuss/2647831/Python-Simple-HashMap-Solution-(One-to-One-mapping)
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: pattList = list(pattern) sList = s.split() if len(pattern) != len(sList): return False p_seen = {} s_seen = {} for i in range(len(pattList)): if pattList[i] in p_seen: if p_seen[pattList[i]] != sList[i]: return False else: p_seen[pattList[i]] = sList[i] if sList[i] in s_seen: if s_seen[sList[i]] != pattList[i]: return False else: s_seen[sList[i]] = pattList[i] if len(p_seen) != len(s_seen): return False flag = True for i in range(len(pattern)): if p_seen[pattern[i]] != sList[i]: return False for i in range(len(sList)): if s_seen[sList[i]] != pattern[i]: return False return True
word-pattern
Python Simple HashMap Solution (One-to-One mapping)
joelkurien
0
19
word pattern
290
0.404
Easy
5,233
https://leetcode.com/problems/word-pattern/discuss/2489618/Python-or-Clear-solution-with-explanation
class Solution: def wordPattern(self, letters: str, words: str) -> bool: ''' Renamed parameters to less confusing names. "patterns" to "letters". "s" to "words". Solution: Return False if the number of letters and words are not the same. Traverse the letters, one by one and return False if: A letter together with its corresponding word in words (same index as in letters) meets a condition when compared: With letters as keys in the dictonary and words as corresponding values: 1. Return False if: Current letter/key in loop already exists but isn't the same as the letter/word pair currently in comparison. 2. Return False if: Current letter in loop is not yet a key but the corresponding word is a value in the dictionary already. (Otherwise add the letter and word as key/value pairs to the dict) Return True if the loop is complete, which means that all letters have been compared with corresponding words without finding any of the above issues. ''' words = words.split() if len(letters) != len(words): return False pairs = dict() for i, letter in enumerate(letters): if letter in pairs.keys(): if pairs[letter] != words[i]: return False elif words[i] not in pairs.values(): pairs[letter] = words[i] else: return False return True
word-pattern
Python | Clear solution with explanation
Wartem
0
90
word pattern
290
0.404
Easy
5,234
https://leetcode.com/problems/word-pattern/discuss/2479551/Python-Solution
class Solution: def getPattern(self,pattern): pm = dict() count = 0 for ch in pattern: if(pm.get(ch)!=None): continue else: count += 1 pm[ch] = count ptr = "" for ch in pattern: ptr += str(pm[ch]) return ptr def wordPattern(self, pattern: str, s: str) -> bool: sl = s.split(' ') ptr1 = self.getPattern(pattern) ptr2 = self.getPattern(sl) if(ptr1==ptr2): return True return False
word-pattern
Python Solution
farazkhanfk7
0
46
word pattern
290
0.404
Easy
5,235
https://leetcode.com/problems/word-pattern/discuss/2467404/Python-simple-solution-using-dictionary
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(" ") if len(pattern) != len(s): return False dic = {} for i in range(len(pattern)): if pattern[i] not in dic and s[i] not in dic.values(): dic[pattern[i]] = s[i] else: if pattern[i] in dic: if s[i] != dic[pattern[i]]: return False else: return False return True
word-pattern
Python simple solution using dictionary
aruj900
0
65
word pattern
290
0.404
Easy
5,236
https://leetcode.com/problems/word-pattern/discuss/2300886/Python-Logic-Efficient
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(' ') map = {} if len(pattern)!= len(s): return False for i in range(len(pattern)): if pattern[i] not in map: if s[i] in s[:i]: return False else: map[pattern[i]] = s[i] else: if map[pattern[i]] != s[i]: return False return True
word-pattern
Python Logic Efficient
Abhi_009
0
104
word pattern
290
0.404
Easy
5,237
https://leetcode.com/problems/word-pattern/discuss/2204941/Python-double-hashmap-solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: hash_map1 = dict(zip(list(pattern),s.split())) hash_map2 = dict(zip(s.split(),list(pattern))) ans1 = [] ans2 = [] for i in pattern: if i in hash_map1: ans1 += [hash_map1[i]] for i in s.split(): if i in hash_map2: ans2 += [hash_map2[i]] return (s == ' '.join(ans1)) and (pattern == ''.join(ans2))
word-pattern
Python double hashmap solution
StikS32
0
65
word pattern
290
0.404
Easy
5,238
https://leetcode.com/problems/word-pattern/discuss/2141271/Code-for-Each-type-of-test-case-Python
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: if len(pattern)>1 and pattern==s: return False hs = {} rs = {} a = '' j = 0 s += ' ' b = 0 c = 0 for i in range(len(s)): if s[i]==' ': c+=1 if len(pattern)<c or c<len(pattern): return False for i in range(len(s)): if s[i]!=" ": a += s[i] continue b += 1 if b>len(pattern): return False if j<len(pattern): print(hs) if (pattern[j] in hs and hs[pattern[j]]!=a) or (a in rs and rs[a]!=pattern[j]): return False hs[pattern[j]]=a rs[a]=pattern[j] j += 1 a = '' return True
word-pattern
Code for Each type of test case-Python
jayeshvarma
0
44
word pattern
290
0.404
Easy
5,239
https://leetcode.com/problems/word-pattern/discuss/2106423/PYTHON-oror-EASY-IMPLEMENTATION
class Solution: def wordPattern(self, a: str, s: str) -> bool: s=list(s.split()) if len(s)!=len(a): return False d={} e={} for i in range(len(a)): if a[i] in d and d[a[i]]!=s[i]: return False if s[i] in e and e[s[i]]!=a[i]: return False e[s[i]]=a[i] d[a[i]]=s[i] return True
word-pattern
✔️ PYTHON || EASY IMPLEMENTATION
karan_8082
0
146
word pattern
290
0.404
Easy
5,240
https://leetcode.com/problems/word-pattern/discuss/2091457/Python-solution-which-converts-pattern-and-string-to-new-word-and-compares
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: sub1 = self.getNewWord(pattern, False) sub2 = self.getNewWord(s, True) return sub1 == sub2 def getNewWord(self, s, split): start = 'a' word = "" subs = {} if split: s = s.split() for i in s: if i not in subs: subs[i] = start start = chr(ord(start) + 1) word += subs[i] return word
word-pattern
Python solution which converts pattern and string to new word and compares
rahulsh31
0
45
word pattern
290
0.404
Easy
5,241
https://leetcode.com/problems/word-pattern/discuss/2091352/Python-Solution
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: d = {} l = s.split() if len(pattern) != len(l): return False for i in range(len(pattern)): if pattern[i] not in d: if l[i] in d.values(): return False d[pattern[i]] = l[i] else: if d[pattern[i]] != l[i]: return False return True
word-pattern
Python Solution
afreenansari25
0
64
word pattern
290
0.404
Easy
5,242
https://leetcode.com/problems/word-pattern/discuss/2010508/f-is-a-function-AND-inv(f)-is-a-function-greater-f-is-bijective
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: f = {} f_inv = {} for pre, image in itertools.zip_longest(pattern, s.split(), fillvalue=False): # I could have left fillvalue empty, but wanted to make the truthy-ness explicit if ((pre in f or image in f_inv) and # if either the image or preimage have been seen before (pre not in f or f[pre] != image # then the preimage must match the image in f or image not in f_inv and f_inv[image] != pre)): # and the image must match the preimage in f_inv return False elif not (pre and image): # every value in the domain must have a matching value in th subdomain and vice versa return False f[pre] = image f_inv[image] = pre return True
word-pattern
f is a function AND inv(f) is a function => f is bijective
taborlin
0
16
word pattern
290
0.404
Easy
5,243
https://leetcode.com/problems/word-pattern/discuss/1835919/Python-easy-to-read-and-understand-or-hashmap
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: l = s.split(" ") if len(l) != len(pattern): return False d = {} for i in range(len(pattern)): if pattern[i] in d and d[pattern[i]] != l[i]: return False elif pattern[i] not in d and l[i] in d.values(): return False d[pattern[i]] = l[i] return True
word-pattern
Python easy to read and understand | hashmap
sanial2001
0
102
word pattern
290
0.404
Easy
5,244
https://leetcode.com/problems/word-pattern/discuss/1825188/Python-Simplest-Solution-With-Explanation-or-Beg-to-Adv-or-HashMap
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split(" ") #to separate rach word from the string. hashmap = {} if len(pattern) != len(words) or len(set(pattern)) != len(set(words)): #checking if len of pattern and the provided string is equal. return False # if not for i in range(len(pattern)): if pattern[i] not in hashmap: hashmap[pattern[i]] = words[i] # as pattern and words are not mapped we have to map them. elif hashmap[pattern[i]] != words[i]: #checking if for the provided pattern does the word match as we had stored it earlier return False # if not return True # if pattern exists.
word-pattern
Python Simplest Solution With Explanation | Beg to Adv | HashMap
rlakshay14
0
48
word pattern
290
0.404
Easy
5,245
https://leetcode.com/problems/word-pattern/discuss/1813952/2-Lines-Python-Solution-oror-50-Faster-oror-Memory-less-than-90
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s = s.split(' ') return len(set(pattern)) == len(set(s)) == len(set(zip(pattern, s))) and len(pattern) == len(s)
word-pattern
2-Lines Python Solution || 50% Faster || Memory less than 90%
Taha-C
0
53
word pattern
290
0.404
Easy
5,246
https://leetcode.com/problems/word-pattern/discuss/1731505/Python-two-dictionaries
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: if len(pattern) != len(s.split()) or len(set(pattern)) != len(set(s.split())): return False pw, wp = {}, {} for p, w in zip(pattern, s.split()): if pw.setdefault(p, w) != w or wp.setdefault(w, p) != p: return False return True
word-pattern
Python two dictionaries
zivoziv
0
46
word pattern
290
0.404
Easy
5,247
https://leetcode.com/problems/word-pattern/discuss/1698858/python3-solution-easy-to-understand
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: s=s.split() if(len(s)!=len(pattern)): return False d=dict() for i,j in zip(list(pattern),s): if i not in d: if j not in d.values(): d[i]=j else: return False else: if d[i]!=j: return False return True
word-pattern
python3 solution- easy to understand
ramya_sri0204
0
53
word pattern
290
0.404
Easy
5,248
https://leetcode.com/problems/nim-game/discuss/1141120/Bottom-up-DP-python
class Solution: def canWinNim(self, n: int) -> bool: if n <= 3: return True new_size = n + 1 memo = [False] * (new_size) for i in range(4): memo[i] = True for i in range(4,new_size): for j in range(1,4): if memo[i] == True: break if memo[i-j] == True: memo[i] = False else: memo[i] = True return memo[n]
nim-game
Bottom-up DP python
lywc
9
725
nim game
292
0.559
Easy
5,249
https://leetcode.com/problems/nim-game/discuss/1596966/Python3-oror-16ms-99-fasteroror-one-line
class Solution: def canWinNim(self, n: int) -> bool: return n % 4 != 0
nim-game
Python3 || 16ms, 99% faster|| one line
s_m_d_29
6
607
nim game
292
0.559
Easy
5,250
https://leetcode.com/problems/nim-game/discuss/771268/Python3-math-instead-of-dp
class Solution: def canWinNim(self, n: int) -> bool: return n % 4
nim-game
[Python3] math instead of dp
ye15
5
235
nim game
292
0.559
Easy
5,251
https://leetcode.com/problems/nim-game/discuss/771268/Python3-math-instead-of-dp
class Solution: def canWinNim(self, n: int) -> bool: @lru_cache(None) def fn(k): """Return True if there is a winning strategy with k stones left.""" if k <= 3: return True for kk in range(1, 4): if not fn(k - kk): return True #opponent cannot win return False return fn(n)
nim-game
[Python3] math instead of dp
ye15
5
235
nim game
292
0.559
Easy
5,252
https://leetcode.com/problems/nim-game/discuss/1353089/Nim-Game-or-Faster-python-solution-with-str
class Solution: def canWinNim(self, n: int) -> bool: return int(str(n)[-2:]) % 4
nim-game
Nim Game | Faster python solution with str
yiseboge
2
233
nim game
292
0.559
Easy
5,253
https://leetcode.com/problems/nim-game/discuss/379819/Solution-in-Python-3-(one-line)
class Solution: def canWinNim(self, n: int) -> bool: return n % 4 - Junaid Mansuri (LeetCode ID)@hotmail.com
nim-game
Solution in Python 3 (one line)
junaidmansuri
2
587
nim game
292
0.559
Easy
5,254
https://leetcode.com/problems/nim-game/discuss/2843718/python-oror-simple-solution-oror-one-liner
class Solution: def canWinNim(self, n: int) -> bool: # if n is not a multiple of 4, it is possible to win return n % 4
nim-game
python || simple solution || one-liner
wduf
1
10
nim game
292
0.559
Easy
5,255
https://leetcode.com/problems/nim-game/discuss/1547807/Python-3-Characters!-With-an-Explanation!
class Solution: def canWinNim(self, n: int) -> bool: return n % 4
nim-game
Python 3 Characters! With an Explanation!
Cavalier_Poet
1
224
nim game
292
0.559
Easy
5,256
https://leetcode.com/problems/nim-game/discuss/1134382/Python3-simple-%22one-liner%22-solution
class Solution: def canWinNim(self, n: int) -> bool: return not(n % 4 == 0)
nim-game
Python3 simple "one-liner" solution
EklavyaJoshi
1
147
nim game
292
0.559
Easy
5,257
https://leetcode.com/problems/nim-game/discuss/951671/return-n4
class Solution: def canWinNim(self, n: int) -> bool: return n%4
nim-game
return n%4
lokeshsenthilkumar
1
252
nim game
292
0.559
Easy
5,258
https://leetcode.com/problems/nim-game/discuss/2792881/Simplest-Python-code!!
class Solution: def canWinNim(self, n: int) -> bool: return n%4
nim-game
Simplest Python code!!
VidaSolitaria
0
6
nim game
292
0.559
Easy
5,259
https://leetcode.com/problems/nim-game/discuss/2777974/using-python
class Solution: def canWinNim(self, n: int) -> bool: return '1' in bin(n)[-2:]
nim-game
using python
sindhu_300
0
7
nim game
292
0.559
Easy
5,260
https://leetcode.com/problems/nim-game/discuss/2682851/One-Liner-Python
class Solution: def canWinNim(self, n: int) -> bool: return n%4 != 0
nim-game
One Liner - Python
Michael_Songru
0
4
nim game
292
0.559
Easy
5,261
https://leetcode.com/problems/nim-game/discuss/2352232/One-line-easy-python
class Solution: def canWinNim(self, n: int) -> bool: return n%4
nim-game
One line easy python
sunakshi132
0
99
nim game
292
0.559
Easy
5,262
https://leetcode.com/problems/nim-game/discuss/2085340/python3-simple-one-liner(full-explanation)
class Solution: def canWinNim(self, n: int) -> bool: return bool((n % 4))
nim-game
python3-simple one liner(full explanation)
Coconut0727
0
136
nim game
292
0.559
Easy
5,263
https://leetcode.com/problems/nim-game/discuss/2085340/python3-simple-one-liner(full-explanation)
class Solution: def canWinNim(self, n: int) -> bool: if n % 4 == 0: return False else: return True
nim-game
python3-simple one liner(full explanation)
Coconut0727
0
136
nim game
292
0.559
Easy
5,264
https://leetcode.com/problems/nim-game/discuss/1949963/One-liner-or-The-Fastest-Python-Solution-or-O(1)-O(1)
class Solution: def canWinNim(self, n: int) -> bool: return n % 4 != 0
nim-game
One-liner | The Fastest Python Solution | O(1) O(1)
tender777
0
74
nim game
292
0.559
Easy
5,265
https://leetcode.com/problems/nim-game/discuss/1842229/1-Line-Python-Solution-oror-75-Faster-oror-Memory-less-than-40
class Solution: def canWinNim(self, n: int) -> bool: return n%4!=0
nim-game
1-Line Python Solution || 75% Faster || Memory less than 40%
Taha-C
0
104
nim game
292
0.559
Easy
5,266
https://leetcode.com/problems/nim-game/discuss/1489496/Python-99-less-space-85-speed
class Solution: def canWinNim(self, n: int) -> bool: return n%4!=0
nim-game
Python // 99% less space 85% speed
fabioo29
0
204
nim game
292
0.559
Easy
5,267
https://leetcode.com/problems/nim-game/discuss/1421141/Python3-Faster-Than-98.62-With-Explanation
class Solution: def canWinNim(self, n: int) -> bool: return n % 4
nim-game
Python3 Faster Than 98.62% With Explanation
Hejita
-1
218
nim game
292
0.559
Easy
5,268
https://leetcode.com/problems/bulls-and-cows/discuss/563661/Fast-and-easy-to-understand-Python-solution-O(n)
class Solution: def getHint(self, secret: str, guess: str) -> str: # The main idea is to understand that cow cases contain the bull cases # This loop will take care of "bull" cases bull=0 for i in range(len(secret)): bull += int(secret[i] == guess[i]) # This loop will take care of "cow" cases cows=0 for c in set(secret): cows += min(secret.count(c), guess.count(c)) return f"{bull}A{cows-bull}B"
bulls-and-cows
Fast and easy to understand Python solution O(n)
mista2311
14
983
bulls and cows
299
0.487
Medium
5,269
https://leetcode.com/problems/bulls-and-cows/discuss/2724321/Python-O(n)-Solution-Using-Hashmap-with-Explanation-or-99-Faster
class Solution: def getHint(self, secret: str, guess: str) -> str: # Dictionary for Lookup lookup = Counter(secret) x, y = 0, 0 # First finding numbers which are at correct position and updating x for i in range(len(guess)): if secret[i] == guess[i]: x+=1 lookup[secret[i]]-=1 # Finding numbers which are present in secret but not at correct position for i in range(len(guess)): if guess[i] in lookup and secret[i] != guess[i] and lookup[guess[i]]>0: y+=1 lookup[guess[i]]-=1 # The reason for using two for loop is in this problem we have # to give first priority to number which are at correct position, # Therefore we are first updating x value return "{}A{}B".format(x, y)
bulls-and-cows
✔️ Python O(n) Solution Using Hashmap with Explanation | 99% Faster 🔥
pniraj657
3
472
bulls and cows
299
0.487
Medium
5,270
https://leetcode.com/problems/bulls-and-cows/discuss/253910/Python3-Solution%3A-1-Pass-with-O(1)-space
class Solution: def getHint(self, secret: str, guess: str) -> str: unmatched_secret = [0] * 10 unmatched_guess = [0] * 10 bulls = 0 for x, y in zip(secret, guess): x, y = int(x), int(y) if x == y: bulls += 1 else: unmatched_secret[x] += 1 unmatched_guess[y] += 1 cows = sum(min(unmatched_secret[i], unmatched_guess[i]) for i in range(10)) return f'{bulls}A{cows}B'
bulls-and-cows
Python3 Solution: 1 Pass with O(1) space
jinjiren
2
228
bulls and cows
299
0.487
Medium
5,271
https://leetcode.com/problems/bulls-and-cows/discuss/2846502/Python-solution-beats-94-users-and-91-space-complexity
class Solution: def getHint(self, secret: str, guess: str) -> str: dict1 = {} cows = bulls = 0 for i in range(len(secret)): if secret[i] == guess[i]: bulls += 1 else: if secret[i] not in dict1: dict1[secret[i]] = 1 else: dict1[secret[i]] += 1 for i in range(len(guess)): if guess[i] in dict1 and secret[i] != guess[i]: if dict1[guess[i]] > 0: dict1[guess[i]] -=1 cows+=1 return f"{bulls}A{cows}B"
bulls-and-cows
Python solution beats 94% users and 91% space complexity
amannagarkar
0
1
bulls and cows
299
0.487
Medium
5,272
https://leetcode.com/problems/bulls-and-cows/discuss/2824411/Bulls-and-Cows-or-Python-solution
class Solution: def getHint(self, secret: str, guess: str) -> str: Bulls,Cows, Position = 0,0, [] for i in range(len(secret)): if secret[i] == guess[i]: Bulls += 1 Position.append(i) for i in range(len(Position)): idx = Position[i] - i secret = secret[:idx] + secret[idx+1:] guess = guess[:idx] + guess[idx+1:] for i in range(len(guess)): if guess[i] in secret: Cows += 1 idx = secret.index(guess[i]) secret = secret[:idx] + secret[idx+1:] return str(Bulls)+"A"+str(Cows)+"B"
bulls-and-cows
Bulls and Cows | Python solution
nishanrahman1994
0
2
bulls and cows
299
0.487
Medium
5,273
https://leetcode.com/problems/bulls-and-cows/discuss/2819197/Python3-oror-Using-Dictionaries-oror-Faster-than-96.55-oror-Less-memory-than-81.01
class Solution: def getHint(self, secret: str, guess: str) -> str: sl, gl = list(secret), list(guess) # sl = secretList; gl = guessList sd, gd = {}, {} # sd = secret dictionary; gd = guessDictionary a = b = 0 # a = number of "bulls"; b = number of "cows" sdk = set() # secretDictionaryKeys i = 0 while i < len(sl): # While length of the sl greater than i if sl[i] == gl[i]: # If they are in the same position sl.pop(i) # Remove the number of sl and gl gl.pop(i) a += 1 else: # If they are not in the same position sd[sl[i]] = sd.get(sl[i], 0) + 1 # Get the value and increment it by 1 in sd and gd gd[gl[i]] = gd.get(gl[i], 0) + 1 sdk.add(sl[i]) i += 1 # Increment the iterator for k in sdk: b += min(sd.get(k, 0), gd.get(k, 0)) return str(a)+'A'+str(b)+'B'
bulls-and-cows
✅ Python3 || Using Dictionaries || Faster than 96.55% || Less memory than 81.01%
PabloVE2001
0
6
bulls and cows
299
0.487
Medium
5,274
https://leetcode.com/problems/bulls-and-cows/discuss/2799469/Bulls-and-Cows-Python-approach
class Solution: def getHint(self, secret: str, guess: str) -> str: n_bulls = 0 n_cows = 0 # Counter s_counter = {} g_counter = {} for i in range(len(secret)): # Count identical letter if secret[i] == guess[i]: n_bulls += 1 else: # We add in respective counter for guess &amp; secret s_counter[secret[i]] = 1 + s_counter.get(secret[i], 0) g_counter[guess[i]] = 1 + g_counter.get(guess[i], 0) # Determine the number of cows for key in g_counter.keys(): n_cows += min(g_counter.get(key), s_counter.get(key, 0)) return "{0}A{1}B".format(n_bulls, n_cows)
bulls-and-cows
Bulls and Cows - Python approach
rere-rere
0
2
bulls and cows
299
0.487
Medium
5,275
https://leetcode.com/problems/bulls-and-cows/discuss/2774980/python-using-Counter-easy-to-understand
class Solution: def getHint(self, secret: str, guess: str) -> str: # count number of each character secretDict,guessDict = Counter(secret),Counter(guess) bulls,cows = 0,0 # find number of bulls for i in range(len(secret)): if secret[i]==guess[i]: bulls+=1 # find number of cows+bulls # note that Cow digits contain Bull digits for char,count in secretDict.items(): cows+= min(count,guessDict.get(char,0)) return "{}A{}B".format(bulls,cows-bulls)
bulls-and-cows
python using Counter -- easy to understand
jayr777
0
7
bulls and cows
299
0.487
Medium
5,276
https://leetcode.com/problems/bulls-and-cows/discuss/2768465/BEATS-90-RUNTIME-80-MEMORY-or-Easy-Solution
class Solution: def getHint(self, secret: str, guess: str) -> str: cntA = 0 cntB = 0 secrcount = {} for i in range(len(secret)): if guess[i] == secret[i]: cntA += 1 else: if secret[i] not in secrcount: secrcount[secret[i]] = 1 else: secrcount[secret[i]] += 1 for i in range(len(guess)): if guess[i] == secret[i]: continue if (guess[i] in secrcount) and (secrcount[guess[i]] > 0): cntB += 1 secrcount[guess[i]] -= 1 return str(cntA) + "A" + str(cntB) + "B"
bulls-and-cows
BEATS 90% RUNTIME, 80% MEMORY | Easy Solution
zaberraiyan
0
5
bulls and cows
299
0.487
Medium
5,277
https://leetcode.com/problems/bulls-and-cows/discuss/2766777/Python-Easy-Intuitive-Solution
class Solution: def getHint(self, secret: str, guess: str) -> str: secret_count = collections.Counter(secret) guess_count = collections.Counter(guess) x = y = 0 for i, c in enumerate(guess): if c == secret[i]: x += 1 secret_count[c] -= 1 guess_count[c] -= 1 for key in guess_count.keys(): if secret_count[key] > 0 and guess_count[key] > 0: y += min(secret_count[key], guess_count[key]) return f"{x}A{y}B"
bulls-and-cows
[Python] Easy Intuitive Solution
Paranoidx
0
5
bulls and cows
299
0.487
Medium
5,278
https://leetcode.com/problems/bulls-and-cows/discuss/2689791/Python3-Commented-and-Readable-Counters
class Solution: def getHint(self, secret: str, guess: str) -> str: # count the number of bulls bulls = 0 secret_counter = collections.Counter() guess_counter = collections.Counter() for idx in range(len(secret)): if secret[idx] == guess[idx]: bulls += 1 else: secret_counter[secret[idx]] += 1 guess_counter[guess[idx]] += 1 # count the number of cows cows = 0 for key, value in guess_counter.items(): if key in secret_counter: cows += min(secret_counter[key], guess_counter[key]) return f'{bulls}A{cows}B'
bulls-and-cows
[Python3] - Commented and Readable Counters
Lucew
0
4
bulls and cows
299
0.487
Medium
5,279
https://leetcode.com/problems/bulls-and-cows/discuss/2641644/Python-single-pass-solution
class Solution: def getHint(self, secret: str, guess: str) -> str: cow_indices = [0 for _ in range(10)] cows = 0 bulls = 0 length = len(secret) for i in range(length): if secret[i] == guess[i]: bulls += 1 else: s = int(secret[i]) g = int(guess[i]) if cow_indices[s] < 0: cows += 1 cow_indices[s] += 1 if cow_indices[g] > 0: cows += 1 cow_indices[g] -= 1 return "%dA%dB" % (bulls,cows)
bulls-and-cows
Python single pass solution
yagizsenal
0
68
bulls and cows
299
0.487
Medium
5,280
https://leetcode.com/problems/bulls-and-cows/discuss/2579119/Solution-with-two-passes-O(n)-time
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls, cows = 0, 0 count_s, count_g = defaultdict(int), defaultdict(int) for s, g in zip(secret,guess): if s == g: bulls +=1 else: count_s[s]+=1 count_g[g]+=1 for key,value in count_s.items(): if key in count_g: cows+=min(value, count_g[key]) return str(bulls)+"A"+str(cows)+"B"
bulls-and-cows
Solution with two passes O(n) time
Saitama1v1
0
39
bulls and cows
299
0.487
Medium
5,281
https://leetcode.com/problems/bulls-and-cows/discuss/2545690/Runtime%3A-137-ms-faster-than-5.07-of-Python3-Memory-Usage%3A-13.9-MB-less-than-31.96-of-Python3
class Solution: def getHint(self, secret: str, guess: str) -> str: s=list(secret) g=list(guess) x,y=0,0 z=list() gs=list() for i in range(len(s)): if s[i]==g[i]: x+=1 else: z.append(s[i]) gs.append(g[i]) if z==gs: y=len(z) else: for j in range(len(z)): if z[j] in gs: y+=1 gs.remove(z[j]) return str(x)+'A'+str(y)+'B'
bulls-and-cows
Runtime: 137 ms, faster than 5.07% of Python3 ;Memory Usage: 13.9 MB, less than 31.96% of Python3
DG-Problemsolver
0
7
bulls and cows
299
0.487
Medium
5,282
https://leetcode.com/problems/bulls-and-cows/discuss/2524312/Python-Solution
class Solution: def getHint(self, secret: str, guess: str) -> str: n=len(secret) bulls, cows=0,0 secret, guess=list(secret), list(guess) for i in range(n): if secret[i]==guess[i]: secret[i]='-1' guess[i]='-1' bulls+=1 secret_counter=collections.Counter(secret) # print(secret_counter) for i in range(n): if guess[i]!='-1': if guess[i] in secret_counter and secret_counter[guess[i]]>0: secret_counter[guess[i]]-=1 cows+=1 ans=str(bulls)+'A'+str(cows)+'B' return ans
bulls-and-cows
Python Solution
Siddharth_singh
0
39
bulls and cows
299
0.487
Medium
5,283
https://leetcode.com/problems/bulls-and-cows/discuss/2481147/Python-The-most-straightforward-and-easyunderstand-way
class Solution: def getHint(self, secret: str, guess: str) -> str: a=0 b=0 temps='' tempg='' for j in range(len(secret)): if secret[j] == guess[j]: a+=1 else: temps+=secret[j] tempg+=guess[j] #iterate both strings to find correct digits, which is bulls. Add all other digits into a dictionary and count the number of them. dic={} for ele in temps: if dic.get(ele) == None: dic[ele]=1 else: dic[ele]+=1 #For all bulls, remove them from the dictionary to aviod duplicate counting. for elem in tempg: if dic.get(elem) and dic[elem]>0: dic[elem]-=1 b+=1 #If all digits appear in both dictionaries, we know they must be in the wrong place. So those digits will be Cows, add up and return. return str(a)+'A'+str(b)+'B' #Put them into one string and return it.
bulls-and-cows
Python - The most straightforward and easyunderstand way
atmosphere77777
0
63
bulls and cows
299
0.487
Medium
5,284
https://leetcode.com/problems/bulls-and-cows/discuss/2467555/Python3-Easy-Solution-with-explanation
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls, cows = 0, 0 bulls_ind = [] hm_secret = Counter(secret) # -- (a for i in range(len(secret)): if secret[i] == guess[i]: bulls +=1 bulls_ind.append(i) # -- (b hm_secret[secret[i]] -= 1 # -- (c for i in range(len(secret)): if i not in bulls_ind: # -- (d if guess[i] in secret and hm_secret[guess[i]] != 0: cows += 1 # -- (e hm_secret[guess[i]] -= 1 # --(f return (f"{bulls}A{cows}B") # format "xAyB"
bulls-and-cows
Python3 Easy Solution with explanation
Emprixies
0
54
bulls and cows
299
0.487
Medium
5,285
https://leetcode.com/problems/bulls-and-cows/discuss/2467555/Python3-Easy-Solution-with-explanation
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls = 0 cows = 0 ns, ng = '', '' for s,g in zip(secret, guess): if s == g: bulls += 1 secret = Counter(secret) guess = Counter(guess) for t in guess: if t in secret: cows += min(secret[t], guess[t]) return f'{bulls}A{cows-bulls}B'
bulls-and-cows
Python3 Easy Solution with explanation
Emprixies
0
54
bulls and cows
299
0.487
Medium
5,286
https://leetcode.com/problems/bulls-and-cows/discuss/2454564/PYTHON-3-Fast-and-Short-Solution-oror-Runtime%3A-56ms
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls=0 cows=0 d1=collections.Counter(secret) d2=collections.Counter(guess) for i in d1: if i in d2: cows+=min(d1[i],d2[i]) for i in range(len(secret)): if secret[i] == guess[i]: bulls+=1 return str(bulls) + "A" + str(cows-bulls) + 'B'
bulls-and-cows
[PYTHON 3] Fast and Short Solution || Runtime: 56ms
WhiteBeardPirate
0
13
bulls and cows
299
0.487
Medium
5,287
https://leetcode.com/problems/bulls-and-cows/discuss/2383593/Python-beats-93-Counter()-thoroughly-explained.
class Solution: def getHint(self, secret: str, guess: str) -> str: # Setup counts for bulls and cows bulls = cows = 0 # Copy secret and guess into lists that are easier to work with secretCopy = list(secret) guessCopy = list(guess) # In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls for i in range(len(secret)): # If they match, bulls += 1 and pop() the letters from the copy lists via their .index() if secret[i] == guess[i]: bulls += 1 secretCopy.pop(secretCopy.index(secret[i])) guessCopy.pop(guessCopy.index(guess[i])) # Count() the letters remaining in secret and guess lists secretCounter = Counter(secretCopy) guessCounter = Counter(guessCopy) # Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed # secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters # Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters dif = secretCounter - (secretCounter - guessCounter) # The .total() of the dif Counter is the number of cows cows = dif.total() # return the formatted string with req. info return f'{bulls}A{cows}B'
bulls-and-cows
Python beats 93%, Counter() thoroughly explained.
DevWantsBTC
0
56
bulls and cows
299
0.487
Medium
5,288
https://leetcode.com/problems/bulls-and-cows/discuss/2235997/Python-O(n)-time-and-space-using-Counter
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls,cow = 0,0 s = list(secret) g = list(guess) i,j=0,0 while i<len(secret): if s[j]==g[j]: bulls+=1 s.pop(j) g.pop(j) else: j+=1 i+=1 count = Counter(s) for char in g: if char in count and count[char]>0: cow+=1 count[char]-=1 return f'{bulls}A{cow}B'
bulls-and-cows
Python O(n) time and space using Counter
abhiswc29
0
47
bulls and cows
299
0.487
Medium
5,289
https://leetcode.com/problems/bulls-and-cows/discuss/2228730/Simple-O(n)-Time-and-O(1)-Space-Simple-Code
class Solution: def getHint(self, secret: str, guess: str) -> str: cnt = [0] * 10 bulls, cows = 0,0 for i in range(len(secret)): if secret[i] == guess[i]: bulls += 1 else: cnt[int(secret[i])] += 1 for i in range(len(secret)): if secret[i] != guess[i] and cnt[int(guess[i])] > 0: cows += 1 cnt[int(guess[i])] -= 1 return str(bulls) + "A" + str(cows) + "B"
bulls-and-cows
Simple O(n) Time and O(1) Space - Simple Code
GiladShotland
0
30
bulls and cows
299
0.487
Medium
5,290
https://leetcode.com/problems/bulls-and-cows/discuss/2220911/Python3-or-Faster-than-96.88
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls, cows = 0, 0 cntS = defaultdict(int) cntG = defaultdict(int) for i in range(len(secret)): if secret[i] == guess[i]: bulls += 1 else: cntS[secret[i]] += 1 cntG[guess[i]] += 1 for k in set(cntS.keys()).intersection(set(cntG.keys())): cows += min(cntS[k], cntG[k]) return f"{bulls}A{cows}B"
bulls-and-cows
Python3 | Faster than 96.88%
anels
0
27
bulls and cows
299
0.487
Medium
5,291
https://leetcode.com/problems/bulls-and-cows/discuss/2219563/Python3-oror-90-Fast-oror-O(N)-Time-oror-Explained
class Solution: def getHint(self, secret: str, guess: str) -> str: m = {} a, b = 0, 0 s = set() for i, c in enumerate(secret): if c not in m: m[c] = set() m[c].add(i) for i, c in enumerate(guess): if c in m and i in m[c]: a += 1 m[c].remove(i) s.add(i) if c in m and not m[c]: m.pop(c) for i, c in enumerate(guess): if i in s: continue if c in m: b += 1 m[c].pop() if c in m and not m[c]: m.pop(c) return str(a)+"A"+str(b)+"B"
bulls-and-cows
Python3 || 90% Fast || O(N) Time || Explained
Dewang_Patil
0
56
bulls and cows
299
0.487
Medium
5,292
https://leetcode.com/problems/bulls-and-cows/discuss/1873565/Python3-Solution
class Solution: def getHint(self, secret: str, guess: str) -> str: d=Counter(secret) a,b=0,0 done=set() for i,x in enumerate(zip(secret,guess)): s,g=x if s==g: done.add(i) a+=1 d[g]-=1 if d[g]==0: del d[g] for i,x in enumerate(zip(secret,guess)): s,g=x if i in done: continue if g in d: b+=1 d[g]-=1 if d[g]==0: del d[g] return f"{a}A{b}B"
bulls-and-cows
Python3 Solution
eaux2002
0
61
bulls and cows
299
0.487
Medium
5,293
https://leetcode.com/problems/bulls-and-cows/discuss/1861352/Simply-Python-TC%3AO(N)-SC%3AO(1)
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls = 0 unmatched_secret_counter = collections.defaultdict(int) unmatched_guess_counter = collections.defaultdict(int) # non-bull digits in secret can be arranged so they match # unmatched digits in guess for s, g in zip(secret, guess): if s == g: bulls += 1 else: unmatched_secret_counter[s] += 1 unmatched_guess_counter[g] += 1 cows = 0 for g in unmatched_guess_counter: cows += min(unmatched_secret_counter[g], unmatched_guess_counter[g]) return f"{bulls}A{cows}B"
bulls-and-cows
Simply Python TC:O(N) SC:O(1)
ya332
0
36
bulls and cows
299
0.487
Medium
5,294
https://leetcode.com/problems/bulls-and-cows/discuss/1422572/Python3-Solution-using-list-with-comments.
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls = 0 cows = 0 # Make list out of strings secret = [int(x) for x in secret] guess = [int(x) for x in guess] sg = [(secret[n], guess[n]) for n in range(len(secret))] # Calc bulls, remove those which matched for s,g, in sg: if s == g: bulls = bulls + 1 secret.remove(s) guess.remove(g) # Calc cows, count only those which are in secret as well as guess for s in secret.copy(): if s in guess: cows = cows + 1 secret.remove(s) guess.remove(s) return '{}A{}B'.format(bulls, cows)
bulls-and-cows
[Python3] Solution using list with comments.
ssshukla26
0
64
bulls and cows
299
0.487
Medium
5,295
https://leetcode.com/problems/bulls-and-cows/discuss/1388157/Python3-oror-Easy-Understandable-oror-Using-hash_map-oror-Self-explanatory
class Solution: def getHint(self, secret: str, guess: str) -> str: bulls=0 cows=0 out='' secret=[i for i in secret] guess=[i for i in guess] hash1={} hash2={} for i in range(len(guess)): if secret[i]==guess[i]: bulls+=1 secret[i]='' guess[i]='' for i in secret: if i!='': if i in hash1: hash1[i]+=1 else: hash1[i]=1 for i in guess: if i!='': if i in hash2: hash2[i]+=1 else: hash2[i]=1 for i in hash1: if i in hash2: cows+=min(hash1[i],hash2[i]) out=str(bulls)+'A'+str(cows)+'B' return out
bulls-and-cows
Python3 || Easy Understandable || Using hash_map || Self explanatory
bug_buster
0
86
bulls and cows
299
0.487
Medium
5,296
https://leetcode.com/problems/bulls-and-cows/discuss/1085410/fast-and-clear-solution
class Solution: def getHint(self, secret: str, guess: str) -> str: z=zip(secret,guess) bulls=0 cows=0 for x,y in z: if x==y: bulls+=1 s=Counter(secret) g=Counter(guess) for x in g.keys(): if x in s: cows+=min(g[x],s[x]) cows-=bulls #to remove bulls in cows return str(bulls)+'A'+str(cows)+'B'
bulls-and-cows
fast and clear solution
sarthakraheja
0
84
bulls and cows
299
0.487
Medium
5,297
https://leetcode.com/problems/bulls-and-cows/discuss/736774/Python3-Old-style-buy-easy-to-read-and-New-Style
class Solution: def getHint(self, secret: str, guess: str) -> str: a, b = 0, 0 for idx, ch in enumerate(guess): if ch in secret: if secret[idx] == guess[idx]: a += 1 secret = secret[:idx] + 'X' + secret[idx+1:] guess = guess[:idx] + 'O' + guess[idx+1:] for idx, ch in enumerate(guess): if ch in secret: temp = secret.index(ch) secret = secret[:temp] + 'X' + secret[temp+1:] b += 1 return f'{a}A{b}B'
bulls-and-cows
Python3 Old style buy easy to read and New Style
sexylol
0
59
bulls and cows
299
0.487
Medium
5,298
https://leetcode.com/problems/bulls-and-cows/discuss/736774/Python3-Old-style-buy-easy-to-read-and-New-Style
class Solution: def getHint(self, secret: str, guess: str) -> str: a = sum(s == g for s,g in zip(secret, guess)) b = collections.Counter(secret) &amp; collections.Counter(guess) return f'{a}A{sum(b.values()) - a}B'
bulls-and-cows
Python3 Old style buy easy to read and New Style
sexylol
0
59
bulls and cows
299
0.487
Medium
5,299