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/number-of-different-integers-in-a-string/discuss/2416756/Python-Easy-Using-Hashmao | class Solution:
def makeEqual(self, words: List[str]) -> bool:
s="".join(words)
d,n={},len(words)
for i in s:d[i]=d.get(i,0)+1
for i in d.values():
if i%n!=0:return False
else:return True | number-of-different-integers-in-a-string | Python Easy Using Hashmao | imamnayyar86 | 0 | 27 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,800 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2416660/Python-Beginner-Friendly(add-a-word-in-end) | class Solution:
def numDifferentIntegers(self, word: str) -> int:
word=word+"x"
i=0
c=set()
n=len(word)
while i <n:
z=i
while i<n and word[i].isnumeric():
i+=1
if word[z:i]:c.add(int(word[z:i]))
i+=1
return len(c) | number-of-different-integers-in-a-string | Python Beginner Friendly(add a word in end) | imamnayyar86 | 0 | 24 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,801 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2324373/Easy-for-loop-Python | class Solution:
def numDifferentIntegers(self, word: str) -> int:
ans=set()
temp=''
l=len(word)
for i in range(l):
if word[i].isdigit():
temp+=word[i]
elif temp:
ans.add(int(temp))
temp=''
if (i==l-1) & (temp!=''):
ans.add(int(temp))
return len(ans) | number-of-different-integers-in-a-string | Easy for loop Python | sunakshi132 | 0 | 41 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,802 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2268641/Python-1-Liner | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return len(set([int(x) for x in "".join([ch if ch.isdigit() else " " for ch in word]).strip(" ").split()])) | number-of-different-integers-in-a-string | Python 1-Liner | amaargiru | 0 | 43 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,803 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2103920/Python-oneliner | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return len({int(x) for x in re.split(r'[^0-9]', word) if x}) | number-of-different-integers-in-a-string | Python oneliner | StikS32 | 0 | 74 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,804 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2034834/O(N)-91-Faster-2-Solution-(1st-is-optimal-2nd-is-neater) | class Solution:
def numDifferentIntegers(self, word: str) -> int:
res = set()
num = ""
for char in word + " ":
if char.isdigit():
num += char
elif num:
res.add(int(num))
num = ""
return len(res) | number-of-different-integers-in-a-string | O(N) 91% Faster 2 Solution (1st is optimal 2nd is neater) | andrewnerdimo | 0 | 62 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,805 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/2034834/O(N)-91-Faster-2-Solution-(1st-is-optimal-2nd-is-neater) | class Solution:
def numDifferentIntegers(self, word: str) -> int:
nums = "".join(n if n.isdigit() else " " for n in word).split()
res = set([int(n) for n in nums])
return len(res) | number-of-different-integers-in-a-string | O(N) 91% Faster 2 Solution (1st is optimal 2nd is neater) | andrewnerdimo | 0 | 62 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,806 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1989072/Python-easy-solution-faster-than-92 | class Solution:
def numDifferentIntegers(self, word: str) -> int:
dig_str = ""
for i in word:
if i.isnumeric():
dig_str += i
else:
dig_str += " "
return len(set([int(x) for x in dig_str.split()])) | number-of-different-integers-in-a-string | Python easy solution faster than 92% | alishak1999 | 0 | 92 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,807 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1936449/Python-Clean-and-Simple-or-Explanation-or-Set-%2B-Math-%2B-Loop | class Solution:
def numDifferentIntegers(self, word):
nums, num, m, i = set(), None, 1, len(word)-1
while i >= 0:
c = word[i]
if c.isdigit():
if num is None: num = int(c)
else: num += int(c)*m
m *= 10
else:
if num is not None:
nums.add(num)
num, m = None, 1
i -= 1
if num is not None: nums.add(num)
return len(nums) | number-of-different-integers-in-a-string | Python - Clean and Simple | Explanation | Set + Math + Loop | domthedeveloper | 0 | 50 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,808 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1918969/Easiest-and-Simplest-Python3-Solution-or-Easy-to-understand-or-100-Faster | class Solution:
def numDifferentIntegers(self, word: str) -> int:
ss=""
temp=[]
for i in word:
if i.isnumeric():
ss=ss+i
else:
ss=ss+" "
ss=ss.split(" ")
for j in ss:
if j!='' and j not in temp and int(j) not in temp:
temp.append(int(j))
return (len(temp)) | number-of-different-integers-in-a-string | Easiest & Simplest Python3 Solution | Easy to understand | 100% Faster | RatnaPriya | 0 | 32 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,809 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1835512/Straightforward-python-solution | class Solution:
def numDifferentIntegers(self, word: str) -> int:
numSet = set()
i = 0
while i < len(word):
digit = ''
while i < len(word) and word[i].isdigit():
digit += word[i]
i+=1
if digit != '':
if digit.startswith('0'):
digit = digit.lstrip('0')
numSet.add(digit)
i+=1
return len(numSet) | number-of-different-integers-in-a-string | Straightforward python solution | htalanki2211 | 0 | 49 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,810 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1800958/3-Lines-Python-Solution-oror-80-Faster-oror-Memory-less-than-60 | class Solution:
def numDifferentIntegers(self, word: str) -> int:
for char in word:
if char.isalpha(): word = word.replace(char,' ',1)
return len(set([x.lstrip('0') for x in word.split(' ') if x!=''])) | number-of-different-integers-in-a-string | 3-Lines Python Solution || 80% Faster || Memory less than 60% | Taha-C | 0 | 60 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,811 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1743499/Python3-Simple-or-O(n)-or-Beats-95-in-Memory | class Solution:
def numDifferentIntegers(self, word: str) -> int:
ll = [str(i) for i in range(10)]
mast = []
temp = ""
for i in range(len(word)):
if word[i] in ll:
temp+=word[i]
else:
if temp:
mast.append(int(temp))
temp = ""
if i == len(word)-1 and temp:
mast.append(int(temp))
return len(set(mast)) | number-of-different-integers-in-a-string | Python3 Simple | O(n) | Beats 95% in Memory | veerbhansari | 0 | 67 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,812 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1510842/Regex-findall-91-speed | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return len(set(map(int, re.findall(r"\d+", word)))) | number-of-different-integers-in-a-string | Regex findall, 91% speed | EvgenySH | 0 | 60 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,813 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1502311/python-o(n)-time-o(n)-space-solution-with-two-pointers | class Solution:
def numDifferentIntegers(self, word: str) -> int:
n = len(word)
start, end = 0, 0
stringset = set()
def remove_zeros(string):
m = len(string)
i = 0
while i <= m-1 and string[i] == "0":
i += 1
return string[i:]
while start <= end and end <= n-1:
if word[start].isalpha():
#print(start)
end += 1
else: # num starts
end = start
while end <= n-1 and not word[end].isalpha():
end += 1
stringset.add(remove_zeros(word[start:end]))
start = end
return len(stringset) | number-of-different-integers-in-a-string | python o(n) time, o(n) space solution with two-pointers | byuns9334 | 0 | 78 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,814 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1494890/1-line-solution-in-Python-using-re | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return int(word.isdigit()) or len(set(re.sub(r"^0+", "", w) for w in re.split(r"[a-z]+", word) if w)) | number-of-different-integers-in-a-string | 1-line solution in Python, using re | mousun224 | 0 | 64 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,815 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1494890/1-line-solution-in-Python-using-re | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return int(word.isdigit()) or len(set(int(w) for w in re.findall(r"\d+", word))) | number-of-different-integers-in-a-string | 1-line solution in Python, using re | mousun224 | 0 | 64 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,816 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1393753/Runtime%3A-36-ms-faster-than-30.28-of-Python3-online-submissions | class Solution:
def numDifferentIntegers(self, word: str) -> int:
i=0
c=0
s=set()
while(i<len(word)):
if word[i].isdigit():
a=""
while(i<len(word) and word[i].isdigit()):
a+=word[i]
i+=1
s.add(int(a))
i+=1
return len(s) | number-of-different-integers-in-a-string | Runtime: 36 ms, faster than 30.28% of Python3 online submissions | harshmalviya7 | 0 | 61 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,817 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1390533/Python3-Memory-Less-Than-95.80-Faster-Than-68.73 | class Solution:
def numDifferentIntegers(self, word: str) -> int:
ss, c = "", set()
for i in word:
if i.isalpha():
if len(ss) > 0:
c.add(int(ss))
ss = ""
continue
else:
ss += i
if len(ss) == 0:
return len(c)
else:
if int(ss) not in c:
return len(c) + 1
return len(c) | number-of-different-integers-in-a-string | Python3 Memory Less Than 95.80%, Faster Than 68.73% | Hejita | 0 | 56 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,818 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1358509/Speed-Faster-then-97.73-Memory-Usage%3A-less-than-94.74-Python3-Submissions | class Solution:
def numDifferentIntegers(self, word: str) -> int:
import string
result = string.ascii_lowercase
word = [item for item in word]
for i in range(0,len(word)):
if word[i] in result :
word[i]= ","
new = ("".join(word))
something = ([int(item) for item in set(new.split(",")) if item != ""])
return (len(set(something))) | number-of-different-integers-in-a-string | Speed Faster then 97.73%, Memory Usage: less than 94.74% Python3 Submissions | xevb | 0 | 74 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,819 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1323019/Python-3-oror-One-line-Solution-oror-Regular-Expression | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return(len(set(map(int,re.findall('[0-9]+',word))))) | number-of-different-integers-in-a-string | Python 3 || One line Solution || Regular Expression | Suryanandhu | 0 | 69 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,820 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1320631/Python-oror-24-ms-faster-than-96.99-oror-Memory-Usage%3A-13.9-MB-less-than-98.93 | class Solution:
def numDifferentIntegers(self, word: str) -> int:
return len(set(int(e) for e in re.sub(r'[a-zA-Z]+',' ', word).split())) | number-of-different-integers-in-a-string | Python || 24 ms, faster than 96.99% || Memory Usage: 13.9 MB, less than 98.93% | ZoS | 0 | 60 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,821 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1199236/Python3-solution-using-ascii-number | class Solution:
def numDifferentIntegers(self, word: str) -> int:
nums = [] # array initialization
s = ""
for i in range(len(word)):
if ord(word[i]) > 47 and ord(word[i]) < 58: # check whether number or not using ascii
s += word[i]
else:
if(s != ""):
nums.append(int(s))
s = ""
if(s != ""):
nums.append(int(s))
return len(set(nums)) | number-of-different-integers-in-a-string | Python3 solution using ascii number | zharfanf | 0 | 81 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,822 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1135972/Python3-simple-solution | class Solution:
def numDifferentIntegers(self, word: str) -> int:
i,j = 0,0
s = set()
while j < len(word):
if word[j].isdigit():
j += 1
elif i < j:
s.add(word[i:j].lstrip('0'))
j += 1
i = j
else:
i += 1
j += 1
if i != j:
s.add(word[i:j].lstrip('0'))
return len(s) | number-of-different-integers-in-a-string | Python3 simple solution | EklavyaJoshi | 0 | 97 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,823 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1134970/Python-Fast-and-Efficient | class Solution:
def numDifferentIntegers(self, word: str) -> int:
numbers = set()
number = []
for char in word:
if char.isdigit():
number.append(char)
elif number:
numbers.add(int(''.join(number)))
number = []
if number:
numbers.add(int(''.join(number)))
return len(numbers) | number-of-different-integers-in-a-string | Python Fast and Efficient | alexanco | 0 | 151 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,824 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1131722/Python-one-for-loop-%2B-set | class Solution:
def numDifferentIntegers(self, word: str) -> int:
nums = set()
start = 0
for i, c in enumerate(word):
if c.isdigit():
if i and not word[i-1].isdigit():
start = i
if i == len(word) - 1 or not word[i+1].isdigit():
nums.add(int(word[start:i+1]))
return len(nums) | number-of-different-integers-in-a-string | Python, one for loop + set | blue_sky5 | 0 | 42 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,825 |
https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1131139/Python-3-solution-faster-than-100 | class Solution:
def numDifferentIntegers(self, word: str) -> int:
nums = "0123456789"
for i in range(len(word)):
if word[i] not in nums:
word = word.replace(word[i], " ")
w = word.split()
for i in range(len(w)):
w[i] = int(w[i])
w = set(w)
return len(w) | number-of-different-integers-in-a-string | Python 3 solution faster than 100% | VIkingKing657 | 0 | 54 | number of different integers in a string | 1,805 | 0.362 | Easy | 25,826 |
https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/discuss/1130760/Python3-simulation | class Solution:
def reinitializePermutation(self, n: int) -> int:
ans = 0
perm = list(range(n))
while True:
ans += 1
perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]
if all(perm[i] == i for i in range(n)): return ans | minimum-number-of-operations-to-reinitialize-a-permutation | [Python3] simulation | ye15 | 4 | 217 | minimum number of operations to reinitialize a permutation | 1,806 | 0.714 | Medium | 25,827 |
https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/discuss/2107225/Learned-solution-from-Alex-Lyan | class Solution:
def reinitializePermutation(self, n: int) -> int:
res = 0
perm = list(range(n))
p = perm.copy()
arr = [0] * n
while arr != p:
res += 1
for i in range(n):
if not i % 2:
arr[i] = perm[i // 2]
else:
arr[i] = perm[n // 2 + (i - 1) // 2]
perm = arr.copy()
return res | minimum-number-of-operations-to-reinitialize-a-permutation | Learned solution from Alex Lyan | andrewnerdimo | 0 | 50 | minimum number of operations to reinitialize a permutation | 1,806 | 0.714 | Medium | 25,828 |
https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/discuss/1198588/Python3-simple-solution-using-brute-force-approach | class Solution:
def reinitializePermutation(self, n: int) -> int:
perm = list(range(n))
count = 0
temp = perm.copy()
while True:
arr = [0]*n
for i in range(n):
if i%2 == 0:
arr[i] = perm[i//2]
else:
arr[i] = perm[n//2+(i-1)//2]
perm = arr.copy()
count += 1
if temp == perm:
return count | minimum-number-of-operations-to-reinitialize-a-permutation | Python3 simple solution using brute force approach | EklavyaJoshi | 0 | 116 | minimum number of operations to reinitialize a permutation | 1,806 | 0.714 | Medium | 25,829 |
https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/discuss/1130603/Easy-Python-(List-Clone) | class Solution:
def reinitializePermutation(self, n: int) -> int:
perm=[i for i in range(n)]
op=list(perm)
arr=[0]*n
c=0
nn=n//2
while arr!=op:
for i in range(n):
if i%2 == 0:
arr[i] = perm[i // 2]
else:
arr[i] = perm[int(nn + (i - 1) // 2)]
perm = list(arr)
c+=1
return c | minimum-number-of-operations-to-reinitialize-a-permutation | Easy Python (List Clone) | harshvivek14 | 0 | 77 | minimum number of operations to reinitialize a permutation | 1,806 | 0.714 | Medium | 25,830 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1286887/Python-or-Dictionary-or-Simple-Solution | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
knowledge = dict(knowledge)
answer, start = [], None
for i, char in enumerate(s):
if char == '(':
start = i + 1
elif char == ')':
answer.append(knowledge.get(s[start:i], '?'))
start = None
elif start is None:
answer.append(char)
return ''.join(answer) | evaluate-the-bracket-pairs-of-a-string | Python | Dictionary | Simple Solution | leeteatsleep | 2 | 102 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,831 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1130707/Straightforward-Python-Dictionary-solution | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
K = { k[0] : k[1] for k in knowledge}
stack = []
for ch in s:
if ch != ')':
stack.append(ch)
else:
word = []
while stack[-1] != '(':
word.append(stack.pop())
stack.pop()
stack.append(K.get(''.join(word[::-1]), '?'))
return ''.join(stack) | evaluate-the-bracket-pairs-of-a-string | Straightforward Python Dictionary solution | Black_Pegasus | 2 | 117 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,832 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1130526/python-using-dic-very-easy-solution | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
dic ={}
for a,b in knowledge:
dic[a] = b
res, temp = '', ''
isopened = False
for i in range(len(s)):
if s[i] == '(':
isopened = True
elif s[i] == ')':
key = temp
if key in dic:
res = res + dic[key]
else:
res = res + '?'
temp = ''
isopened = False
elif isopened == False:
res = res + s[i]
elif isopened == True:
temp = temp + s[i]
return res | evaluate-the-bracket-pairs-of-a-string | python using dic very easy solution | deleted_user | 2 | 134 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,833 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1547361/Python-hashmap-dictionary-faster-than-96 | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
hashmap = collections.defaultdict(lambda: '?')
for pair in knowledge:
hashmap['(' + pair[0] + ')'] = pair[1]
res = ''
cur = ''
flag = False
for c in s:
if flag:
cur += c
if c == ')':
res += hashmap[cur]
cur = ''
flag = False
else:
if c == '(':
flag = True
cur += c
else:
res += c
return res | evaluate-the-bracket-pairs-of-a-string | Python hashmap / dictionary faster than 96% | dereky4 | 1 | 66 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,834 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1189716/Python3-simple-solution-using-dictionary | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d= {}
for i in knowledge:
d[i[0]] = i[1]
z = ''
x = ''
flag = False
for i in s:
if i == '(':
flag = True
elif i == ')':
flag = False
z += d.get(x,'?')
x = ''
elif flag:
x += i
else:
z += i
return z | evaluate-the-bracket-pairs-of-a-string | Python3 simple solution using dictionary | EklavyaJoshi | 1 | 54 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,835 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1171379/Python | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
dct = {kn[0]: kn[1] for kn in knowledge}
res = []
temp = None
for index, value in enumerate(s):
if value == '(':
temp = index
elif value == ')':
res.append(dct.get(s[temp+1:index], '?'))
temp = None
elif temp is None:
res.append(value)
return ''.join(res) | evaluate-the-bracket-pairs-of-a-string | [Python] | cruim | 1 | 54 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,836 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1130768/Python3-sweep | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
mp = dict(knowledge)
i = 0
ans = []
while i < len(s):
if s[i] == "(":
ii = i
while ii < len(s) and s[ii] != ")":
ii += 1
ans.append(mp.get(s[i+1:ii], "?"))
i = ii+1
else:
ans.append(s[i])
i += 1
return "".join(ans) | evaluate-the-bracket-pairs-of-a-string | [Python3] sweep | ye15 | 1 | 36 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,837 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/2743043/Python3-Iterative-approach-with-dict | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
# make a dict with the knowledge
know = collections.defaultdict(lambda: '?')
for key, value in knowledge:
know[key] = value
# go through the string
bracket = -1
result = []
for idx, char in enumerate(s):
if char == '(':
bracket = idx
elif char == ')':
result.append(know[s[bracket+1:idx]])
bracket = -1
elif bracket < 0:
result.append(char)
return "".join(result) | evaluate-the-bracket-pairs-of-a-string | [Python3] - Iterative approach with dict | Lucew | 0 | 4 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,838 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1968271/Simple-Python-Solution-with-explanation-Time-(O(n))-or-70-Faster-or-Memory-less-than-85 | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d={}
for i in knowledge:
if i[0] not in d:
d[i[0]]=i[1]
s=s.split('(')
final = []
for i in s:
if ')' not in list(i):
final.append(i)
else:
i=i.split(')')
if i[0] in d:
final.append(d[i[0]])
else:
final.append('?')
final.append(i[1])
return ''.join(final) | evaluate-the-bracket-pairs-of-a-string | Simple Python Solution with explanation - Time (O(n)) | 70% Faster | Memory less than 85% | eerie997 | 0 | 36 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,839 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1348852/Stack-and-dictionary | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
vocabulary = {key: val for key, val in knowledge}
stack, idx = [], 0
for c in s:
if c == ")":
word = "".join(stack[idx + 1:])
stack = stack[:idx]
if word in vocabulary:
stack.append(vocabulary[word])
else:
stack.append("?")
elif c == "(":
idx = len(stack)
stack.append(c)
else:
stack.append(c)
return "".join(stack) | evaluate-the-bracket-pairs-of-a-string | Stack and dictionary | EvgenySH | 0 | 44 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,840 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1271214/Python-simple-dictionary-approach | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
i=0
d={}
for b in knowledge:
d[b[0]]=b[1]
while(i<len(s)):
if(s[i]=='('):
g=i
i=i+1
k=''
while(s[i]!=')'):
k=k+s[i]
i=i+1
if(k in d.keys()): k=d[k]
else: k='?'
s=s[:g]+k+s[i+1:]
i=g-1
i=i+1
return s | evaluate-the-bracket-pairs-of-a-string | Python simple dictionary approach | Rajashekar_Booreddy | 0 | 42 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,841 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1181505/python-regex | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
d = dict(knowledge)
a = lambda x: d.get(x.group(0)[1:-1], '?')
return re.sub('\([a-z]+\)', a, s) | evaluate-the-bracket-pairs-of-a-string | python regex | Hoke_luo | 0 | 30 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,842 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1141228/Intuitive-approach-by-using-stack | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
kdict = {}
for k, v in knowledge:
kdict[k] = v
cstack = []
def pop_key():
reverse_key = []
while cstack[-1] != '(':
reverse_key.append(cstack.pop())
cstack.pop()
key = "".join(reverse_key[::-1])
cstack.extend(list(kdict.get(key, "?")))
for c in s:
if c == ')':
pop_key()
else:
cstack.append(c)
return "".join(cstack) | evaluate-the-bracket-pairs-of-a-string | Intuitive approach by using stack | puremonkey2001 | 0 | 27 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,843 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1130978/Python3-Straight-Forward-Solution-with-explanation | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
stack,hmap = [], {}
for word in knowledge:
hmap[word[0]] = word[1]
i = 0
while i < len(s):
if s[i] == ')':
#temp will contain the word (which is in between brackets)and we will check if the word is in Hashtable e.g. temp = 'name'
temp = ''
while stack[-1] != '(':
temp += stack.pop()
# pop the starting bracket '('
stack.pop()
# checking if the word is in hashmap
if temp[::-1] in hmap:
# if the word is in hashtable, we will add each letter onto stack, '?' otherwise.
stack.extend(list(hmap[temp[::-1]]))
else:
stack.append('?')
else:
#keep adding the elements onto the stack until closing bracket comes.
stack.append(s[i])
i += 1
return ''.join(stack) | evaluate-the-bracket-pairs-of-a-string | [Python3] Straight Forward Solution [with explanation] | pratushah | 0 | 27 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,844 |
https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1130857/Easy-python-solution-few-lines-of-code | class Solution:
def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
answers = {}
keys = [n.split('(')[-1] for n in s.split(')')][:-1]
for k, v in knowledge:
answers[k] = v
for key in keys:
s = s.replace(f'({key})', answers.get(key, '?'))
return s | evaluate-the-bracket-pairs-of-a-string | Easy python solution, few lines of code | gates55434 | 0 | 30 | evaluate the bracket pairs of a string | 1,807 | 0.667 | Medium | 25,845 |
https://leetcode.com/problems/maximize-number-of-nice-divisors/discuss/1130780/Python3-math | class Solution:
def maxNiceDivisors(self, primeFactors: int) -> int:
mod = 1_000_000_007
if primeFactors % 3 == 0: return pow(3, primeFactors//3, mod)
if primeFactors % 3 == 1: return 1 if primeFactors == 1 else 4*pow(3, (primeFactors-4)//3, mod) % mod
return 2*pow(3, primeFactors//3, mod) % mod | maximize-number-of-nice-divisors | [Python3] math | ye15 | 2 | 74 | maximize number of nice divisors | 1,808 | 0.313 | Hard | 25,846 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1140948/PythonPython3-or-Simple-and-Easy-code-or-self-explanatory | class Solution:
def squareIsWhite(self, c: str) -> bool:
if c[0] in 'aceg':
return int(c[1])%2==0
elif c[0] in 'bdfh':
return int(c[1])%2==1
return False | determine-color-of-a-chessboard-square | [Python/Python3 | Simple and Easy code | self-explanatory | Sukhdev_143 | 12 | 513 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,847 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2277434/PYTHON-3-EASY-or-SELF-EXPLANITORY | class Solution:
def squareIsWhite(self, c: str) -> bool:
e,o = ["b","d","f","h"], ["a","c","e","g"]
if int(c[-1]) % 2 == 0:
if c[0] in e: return False
else: return True
else:
if c[0] in e: return True
else: return False | determine-color-of-a-chessboard-square | [PYTHON 3] EASY | SELF EXPLANITORY | omkarxpatel | 2 | 55 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,848 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1140664/Python-1-lines | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
return True if ((ord(coordinates[0]))+int(coordinates[1])) % 2 else False | determine-color-of-a-chessboard-square | [Python] 1-lines | maiyude | 2 | 116 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,849 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2773815/1-line-solution-with-%22ord%22-O(1) | class Solution:
def squareIsWhite(self, C: str) -> bool:
return (ord(C[0]) + ord(C[1])) & 1 | determine-color-of-a-chessboard-square | 1 line solution with "ord" O(1) | Mencibi | 1 | 39 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,850 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2702360/Python-O(1) | class Solution:
def squareIsWhite(self, c: str) -> bool:
if c[0]=="a" and int(c[-1])%2==0:
return True
if c[0]=="b" and int(c[-1])%2==1:
return True
if c[0]=="c" and int(c[-1])%2==0:
return True
if c[0]=="d" and int(c[-1])%2==1:
return True
if c[0]=="e" and int(c[-1])%2==0:
return True
if c[0]=="f" and int(c[-1])%2==1:
return True
if c[0]=="g" and int(c[-1])%2==0:
return True
if c[0]=="h" and int(c[-1])%2==1:
return True
return False | determine-color-of-a-chessboard-square | [Python O(1) ] | Sneh713 | 1 | 84 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,851 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2499408/Simple-if-else-faster-than-83 | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
black = "aceg"
white = "bdfh"
if coordinates[0] in black and int(coordinates[1]) % 2 == 1:
return False
elif coordinates[0] in white and int(coordinates[1]) % 2 == 0:
return False
else:
return True | determine-color-of-a-chessboard-square | Simple if-else faster than 83% | aruj900 | 1 | 62 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,852 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2420004/Python-99-Faster-(-Simple-Solution-) | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
c = coordinates
a,b = "aceg","bdfh"
for i in range(0,len(c)):
if (( c[0] in a ) and ( int(c[1])%2 != 0 )) or (( c[0] in b ) and ( int(c[1])%2 == 0 )):
return False
return True | determine-color-of-a-chessboard-square | Python 99% Faster ( Simple Solution ) | SouravSingh49 | 1 | 41 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,853 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2339118/Python3-or-Simple-logic-faster-than-92 | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
# Convert to [int, int]
first_8_chars = ["a","b","c","d","e","f","g","h"]
numerical_coordinate = [(int(first_8_chars.index(coordinates[0]))+1), int(coordinates[1])]
# Then check if coordinate is white
if numerical_coordinate[0]%2 != 0 and numerical_coordinate[1]%2 != 0: #odd odd
return False
elif numerical_coordinate[0]%2 != 0 and numerical_coordinate[1]%2 == 0: #odd even:
return True
elif numerical_coordinate[0]%2 == 0 and numerical_coordinate[1]%2 != 0: #even odd:
return True
else: #even even
return False | determine-color-of-a-chessboard-square | Python3 | Simple logic faster than 92% | AndrewNgKF | 1 | 26 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,854 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2320321/Solution-(Faster-than-96-) | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
a = int(ord(coordinates[0]))% 2
b = int(coordinates[1]) % 2
if (a == 0 and b != 0):
return True
elif (a != 0 and b == 0):
return True | determine-color-of-a-chessboard-square | Solution (Faster than 96 %) | fiqbal997 | 1 | 31 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,855 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2320321/Solution-(Faster-than-96-) | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
a = int(ord(coordinates[0])) + int(coordinates[1])
if (a % 2 != 0):
return True | determine-color-of-a-chessboard-square | Solution (Faster than 96 %) | fiqbal997 | 1 | 31 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,856 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2833279/Python-Solution-T.C-%3A-0(1)-100-faster | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
if (ord(coordinates[0])%2!=0 and int(coordinates[1])%2==0 ) or (ord(coordinates[0])%2==0 and int(coordinates[1])%2!=0 ):
return True
return False | determine-color-of-a-chessboard-square | Python Solution T.C :- 0(1) 100% faster | kartik_5051 | 0 | 1 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,857 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2813064/Optimal-and-Clean-O(1)-time-and-O(1)-space | class Solution:
# ASCII of 'a' is 97 : '1' is 49
# meaning if we add them and the sum is even the square is black.
# and if the sum is odd, the square is white
# O(1) time : O(1) space
def squareIsWhite(self, coordinates: str) -> bool:
return (ord(coordinates[0]) + ord(coordinates[1])) % 2 | determine-color-of-a-chessboard-square | Optimal and Clean - O(1) time and O(1) space | topswe | 0 | 1 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,858 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2786360/python-solution-calculating-odd-and-even-indexes | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
nums = ['1', '2', '3', '4', '5', '6', '7', '8']
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
if letters.index(coordinates[0]) % 2 == 0 and nums.index(coordinates[1]) % 2 != 0 or letters.index(
coordinates[0]) % 2 != 0 and nums.index(coordinates[1]) % 2 == 0:
return True
return False | determine-color-of-a-chessboard-square | python solution calculating odd and even indexes | samanehghafouri | 0 | 3 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,859 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2778174/Determine-Color-Of-a-Chessboard-square-or-if-else-or-Python | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
a="abcdefgh"
if (a.index(coordinates[0])+1) %2!=0 and int(coordinates[1])%2!=0:
return False
elif (a.index(coordinates[0])+1) %2==0 and int(coordinates[1])%2!=0:
return True
elif (a.index(coordinates[0])+1) %2!=0 and int(coordinates[1])%2==0:
return True
else:
return False | determine-color-of-a-chessboard-square | Determine Color Of a Chessboard square | if else | Python | saptarishimondal | 0 | 2 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,860 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2640766/100-EASY-TO-UNDERSTANDSIMPLECLEAN | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
strlist=[i for a,i in enumerate(coordinates)]
for i in range(len(strlist)):
if strlist[i] == "a" or strlist[i] == "c" or strlist[i] == "e" or strlist[i] == "g":
if int(strlist[1])%2==0:
return True
else:
return False
else:
if int(strlist[1])%2==1:
return True
else:
return False | determine-color-of-a-chessboard-square | 🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥 | YuviGill | 0 | 25 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,861 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2635570/Python-easy-to-understand-solution | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
diction = {}
letters = "abcdefgh"
i = 0
for letter in letters:
diction[letter] = i
i += 1
#make dictionary of pattern {evenLetter:evenInt, oddLetter:oddInt}
coor = coordinates.split()
if diction[coordinates[0]] % 2 == 0:
#is letter even?
if int(coordinates[1]) % 2 == 0:
#is number even?
return True
#if letter is even and tile square number is even
#then tile color must be white
#even letter even num
elif diction[coordinates[0]] % 2 == 1:
#is letter odd?
if int(coordinates[1]) % 2 == 1:
#is number odd?
return True
#if letter is odd and tile square number is odd
#then tile color must be odd
else:
return False
#we have covered both cases where the tile would be white
#so in every other case the tile must be black | determine-color-of-a-chessboard-square | Python easy to understand solution | rcooper47 | 0 | 6 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,862 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2624591/PYTHON3-SIMPLEEASYCLEAN-SOLUTION | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
strlist=[i for a,i in enumerate(coordinates)]
for i in range(len(strlist)):
if strlist[i] == "a" or strlist[i] == "c" or strlist[i] == "e" or strlist[i] == "g":
if int(strlist[1])%2==0:
return True
else:
return False
else:
if int(strlist[1])%2==1:
return True
else:
return False | determine-color-of-a-chessboard-square | 🔥PYTHON3 SIMPLE/EASY/CLEAN SOLUTION🔥 | YuviGill | 0 | 22 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,863 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2350997/Python-or-1-liner | class Solution(object):
def squareIsWhite(self, coordinates):
return not(ord(coordinates[0])%2 == 0) == (int(coordinates[1])%2 == 0) | determine-color-of-a-chessboard-square | Python | 1 liner | JasminNev | 0 | 27 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,864 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2184254/Simple-8-combinations-in-Python | class Solution:
def squareIsWhite(self, cr: str) -> bool:
cr = list(cr)
if cr[0] == 'a':
if int(cr[1]) % 2 == 0: return True
if int(cr[1]) % 2 != 0: return False
if cr[0] == 'b':
if int(cr[1]) % 2 == 0: return False
if int(cr[1]) % 2 != 0: return True
if cr[0] == 'c':
if int(cr[1]) % 2 == 0: return True
if int(cr[1]) % 2 != 0: return False
if cr[0] == 'd':
if int(cr[1]) % 2 == 0: return False
if int(cr[1]) % 2 != 0: return True
if cr[0] == 'e':
if int(cr[1]) % 2 == 0: return True
if int(cr[1]) % 2 != 0: return False
if cr[0] == 'f':
if int(cr[1]) % 2 == 0: return False
if int(cr[1]) % 2 != 0: return True
if cr[0] == 'g':
if int(cr[1]) % 2 == 0: return True
if int(cr[1]) % 2 != 0: return False
if cr[0] == 'h':
if int(cr[1]) % 2 == 0: return False
if int(cr[1]) % 2 != 0: return True | determine-color-of-a-chessboard-square | Simple 8 combinations in Python | ankurbhambri | 0 | 28 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,865 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2136940/Python-3-Solution-or-One-Liner-or-O(1)-Time-and-Space | class Solution:
def squareIsWhite(self, s: str) -> bool:
return False if ((ord(s[0]) - ord('a') + 1) + int(s[1])) % 2 == 0 else True | determine-color-of-a-chessboard-square | Python 3 Solution | One Liner | O(1) Time and Space | Gautam_ProMax | 0 | 28 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,866 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2103906/Python-oneliner | class Solution:
def squareIsWhite(self, c: str) -> bool:
return ([[0,1]*4,[1,0]*4]*4)[ord(c[0])-ord('a')][int(c[1])-1] | determine-color-of-a-chessboard-square | Python oneliner | StikS32 | 0 | 29 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,867 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2046755/Memory-Less-than-94.44-of-Python-online-submissions-for-Determine-Color-of-a-Chessboard-Square. | class Solution(object):
def squareIsWhite(self, coordinates):
"""
:type coordinates: str
:rtype: bool
"""
l="abcdefgh"
row=False
for i in range(1,9):
row=True if row==False else False
for j in range(1,9):
row= True if row==False else False
if coordinates==l[i-1]+str(j):
return row | determine-color-of-a-chessboard-square | Memory Less than 94.44% of Python online submissions for Determine Color of a Chessboard Square. | glimloop | 0 | 35 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,868 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2020865/Python-Solution-%2B-One-Line!-Clean-and-Simple! | class Solution:
def squareIsWhite(self, coordinates):
col, row = coordinates
colNum, rowNum = ord(col) - ord('a'), int(row)
return not ((colNum + rowNum) % 2) | determine-color-of-a-chessboard-square | Python - Solution + One Line! Clean and Simple! | domthedeveloper | 0 | 49 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,869 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2020865/Python-Solution-%2B-One-Line!-Clean-and-Simple! | class Solution:
def squareIsWhite(self, coords):
return not ((ord(coords[0])-ord('a')+int(coords[1]))%2) | determine-color-of-a-chessboard-square | Python - Solution + One Line! Clean and Simple! | domthedeveloper | 0 | 49 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,870 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/2016022/Python-easy-solution | class Solution:
def squareIsWhite(self, e: str) -> bool:
a=["a","b","c","d","e","f","g","h"]
f=["a","c","e","g"]
b=[1,2,3,4,5,6,7,8]
c=zip(a,b)
d=dict(c)
for k,v in d.items():
if(k==e[0] and k in f):
if(int(e[1])%2==0):
return True
else:
return False
if(k==e[0] and k not in f):
if(int(e[1])%2==0):
return False
else:
return True | determine-color-of-a-chessboard-square | Python easy solution | Durgavamsi | 0 | 39 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,871 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1884245/Python-easy-solution-with-memory-usage-less-than-98 | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
if coordinates[0] in ['a', 'c', 'e', 'g']:
if int(coordinates[1]) % 2 == 0:
return True
return False
else:
if int(coordinates[1]) % 2 == 0:
return False
return True | determine-color-of-a-chessboard-square | Python easy solution with memory usage less than 98% | alishak1999 | 0 | 47 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,872 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1873912/very-simple-Python-orpython3or-one-linerorsimple-and-well-explainedorbruteforce | class Solution:
def squareIsWhite(self, s: str) -> bool:
# BRUTE FORCE
n1,n2=int(s[1]),ord(s[0])-96
if n1%2==0:
if n2%2==0:
return False #even then even False
return True #even then odd True
else:
if n2%2==0:
return True #odd then odd False
return False #odd then even True | determine-color-of-a-chessboard-square | very simple Python 🐍|python3| one-liner|simple and well explained|bruteforce | YaBhiThikHai | 0 | 23 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,873 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1868168/Python-Easy-and-Efficient-Solution | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
row = ord(coordinates[0]) - 96
col = int(coordinates[1])
result = row + col
return result % 2 != 0 | determine-color-of-a-chessboard-square | Python Easy and Efficient Solution | hardik097 | 0 | 23 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,874 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1859161/Python-dollarolution-(Faster-than-95) | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
letters = 'abcdefgh'
return (letters.index(coordinates[0]) + int(coordinates[1]))%2 == 0
class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
letters = 'abcdefgh'
x = letters.index(coordinates[0]) + 1
y = int(coordinates[1])
while x != 1:
x -= 1
y += 1
return (y%2 == 0) | determine-color-of-a-chessboard-square | Python $olution (Faster than 95%) | AakRay | 0 | 28 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,875 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1684555/Simple-Python3-Implementation | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
col = ord(coordinates[0]) - 96 # 'a' as 1 and 'h' as 8
row = int(coordinates[1])
return col & 1 != row & 1 | determine-color-of-a-chessboard-square | Simple Python3 Implementation | atiq1589 | 0 | 45 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,876 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1615320/Too-Ez-1-Liner | class Solution:
def squareIsWhite(self, c: str) -> bool:
return (True if (ord(c[0])-ord('a')+1+int(c[1]))&1 else 0) | determine-color-of-a-chessboard-square | Too Ez 1 Liner | P3rf3ct0 | 0 | 32 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,877 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1593574/Python-3-one-line | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
return ord(coordinates[0]) % 2 != int(coordinates[1]) % 2 | determine-color-of-a-chessboard-square | Python 3 one line | dereky4 | 0 | 56 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,878 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1372970/Python3-with-Explanation | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
abc = coordinates[0]
num = int(coordinates[1])
# use ONE based index for letters
# search for the 1 based index of the first character in coordinates
# look at pairs: a1 would be 1 and 1, and that's black. any odd number with any odd number is black, and any even with even is black as well. Anything else will be white
for i in range(0, len(letters)):
if letters[i] == abc:
if (i + 1) % 2 != 0: # if the letter found is odd
if num % 2 != 0:
return False
else:
return True
else: # if the letter found is even
if num % 2 == 0:
return False
else:
return True | determine-color-of-a-chessboard-square | Python3 with Explanation | RobertObrochta | 0 | 67 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,879 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1185357/Python-one-liner | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
return (ord(coordinates[0])-ord('a')+ int(coordinates[1])) %2 == 0 | determine-color-of-a-chessboard-square | Python one liner | Sanjaychandak95 | 0 | 99 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,880 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1184923/Python3-simple-solution-beats-85-users | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
x_odd = ['a','c','e','g']
x_even = ['b','d','f','h']
y_odd = [1,3,5,7]
y_even = [2,4,6,8]
x,y = coordinates[0],int(coordinates[1])
if (x in x_odd and y in y_odd) or (x in x_even and y in y_even):
return False
else:
return True | determine-color-of-a-chessboard-square | Python3 simple solution beats 85% users | EklavyaJoshi | 0 | 67 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,881 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1168782/Python3-1-line | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
return (ord(coordinates[0])-97)&1 == int(coordinates[1])&1 | determine-color-of-a-chessboard-square | [Python3] 1-line | ye15 | 0 | 53 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,882 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1155270/Python-pythonic-solution | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
pattern = 'abcdefgh'
temp = False if not pattern.index(coordinates[0]) % 2 else True
return temp if int(coordinates[1]) % 2 else not temp | determine-color-of-a-chessboard-square | [Python] pythonic solution | cruim | 0 | 72 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,883 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1142988/Intuitive-approach-by-translating-column-in-integer-and-use-oddeven-to-decide-blackwhite | class Solution:
def squareIsWhite(self, c: str) -> bool:
clist = {c:i+1 for i, c in enumerate('abcdefgh')}
# white area locates in position where row+col as odd
# e.g.: a1 => row=1, col=a=1, row+col = 1+1 = 2 (even) as black
# e.g.: a2 => row=2, col=a=1, row+col = 2+1 = 3 (odd) as whilte
# e.g.: b1 => row=1, col=b=2, row+col = 1+2 = 3 (odd) as whilte
return (clist[c[0]] + int(c[1])) % 2 != 0 | determine-color-of-a-chessboard-square | Intuitive approach by translating column in integer and use odd/even to decide black/white | puremonkey2001 | 0 | 37 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,884 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1141457/Python-3-Lines-Parity | class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
char, idx = coordinates
char_coord, idx = ord(char)-ord('a'), int(idx)
return (char_coord % 2) == (idx % 2) | determine-color-of-a-chessboard-square | Python - 3 Lines - Parity | leeteatsleep | 0 | 65 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,885 |
https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1492485/Python-or-one-liner-or-Easy-or-95-faster | class Solution:
def squareIsWhite(self, c: str) -> bool:
return True if (ord(c[0])-96 + int(c[1]))%2!=0 else False | determine-color-of-a-chessboard-square | Python | one liner | Easy | 95% faster | vineetkrgupta | -1 | 74 | determine color of a chessboard square | 1,812 | 0.774 | Easy | 25,886 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/1461165/PYTHON3-Easy-Peezy-code-using-Stack-crisp-and-clear | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
if len(sentence2)>len(sentence1):
return self.areSentencesSimilar(sentence2,sentence1)
sentence1=sentence1.split(" ")
sentence2=sentence2.split(" ")
s1=sentence1[:]
s2=sentence2[:]
while s1[0]==s2[0]:
s1.pop(0)
s2.pop(0)
if not s2:
return True
if not s2:
return True
while s1[-1]==s2[-1]:
s1.pop()
s2.pop()
if not s2:
return True
if not s2:
return True
return False | sentence-similarity-iii | PYTHON3 Easy Peezy code using Stack crisp and clear | mathur17021play | 2 | 102 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,887 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/1350633/Find-prefix-and-suffix-of-lists | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
lst1, lst2 = sentence1.split(" "), sentence2.split(" ")
for i, (a, b) in enumerate(zip(lst1, lst2)):
if a != b:
prefix = i
break
else:
return True
for i, (a, b) in enumerate(zip(lst1[::-1], lst2[::-1])):
if a != b:
suffix = i
break
else:
return True
return prefix + suffix in (len(lst1), len(lst2)) | sentence-similarity-iii | Find prefix and suffix of lists | EvgenySH | 1 | 136 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,888 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/1140635/Python-easy-to-understand-solution-with-comments-for-explanation | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
if sentence1 == sentence2:
return True
# spplit the sentences into words
words1 = sentence1.split(" ")
words2 = sentence2.split(" ")
# kep the smaller one in words2
if len(words1) < len(words2):
words1, words2 = words2, words1
'''
Keep following states during traversal
0. not inserted
1. inserting
2. inserted
'''
inserted = 0
i = 0
j = 0
while(i < len(words1)):
if j >= len(words2):
if inserted == 2:
return False
else:
return True
if words1[i] != words2[j]:
if inserted == 0:
inserted = 1 # start insertion
i += 1 # only move i not j
elif inserted == 1:
i += 1 # keep inserting more words
else: # that means it's 2 .. hence a sentence is already inserted
return False # as not more sentences can be inserted
else: # continue moving
if inserted == 1:
inserted = 2 # set that previously a sentence has already been inserted
i += 1
j += 1
# if we reach here then it means we can do it
return j == len(words2) | sentence-similarity-iii | Python easy to understand solution with comments for explanation | CaptainX | 1 | 118 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,889 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/2761818/Python-O(n)-solution-93-time-80-memory | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
s2 = sentence2.split(' ')
s1 = sentence1.split(' ')
def compare(s1,s2):
idx = 0
for i in range(len(s2)):
if s2[i] == s1[i]:
idx+=1
else:
break
left = s2[idx:]
itemTake = len(s2)-idx
right = s1[len(s1)-itemTake:]
return ' '.join(left) == ' '.join(right)
## alternative way to save memory
## for i in range(idx, len(s2)):
## if s2[i] != s1[len(s1)-len(s2)+i]:
## return False
## return True
if len(s1) > len(s2):
return compare(s1,s2)
else:
return compare(s2,s1) | sentence-similarity-iii | Python O(n) solution 93% time, 80% memory | stanleyyuen_pang | 0 | 6 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,890 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/2631960/Very-easy-solution-in-Python-less-then-10-lines! | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
sentence1, sentence2 = sentence1.split(), sentence2.split()
if len(sentence2) > len(sentence1):
sentence1, sentence2 = sentence2, sentence1
for p in range(len(sentence2)):
if sentence1[p] != sentence2[p]:
return sentence1[-(len(sentence2) - p):] == sentence2[p:]
return True | sentence-similarity-iii | Very easy solution in Python, less then 10 lines! | metaphysicalist | 0 | 6 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,891 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/1169937/Python3-pointers | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
if len(sentence1) < len(sentence2):
sentence1, sentence2 = sentence2, sentence1
words1 = sentence1.split()
words2 = sentence2.split()
lo = 0
while lo < len(words2) and words1[lo] == words2[lo]: lo += 1
hi = -1
while -len(words2) <= hi and words1[hi] == words2[hi]: hi -= 1
return lo - hi -1 >= len(words2) | sentence-similarity-iii | [Python3] pointers | ye15 | 0 | 80 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,892 |
https://leetcode.com/problems/sentence-similarity-iii/discuss/1148708/Simple-Python3-solution-with-prefix-and-suffix-concept | class Solution:
def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:
# this is the solution for comparing char-wise, but the question is asking for word-wise :(
#############################################################################
# According to the 'similarity' definition given,
# if we can insert some chars (could be empty) to make
# inserted sentence1 == sentence2 (assume len(sentence1) <= len(sentence2))
#############################################################################
# Idea:
# view sentence 1 as prefix + arbitrary sentence to insert (possibly empty) + suffix
# view sentence 2 as prefix + middle chars + suffix
# 1. compare sentence1 and sentence2 until they are not matched (it is prefix)
# 2. rest of sentence2 is suffix -> if this suffix exists in sentence1 -> similar (otherwise not)
''' this is the solution for comparing char-wise, but the question is asking for word-wise :(
if len(sentence1) == len(sentence2):
return sentence1 == sentence2
# make sure sentence1 has shorted length
if len(sentence1) > len(sentence2):
sentence1, sentence2 = sentence2, sentence1
# find the end of prefix
# if char is unmatched => compare suffix
for idx, c in enumerate(sentence1):
if not (c == sentence2[idx]):
return sentence1[idx:] == sentence2[-(len(sentence1)-idx):]
return True
'''
# adjust from our char-wise solution
# w for word
s1 = sentence1.split()
s2 = sentence2.split()
if len(s1) == len(s2):
return all([w1==w2 for (w1, w2) in zip(s1, s2)])
# make sure sentence1 has shorted length
if len(s1) > len(s2):
s1, s2 = s2, s1
# find the end of prefix & compare suffix
for idx, w in enumerate(s1):
if not (w == s2[idx]):
return all([w1==w2 for (w1, w2) in zip(s1[idx:], s2[-(len(s1)-idx):])])
return True | sentence-similarity-iii | Simple Python3 solution with prefix & suffix concept | tkuo-tkuo | 0 | 92 | sentence similarity iii | 1,813 | 0.331 | Medium | 25,893 |
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1140577/Accepted-Python-simple-and-easy-to-understand-solution-with-comments | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
# define constants
n = len(nums)
MOD = 10**9 + 7
# handle scenario for no pairs
if n<=1:
return 0
# utility method to calculate reverse of a number
# e.g. rev(123) -> 321
def rev(i):
new = 0
while(i!=0):
r = i%10
new = new*10+r
i = i//10
return new
# calculate frequency of all the diffs
freq_counter = defaultdict(int)
for num in nums:
freq_counter[num-rev(num)] += 1
# for all the frequencies calculate the number of paris
# which is basically nC2 (read as - "n choose 2") -> n*(n-1)/2
answer = 0
for freq in freq_counter.keys():
count = freq_counter[freq]
# note the modulo operation being performed to handle large answer
answer = (answer + (count*(count-1))//2)%MOD
return answer | count-nice-pairs-in-an-array | [Accepted] Python simple and easy to understand solution with comments | CaptainX | 5 | 502 | count nice pairs in an array | 1,814 | 0.42 | Medium | 25,894 |
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1145212/Python-Easy-Solution-Using-Dictionary-or-O(N)-Time-and-Space | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
def rev(num):
return int(str(num)[::-1])
for i in range(len(nums)):
nums[i] = nums[i] - rev(nums[i])
count = 0
freq = {}
for i in nums:
if i in freq.keys(): freq[i] += 1
else: freq[i] = 1
for k, v in freq.items():
count += ((v * (v -1 )) // 2)
return count % (10 ** 9 + 7) | count-nice-pairs-in-an-array | Python Easy Solution Using Dictionary | O(N) Time and Space | vanigupta20024 | 2 | 205 | count nice pairs in an array | 1,814 | 0.42 | Medium | 25,895 |
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1141179/Python-3-or-O(n)-Math-or-Explanation | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
rev_nums = [int(str(num)[::-1]) for num in nums]
c = collections.Counter([i-j for i, j in zip(nums, rev_nums)])
return sum([freq * (freq-1) // 2 for _, freq in c.items() if freq > 1]) % int(1e9+7) | count-nice-pairs-in-an-array | Python 3 | O(n), Math | Explanation | idontknoooo | 2 | 172 | count nice pairs in an array | 1,814 | 0.42 | Medium | 25,896 |
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/2640653/Python-O(N)-O(N) | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
res = 0
groups = collections.defaultdict(int)
for num in nums:
current = int(str(num)[::-1]) - num
res += groups[current]
groups[current] += 1
return res % (10 ** 9 + 7) | count-nice-pairs-in-an-array | Python - O(N), O(N) | Teecha13 | 0 | 9 | count nice pairs in an array | 1,814 | 0.42 | Medium | 25,897 |
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1350959/Default-dict-for-frequencies | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
freq = defaultdict(int)
for n in nums:
freq[n - int("".join(str(n)[::-1]))] += 1
return (sum((n - 1) * n // 2 for n in freq.values() if n > 1) %
1_000_000_007) | count-nice-pairs-in-an-array | Default dict for frequencies | EvgenySH | 0 | 115 | count nice pairs in an array | 1,814 | 0.42 | Medium | 25,898 |
https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1168728/Python3-freq-table | class Solution:
def countNicePairs(self, nums: List[int]) -> int:
ans = 0
freq = defaultdict(int)
for x in nums:
x -= int(str(x)[::-1])
ans += freq[x]
freq[x] += 1
return ans % 1_000_000_007 | count-nice-pairs-in-an-array | [Python3] freq table | ye15 | 0 | 102 | count nice pairs in an array | 1,814 | 0.42 | Medium | 25,899 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.