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/shortest-distance-to-a-character/discuss/2226939/Easiest-Python-solution-with-explanation | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# occurence of charachter in the array.
occ = []
for i in range(len(s)):
if s[i] == c:
occ.append(i)
ans = []
for i in range(len(s)):
#checking distance of each point from occurences ans the selecting the least distance.
tmplst = []
for j in occ:
tmplst.append(abs(i-j))
ans.append(min(tmplst))
return ans | shortest-distance-to-a-character | Easiest Python solution with explanation | EbrahimMG | 1 | 111 | shortest distance to a character | 821 | 0.714 | Easy | 13,300 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2007025/Python-3-Solution-Brute-Force-and-Two-Pointers-2-Solutions | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
req = []
ind_list = []
for i in range(len(s)):
if s[i] == c:
ind_list.append(i)
min_dis = len(s)
for j in range(len(s)):
for k in range(len(ind_list)):
min_dis = min(min_dis, abs(j - ind_list[k]))
req.append(min_dis)
min_dis = len(s)
return req | shortest-distance-to-a-character | Python 3 Solution, Brute Force and Two Pointers - 2 Solutions | AprDev2011 | 1 | 121 | shortest distance to a character | 821 | 0.714 | Easy | 13,301 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2007025/Python-3-Solution-Brute-Force-and-Two-Pointers-2-Solutions | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# Travelling front to back
result = ["*"] * len(s)
i, j = 0, 0
while i < len(s) and j < len(s):
if s[i] == s[j] == c:
result[i] = 0
i += 1
j += 1
elif s[i] != c and s[j] == c:
result[i] = abs(i-j)
i += 1
elif s[i] != c and s[j] != c:
j += 1
# Travelling back to front
i = j = len(s) - 1
while i >= 0 and j >= 0:
if s[i] == s[j] == c:
result[i] = 0
i -= 1
j -= 1
elif s[i] != c and s[j] == c:
if type(result[i]) == int:
result[i] = min(result[i], abs(i-j))
else:
result[i] = abs(i-j)
i -= 1
elif s[i] != c and s[j] != c:
j -= 1
return result | shortest-distance-to-a-character | Python 3 Solution, Brute Force and Two Pointers - 2 Solutions | AprDev2011 | 1 | 121 | shortest distance to a character | 821 | 0.714 | Easy | 13,302 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1337089/Simple-Python-Solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
temp=[]
result =[]
for char in range(len(s)):
if s[char]==c:
temp.append(char)
for j in range(len(s)):
result.append(min(list(map(lambda x:abs(x-j), temp))))
return result | shortest-distance-to-a-character | Simple Python Solution | sangam92 | 1 | 183 | shortest distance to a character | 821 | 0.714 | Easy | 13,303 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1057046/PythonPython3-Shortest-Distance-to-a-Character | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
final = [float('inf') for x in range(len(s))]
final_final = []
# assigning 10**4 + 1 value as the length of string is less than that and hence
# our answer will be less than that. We can assign float('inf') here also.
nearest_c = 10001
# Here, we are going from left to right and calculating the distance from out target
# character c to other characters
for idx, val in enumerate(s):
if val == c:
nearest_c = 0
final[idx] = 0
elif nearest_c != float('inf'):
nearest_c += 1
final[idx] = min(final[idx], nearest_c)
# assigning 10**4 + 1 value as the length of string is less than that and hence
# our answer will be less than that. We can assign float('inf') here also.
nearest_c = 10001
# Here we are going from right to left so that we can make sure that the distance between
# the target character is lowest from front and back.
for idx in range(len(s))[::-1]:
if s[idx] == c:
nearest_c = 0
elif nearest_c != float('inf'):
nearest_c += 1
# final[idx] = nearest_c
final[idx] = min(final[idx], nearest_c)
# print(final)
return final | shortest-distance-to-a-character | [Python/Python3] Shortest Distance to a Character | newborncoder | 1 | 254 | shortest distance to a character | 821 | 0.714 | Easy | 13,304 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2822803/Python-Concise-Greedy-Solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
# get c index in s
target_indexes = []
for i, char in enumerate(s):
if char == c:
target_indexes.append(i)
result = []
for i, char in enumerate(s):
if char == c:
result.append(0)
else:
# get minimum abs difference
minimum_abs = sys.maxsize
for target_index in target_indexes:
if (diff := abs(i - target_index)) < minimum_abs:
minimum_abs = diff
result.append(minimum_abs)
return result | shortest-distance-to-a-character | Python Concise Greedy Solution | namashin | 0 | 1 | shortest distance to a character | 821 | 0.714 | Easy | 13,305 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2750794/python-simple-solution-using-map | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
res=[]
index=[i for i,j in enumerate(s) if j==c]
print(index)
for i in range(len(s)):
if(i in index):
res.append(0)
else:
res.append(min(map(lambda x:abs(x-i),index)))
return res | shortest-distance-to-a-character | python simple solution using map | Raghunath_Reddy | 0 | 6 | shortest distance to a character | 821 | 0.714 | Easy | 13,306 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2740652/Python-Easy | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
lst = []
for _ in range(len(s)):
lst.append(1000000000)
for i in range(len(s)):
if (s[i] == c):
lst[i] = 0
continue
for j in range(i + 1, len(s)):
if (s[j] == c):
tmp = j - i
lst[i] = min(tmp, lst[i])
break
s1 = s[::-1]
lst[:] = lst[::-1]
for i in range(len(s1)):
if (s1[i] == c):
lst[i] = 0
continue
for j in range(i + 1, len(s1)):
if (s1[j] == c):
tmp = j - i
lst[i] = min(tmp, lst[i])
break
lst[:] = lst[::-1]
return lst | shortest-distance-to-a-character | Python Easy | lucasschnee | 0 | 3 | shortest distance to a character | 821 | 0.714 | Easy | 13,307 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2642435/Python3-One-Liner | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
return [min(abs(i - j) for i, char in enumerate(s) if char == c) for j in range(len(s))] | shortest-distance-to-a-character | [Python3] One-Liner | ivnvalex | 0 | 32 | shortest distance to a character | 821 | 0.714 | Easy | 13,308 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2604735/Python3-or-O(n)-Easy-Solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
arr = []
for i in range(len(s)):
if(s[i] == c):
arr.append(i)
a_index = 0
print(arr)
return_arr = []
for i in range(len(s)):
if(a_index+1 >= len(arr)):
return_arr.append(abs(i-arr[a_index]))
elif(abs(i-arr[a_index]) <= abs(i-arr[a_index+1])):
return_arr.append(abs(i-arr[a_index]))
else:
return_arr.append(abs(i-arr[a_index+1]))
a_index += 1
return return_arr | shortest-distance-to-a-character | Python3 | O(n) Easy Solution | urmil_kalaria | 0 | 32 | shortest distance to a character | 821 | 0.714 | Easy | 13,309 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2560677/python-solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
set_c_indexes = set()
for c_index in range(len(s)):
if s[c_index] == c:
set_c_indexes.add(c_index)
if len(set_c_indexes) == 0:
return []
result = []
helper_li = []
for char in range(len(s)):
for c_index in set_c_indexes:
diff = abs(char - c_index)
helper_li.append(diff)
min_distance = min(helper_li)
helper_li = []
result.append(min_distance)
return result | shortest-distance-to-a-character | python solution | samanehghafouri | 0 | 27 | shortest distance to a character | 821 | 0.714 | Easy | 13,310 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2559873/Python3-Two-pointer-O(n)-runtime-O(1)-space | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
afterc = -1
beforec = -1
i = 0
ans = []
while i < len(s):
print(s)
print(s[:i])
if afterc < i:
beforec = afterc
afterc += 1
print(f"Need adjust: afterc < i: {afterc} < {i}")
while afterc < len(s) and s[afterc] != c:
afterc += 1
print(f"After adjust: {afterc}")
if beforec == -1:
print(f"beforec == -1")
print(f"ans.append({afterc - i})")
ans.append(afterc - i)
elif afterc == len(s):
print(f"afterc == len(s)")
print(f"ans.append({i - beforec})")
ans.append(i - beforec)
else:
print(f"else")
print(f"afterc - i: {afterc - i}, i - beforec: {i - beforec}, ans.append({min(afterc - i, i - beforec)})")
ans.append(min(afterc - i, i - beforec))
i += 1
print()
return ans | shortest-distance-to-a-character | [Python3] Two-pointer, O(n) runtime, O(1) space | DG_stamper | 0 | 22 | shortest distance to a character | 821 | 0.714 | Easy | 13,311 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2422908/Python3-Solution-oror-50-Faster-oror-For-Loops | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
new=[]
for i in range(len(s)):
if s[i]==c:
new.append(i)
final=[]
for i in range(len(s)):
final.append(min([abs(t - i)for t in new]))
return final | shortest-distance-to-a-character | Python3 Solution || 50% Faster || For Loops | shashank_shashi | 0 | 13 | shortest distance to a character | 821 | 0.714 | Easy | 13,312 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2307901/Shortest-Distance-to-a-Character | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
arr = []
for i in range(len(s)):
if s[i] == c:
arr.append(i)
newarr = []
for i in range(len(s)):
minnum = len(s)
for j in range(len(arr)):
if abs(i-arr[j]) < minnum:
minnum = abs(i-arr[j])
newarr.append(minnum)
return newarr | shortest-distance-to-a-character | Shortest Distance to a Character 🤩 | ibrahimbayburtlu5 | 0 | 15 | shortest distance to a character | 821 | 0.714 | Easy | 13,313 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/2299609/Simple-Python3-Solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
each_char_index = []
specific_char_index = []
for index, item in enumerate(s):
each_char_index.append(index)
if item == c:
specific_char_index.append(index)
res = []
for i in each_char_index:
dist = []
for j in specific_char_index:
dist.append(abs(i-j))
res.append(min(dist))
return res | shortest-distance-to-a-character | Simple Python3 Solution | vem5688 | 0 | 56 | shortest distance to a character | 821 | 0.714 | Easy | 13,314 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1986158/Python-Easy-or-Low-Memory-Utilization | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
final = []
temp = [i for i,x in enumerate(s) if x == c]
for x in range(len(s)):
sub_value = abs(temp[0]-x)
for y in temp:
if abs(y-x) < sub_value:
sub_value = abs(y-x)
final.append(sub_value)
return(final) | shortest-distance-to-a-character | Python Easy | Low Memory Utilization | Yodawgz0 | 0 | 71 | shortest distance to a character | 821 | 0.714 | Easy | 13,315 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1962727/Python-One-Pass-No-Extra-Space!-Multiple-Solutions | class Solution:
def shortestToChar(self, s, c):
distance_r = deque()
j = 0
for i in range(len(s)):
while j < len(s) and s[j] != c:
j += 1
if j == len(s): j = inf
distance_r.append(j-i)
if i == j: j += 1
distance_l = deque()
j = len(s)-1
for i in range(len(s)-1,-1,-1):
while j > -1 and s[j] != c:
j -= 1
if j == -1: j = -inf
distance_l.appendleft(i-j)
if i == j: j -= 1
distance = [min(r,l) for r,l in zip(distance_r,distance_l)]
return distance | shortest-distance-to-a-character | Python - One Pass - No Extra Space! Multiple Solutions | domthedeveloper | 0 | 122 | shortest distance to a character | 821 | 0.714 | Easy | 13,316 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1962727/Python-One-Pass-No-Extra-Space!-Multiple-Solutions | class Solution:
def shortestToChar(self, s, c):
distance = list()
j = 0
for i in range(len(s)):
while j < len(s) and s[j] != c:
j += 1
if j == len(s): j = inf
distance.append(j-i)
if i == j: j += 1
j = len(s)-1
for i in range(len(s)-1,-1,-1):
while j > -1 and s[j] != c:
j -= 1
if j == -1: j = -inf
distance[i] = min(distance[i], i-j)
if i == j: j -= 1
return distance | shortest-distance-to-a-character | Python - One Pass - No Extra Space! Multiple Solutions | domthedeveloper | 0 | 122 | shortest distance to a character | 821 | 0.714 | Easy | 13,317 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1962727/Python-One-Pass-No-Extra-Space!-Multiple-Solutions | class Solution:
def shortestToChar(self, s, c):
ans, l, r = list(), -inf, 0
for i in range(len(s)):
if i == r+1: l, r = r, r+1
while r < len(s) and s[r] != c: r = r+1 if r < len(s)-1 else inf
ans.append(min(i-l, r-i))
return ans | shortest-distance-to-a-character | Python - One Pass - No Extra Space! Multiple Solutions | domthedeveloper | 0 | 122 | shortest distance to a character | 821 | 0.714 | Easy | 13,318 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1948084/easy-python-code | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
output = []
for i in range(len(s)):
m,n = None,None
for j in range(i,-1,-1):
if s[j] == c:
m = j
break
for k in range(i,len(s),1):
if s[k] == c:
n = k
break
if m == None:
output.append(abs(i-n))
elif n == None:
output.append(abs(i-m))
else:
if abs(i-m)<abs(i-n):
output.append(abs(i-m))
else:
output.append(abs(i-n))
return output | shortest-distance-to-a-character | easy python code | dakash682 | 0 | 41 | shortest distance to a character | 821 | 0.714 | Easy | 13,319 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1805885/Python-concise-and-explained-solution-oror-easy-to-understand | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
k=[]
ids=[i for i in range(len(s)) if s[i]==c] #making array of indices where c is found
for i in range(len(s)):
d=[] #an empty array that will keep the each distance between every c and i
for id_ in ids:
d.append(abs(i-id_)) #appending distance of i from every c present in the string
k.append(min(d)) #appending minimum distance in the output array
return k | shortest-distance-to-a-character | Python concise and explained solution || easy to understand | _anuraag_ | 0 | 129 | shortest distance to a character | 821 | 0.714 | Easy | 13,320 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1672243/WEEB-EXPLAINS-PYTHON-TWO-POINTERS-SOLUTION-(BEATS-80.74) | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
result = []
low, high = 0, 0
foundFirstC = False
while high < len(s):
if s[high] == c and not foundFirstC: # we found the first c
low = high + 1
result += [i for i in range(high, -1, -1)]
foundFirstC = True
elif s[high] == c and foundFirstC: # we found more than the first c
length = high - low
isEven = False
if length % 2 == 0:
isEven = True
if isEven: #e.g. s="eikkfe" is even in between the e's, including the e's, when c="e"
result += [i for i in range(1,length//2+1)] + [i for i in range(length//2,-1,-1)]
else: #e.g. s="eikkfse" is odd in between the e's, including the e's, when c="e"
result += [i for i in range(1, length//2+1)] + [length//2+1] + [i for i in range(length//2,-1, -1)]
low = high + 1
high += 1
# handling of edge case, we need to add the distance of characters after the last c
count = 1
for i in range(low, high):
result.append(count)
count += 1
return result | shortest-distance-to-a-character | WEEB EXPLAINS PYTHON TWO POINTERS SOLUTION (BEATS 80.74%) | Skywalker5423 | 0 | 112 | shortest distance to a character | 821 | 0.714 | Easy | 13,321 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1584037/Python-3-O(n)-solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
locations = [i for i in range(len(s)) if s[i] == c]
n = len(locations) - 1
cur = 0
res = []
for i, char in enumerate(s):
dist1 = abs(i - locations[cur])
if cur != n:
dist2 = abs(i - locations[cur+1])
if dist1 > dist2:
cur += 1
dist1 = dist2
res.append(dist1)
return res | shortest-distance-to-a-character | Python 3 O(n) solution | dereky4 | 0 | 173 | shortest distance to a character | 821 | 0.714 | Easy | 13,322 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1443473/Python-3-Two-Pointer-98-runtime | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
d = [ i for i in range(len(s)) if s[i]==c]
res = [0]*len(s)
l = 0
r = 0
while l < len(d) and r < len(s):
if s[r] == c:
res[r] = 0
l+=1
else:
if d[l] > r and l == 0:
res[r] = abs(r-d[l])
elif d[l]>r:
res[r] = min(d[l]-r,r-d[l-1])
elif d[l]<r:
res[r] = d[-1]
r+=1
while r < len(s):
res[r] = abs(r - d[-1])
r+=1
return res | shortest-distance-to-a-character | Python 3 Two Pointer 98% runtime | rstudy211 | 0 | 137 | shortest distance to a character | 821 | 0.714 | Easy | 13,323 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1395877/Python3-Memory-Less-Than-99.57 | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
idx, ans = [], []
for i in range(len(s)):
if s[i] == c:
idx.append(i)
q, i, prev = 0, 0, 99999
while i < len(s):
if i > idx[q]:
prev = idx[q]
if q + 1 < len(idx):
q += 1
ans.append(min(abs(i - idx[q]), abs(i - prev)))
i += 1
return ans | shortest-distance-to-a-character | Python3 Memory Less Than 99.57% | Hejita | 0 | 106 | shortest distance to a character | 821 | 0.714 | Easy | 13,324 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1348741/NlogN-binary-search-for-the-closest-positions-after-storing-all-index-of-C | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
pos = []
for i,x in enumerate(s):
if x == c:
pos.append(i)
# print(pos)
res = [len(s) for i in range(len(s))]
for i in range(len(s)): # O(N) # [1, 6 ]
right = bisect_left(pos, i) # O(log N) first occurance of index of C where idx > i
left = right-1
# print(left, right, i)
if left >=0: res[i] = i - pos[left]
if right<len(pos): res[i] = min(res[i], pos[right] - i)
return res | shortest-distance-to-a-character | NlogN binary search for the closest positions after storing all index of C | yozaam | 0 | 33 | shortest distance to a character | 821 | 0.714 | Easy | 13,325 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1323129/python3-%3A-3-line-solution-map-reduce | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
letters = list(enumerate(list(s)))
c_idxes = [idx for idx,ch in letters if ch == c]
# could have also used min(), instead of reduce. but ...
return [reduce(lambda x,y: x if x <= y else y,map(lambda x: abs(x-ch_idx), c_idxes)) for ch_idx,ch in letters] | shortest-distance-to-a-character | python3 : 3 line solution, map-reduce | anupamkumar | 0 | 94 | shortest distance to a character | 821 | 0.714 | Easy | 13,326 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1055793/Python-Solution | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
n = len(s)
left = [n]*(n)
right = [n]*(n)
minl = n
minr = n
i = 0
while i <n:
if s[i] == c:
minl = i
if minl!=n:
left[i] = min(i-minl,left[i])
i += 1
i = n-1
while i>= 0:
if s[i] == c:
minr = i
if minr!=n:
right[i] = min(minr-i,right[i])
i -= 1
ans = []
i= 0
while i<n:
ans.append(min(left[i],right[i]))
i += 1
return ans | shortest-distance-to-a-character | Python Solution | SaSha59 | 0 | 76 | shortest distance to a character | 821 | 0.714 | Easy | 13,327 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1054185/Simple-solution-in-Python3-by-creating-two-right-and-left-arrays-briefly-explained | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
n = len(s)
left = []
last = -10 ** 9
for i in range(n):
if s[i] == c:
left.append(0)
last = i
else:
left.append(i - last)
last = 10 ** 9
right = []
for i in range(n - 1, -1, -1):
if s[i] == c:
right.append(0)
last = i
else:
right.append(last - i)
right = right[::-1]
ans = []
for i in range(n):
ans.append(min(left[i], right[i]))
return ans | shortest-distance-to-a-character | Simple solution in Python3 by creating two right and left arrays, briefly explained | amoghrajesh1999 | 0 | 23 | shortest distance to a character | 821 | 0.714 | Easy | 13,328 |
https://leetcode.com/problems/shortest-distance-to-a-character/discuss/358679/Python3-Solution-beats-98-(easy-to-understand) | class Solution:
def shortestToChar(self, S: str, C: str) -> List[int]:
l=[]
x=[]
for i in range(len(S)):
if(S[i]==C):
l.append(i)
a=l[0]
b=l[len(l)-1]
k=0
for i in range(len(S)):
if(i<a):
x.append(a-i)
elif(i>b):
x.append(i-b)
else:
if(i==l[k]):
x.append(0)
if(k<len(l)-1):
k+=1
continue
else:
x.append(min(i-l[k-1],l[k]-i))
return x | shortest-distance-to-a-character | Python3 Solution beats 98% (easy to understand) | Banra123 | 0 | 82 | shortest distance to a character | 821 | 0.714 | Easy | 13,329 |
https://leetcode.com/problems/card-flipping-game/discuss/530999/Python3-simple-solution-using-a-for()-loop | class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
"""
O(n) time complexity: n is length of fronts
O(n) space complexity
"""
same = {x for i, x in enumerate(fronts) if x == backs[i]}
res = 9999
for i in range(len(fronts)):
if fronts[i] not in same: res = min(res, fronts[i])
if backs[i] not in same: res = min(res, backs[i])
return res % 9999 | card-flipping-game | Python3 simple solution using a for() loop | jb07 | 2 | 254 | card flipping game | 822 | 0.456 | Medium | 13,330 |
https://leetcode.com/problems/card-flipping-game/discuss/934917/Python3-two-passes | class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
same = {ff for ff, bb in zip(fronts, backs) if ff == bb}
return min((x for x in fronts+backs if x not in same), default=0) | card-flipping-game | [Python3] two passes | ye15 | 0 | 134 | card flipping game | 822 | 0.456 | Medium | 13,331 |
https://leetcode.com/problems/card-flipping-game/discuss/388444/Solution-in-Python-3-(beats-~98)-(one-line) | class Solution:
def flipgame(self, f: List[int], b: List[int]) -> int:
return min(set(f+b)-set(f[i] for i in range(len(f)) if f[i] == b[i]), default = 0)
- Junaid Mansuri
(LeetCode ID)@hotmail.com | card-flipping-game | Solution in Python 3 (beats ~98%) (one line) | junaidmansuri | 0 | 174 | card flipping game | 822 | 0.456 | Medium | 13,332 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2402569/Python-oror-Detailed-Explanation-oror-Easily-Understood-oror-DP-oror-O(n-*-sqrt(n)) | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
total_nums = len(arr)
moduler = 1000000007
count_product_dict = {num: 1 for num in arr}
arr.sort()
for i in range(1, total_nums):
for j in range(i):
quotient = arr[i] // arr[j]
if quotient < 2 or math.sqrt(arr[i]) > arr[i- 1]:
break
if arr[i] % arr[j] == 0:
count_product_dict[arr[i]] += count_product_dict[arr[j]] * count_product_dict.get(quotient, 0)
count_product_dict[arr[i]] %= moduler
return sum(count_product_dict.values()) % moduler | binary-trees-with-factors | 🔥 Python || Detailed Explanation ✅ || Easily Understood || DP || O(n * sqrt(n)) | wingskh | 35 | 1,100 | binary trees with factors | 823 | 0.5 | Medium | 13,333 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2400058/Python-dp-with-hash-table | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
ans = 0
dp = {}
for n in arr:
temp = 1
for k in dp.keys():
if n%k==0 and n//k in dp:
temp+=dp[k]*dp[n//k]
ans+= temp
dp[n] = temp
return ans%(10**9+7) | binary-trees-with-factors | Python dp with hash table | li87o | 3 | 152 | binary trees with factors | 823 | 0.5 | Medium | 13,334 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/934727/Python3-two-approaches | class Solution:
def numFactoredBinaryTrees(self, A: List[int]) -> int:
As = set(A) # set for O(1) lookup
pq = [] # min heap
for x, y in product(A, A):
if x*y in As: heappush(pq, (x*y, x, y))
cnt = {x: 1 for x in A}
while pq:
z, x, y = heappop(pq)
cnt[z] += cnt[x] * cnt[y]
return sum(cnt.values()) % 1_000_000_007 | binary-trees-with-factors | [Python3] two approaches | ye15 | 3 | 265 | binary trees with factors | 823 | 0.5 | Medium | 13,335 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/934727/Python3-two-approaches | class Solution:
def numFactoredBinaryTrees(self, A: List[int]) -> int:
cnt = {}
for x in sorted(A):
cnt[x] = 1 + sum(cnt[xx]*cnt[x//xx] for xx in cnt if not x%xx and x//xx in cnt)
return sum(cnt.values()) % 1_000_000_007 | binary-trees-with-factors | [Python3] two approaches | ye15 | 3 | 265 | binary trees with factors | 823 | 0.5 | Medium | 13,336 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/934727/Python3-two-approaches | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
freq = {}
for x in sorted(arr):
freq[x] = 1
for xx in freq:
freq[x] += freq[xx] * freq.get(x/xx, 0)
return sum(freq.values()) % 1_000_000_007 | binary-trees-with-factors | [Python3] two approaches | ye15 | 3 | 265 | binary trees with factors | 823 | 0.5 | Medium | 13,337 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/1107357/PythonGo-by-DP-w-Diagram | class Solution:
def numFactoredBinaryTrees(self, A):
## dictionary
# key: root node value
# value: number of binary tree
dp = defaultdict(int)
# keep A sorted in ascending order
A.sort()
constant, size = (10**9 + 7), len(A)
# scan each possible root node value
for i, cur_num in enumerate(A):
# Case 1: cur_num as root with child nodes
# scan each potential child node value
for j in range(i):
factor = A[j]
quotient, remainder = divmod(cur_num, factor)
# current (factor, quotient) pair are feasible to be child nodes
if remainder == 0:
dp[cur_num] += dp[quotient] * dp[factor]
# Case 2: cur_num as root without child nodes
dp[cur_num] += 1
return sum( dp.values() ) % constant | binary-trees-with-factors | Python/Go by DP [w/ Diagram] | brianchiang_tw | 2 | 268 | binary trees with factors | 823 | 0.5 | Medium | 13,338 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2409005/Python-simple-and-easy-solution-oror-clean-code-or-faster-than-99 | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
mem = {}
for parent in arr:
mem[parent] = 1
for child in arr:
other_child = parent/child
if other_child in mem:
mem[parent] += (mem[other_child] * mem[child]) % 1000000007
return (sum(mem.values()) % 1000000007) | binary-trees-with-factors | Python simple and easy solution || clean code | faster than 99% | wilspi | 1 | 30 | binary trees with factors | 823 | 0.5 | Medium | 13,339 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2409005/Python-simple-and-easy-solution-oror-clean-code-or-faster-than-99 | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
mem = {}
for parent in arr:
mem[parent] = 1
for child in arr:
if child > math.sqrt(parent):
break
other_child = parent / child
if other_child in mem:
mem[parent] += (
(mem[other_child] * mem[child])
* (1 if other_child == child else 2)
) % 1000000007
return sum(mem.values()) % 1000000007 | binary-trees-with-factors | Python simple and easy solution || clean code | faster than 99% | wilspi | 1 | 30 | binary trees with factors | 823 | 0.5 | Medium | 13,340 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2401736/Python-or-Two-Dynamic-programming-solutions | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
N = len(arr)
arr.sort()
arr_set = defaultdict(int)
for i in range(N):
arr_set[arr[i]] = i
dp = [1] * N
for i in range(1, N):
for j in range(i):
left = arr[j]
right = arr[i] / left
if right in arr_set:
l_comb = dp[j]-1
r_comb = dp[arr_set[right]]-1
dp[i] += 1 + l_comb + r_comb + (l_comb * r_comb)
return sum(dp) % 1000000007 | binary-trees-with-factors | Python | Two Dynamic programming solutions | pivovar3al | 1 | 19 | binary trees with factors | 823 | 0.5 | Medium | 13,341 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2401736/Python-or-Two-Dynamic-programming-solutions | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
arr_set = set(arr)
@cache
def dp(val):
r = 1
for i in range(len(arr)):
left = arr[i]
if left >= val:
break
right = val / left
if right in arr_set:
l_comb = dp(left)
r_comb = dp(right)
r += 1
r += l_comb-1
r += r_comb-1
r += (l_comb-1) * (r_comb-1)
return r
answer = 0
for n in arr:
answer += dp(n)
return answer % 1000000007 | binary-trees-with-factors | Python | Two Dynamic programming solutions | pivovar3al | 1 | 19 | binary trees with factors | 823 | 0.5 | Medium | 13,342 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2399932/Python-100-faster-DP-solution-not-short | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
children = {num: [] for num in arr}
trees = {num: 1 for num in arr}
MOD = 10 ** 9 + 7
for i in range(len(arr) - 1):
for j in range(i, len(arr) - 1):
product = arr[i] * arr[j]
if product in children:
children[product].append((arr[i], arr[j]))
elif product > arr[-1]:
break
res = 0
for num in arr:
for pair in children[num]:
trees[num] += (trees[pair[0]] * trees[pair[1]]
if pair[0] == pair[1]
else 2 * (trees[pair[0]] * trees[pair[1]]))
trees[num] %= MOD
res = (res + trees[num]) % MOD
return res | binary-trees-with-factors | [Python] [100% faster] DP solution, not short | celestez | 1 | 119 | binary trees with factors | 823 | 0.5 | Medium | 13,343 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2180513/python-3-or-recursion-%2B-memoization-or-O(n2)O(n) | class Solution:
def numFactoredBinaryTrees(self, nums: List[int]) -> int:
nums = set(nums)
n = len(nums)
@lru_cache(None)
def helper(num):
trees = 1
for factor in nums:
if not num % factor and num // factor in nums:
trees += helper(factor) * helper(num // factor)
return trees
return sum(helper(num) for num in nums) % (10 ** 9 + 7) | binary-trees-with-factors | python 3 | recursion + memoization | O(n^2)/O(n) | dereky4 | 1 | 88 | binary trees with factors | 823 | 0.5 | Medium | 13,344 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/1108180/Python-Iteration%2BLookuporExplanationandCommentsandDiagram | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
#print("sorted input={}".format(arr))
valToCount = {} #maps arr value to number of binary trees we can make having that value as root
MOD = 10**9+7
result = 0
#for each arr[i] we will get the count of all possible binary trees that have arr[i] as root, and then add it to valToCount map
for index,val in enumerate(arr):
valResult = 1 #start off with just [arr[i]], then add more for each binary tree we can make with factors
#find all factors (by checking to the left of val) and multiply the count of each pair of factors to get the combination for this factor pair's orientation
for factorIdx in range(index-1,-1,-1):
factorCandidate = arr[factorIdx]
if val % factorCandidate == 0:
#this is a factor, so get the sum of the combinations for the [thisfactor,completementfactor] orientation
#(i.e. this factor will go first, and later on when we iterate to another arr[factorIdx], we will use the other factor to go first).
factor2 = val // factorCandidate
#print("factorCandidate={},factor2={}".format(factorCandidate,factor2))
#check if factor2 exists in arr
if factor2 in valToCount:
#note that we can do lookups because any value to the left is already computed in the previous iteration of our first for loop
valResult += valToCount[factorCandidate] * valToCount[factor2]
valResult %= MOD
#append val to map so we can reuse without having to recursively compute the result for value again
valToCount[val] = valResult
result += valResult
result %= MOD
return result | binary-trees-with-factors | [Python] Iteration+Lookup|Explanation&Comments&Diagram | Vikktour | 1 | 150 | binary trees with factors | 823 | 0.5 | Medium | 13,345 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/1107684/Python3-Dp-sol-with-comments-for-reference. | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
# sort numbers so that we know that the factors of a number are to left.
arr.sort()
# since all single digit tree's are valid, init dp solution with 1's
T = [1] * len(arr)
# As we calcuate, we need a look up for numbers after division with factors.
v = {}
# Loop around to assume that you need to calcuate all trees with root a specific number.
for numidx in range(len(arr)):
root_of_tree = arr[numidx]
# Check all prev values to see which one's are potential factors
for factor in range(0, numidx):
# if the number is a factor then the divisor needs to also be in the prev numbers.
t = root_of_tree//arr[factor]
if root_of_tree % arr[factor] == 0 and t in v:
# if both factors exist, multiply to get full count of the tree
T[numidx] += v[arr[factor]] * v[t]
# Store the value of the root to for future lookups.
v[root_of_tree] = T[numidx]
# Divide sum by mod to keep the ans in range.
return sum(T) % (10**9+7) | binary-trees-with-factors | [Python3] Dp sol with comments for reference. | vadhri_venkat | 1 | 110 | binary trees with factors | 823 | 0.5 | Medium | 13,346 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/809026/Python-3-or-DFS | class Solution:
def numFactoredBinaryTrees(self, A: List[int]) -> int:
n = len(A)
A.sort()
s = {a:i for i,a in enumerate(A)}
d = collections.defaultdict(set)
for i in range(n):
for j in range(i):
if A[i] % A[j] == 0:
res = A[i] // A[j]
if res in s: d[i].add((j, s[res]))
@lru_cache(maxsize=None)
def dfs(i):
cur = 1
for l, r in d[i]: cur += dfs(l) * dfs(r)
return cur
ans = 0
for i in range(n):
ans += dfs(i)
return ans % 1000000007 | binary-trees-with-factors | Python 3 | DFS | idontknoooo | 1 | 183 | binary trees with factors | 823 | 0.5 | Medium | 13,347 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2836482/bottom-up-DP-python3 | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
mapp = collections.defaultdict(int)
arr = sorted(arr)
for n in arr:
mapp[n] = 1
for i in range(len(arr)):
for j in range(i+1):
if arr[i]*arr[j] in mapp:
mapp[arr[i]*arr[j]] += (mapp[arr[i]]*mapp[arr[j]])*((i!=j)+1)
# print(mapp)
return sum(mapp[n] for n in mapp.keys()) % (10**9 + 7) | binary-trees-with-factors | bottom-up DP - python3 | zahrash | 0 | 1 | binary trees with factors | 823 | 0.5 | Medium | 13,348 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2827282/Python-(Simple-DP) | class Solution:
def numFactoredBinaryTrees(self, arr):
arr.sort()
dict1 = {i:1 for i in arr}
for i in range(1,len(arr)):
for j in range(i):
if arr[i]%arr[j] == 0 and arr[i]//arr[j] in dict1:
dict1[arr[i]] += dict1[arr[j]]*dict1[arr[i]//arr[j]]
return sum(dict1.values())%(10**9+7) | binary-trees-with-factors | Python (Simple DP) | rnotappl | 0 | 2 | binary trees with factors | 823 | 0.5 | Medium | 13,349 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2408591/Very-simple-Python3-solution-beats-92.53-other-submissions | class Solution:
def numFactoredBinaryTrees(self, nums: List[int]) -> int:
nums = set(nums)
n = len(nums)
@lru_cache(None)
def helper(num):
trees = 1
for factor in nums:
if not num % factor and num // factor in nums:
trees += helper(factor) * helper(num // factor)
return trees
return sum(helper(num) for num in nums) % (10 ** 9 + 7) | binary-trees-with-factors | ✔️ Very simple Python3 solution beats 92.53% other submissions | UpperNoot | 0 | 4 | binary trees with factors | 823 | 0.5 | Medium | 13,350 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2403809/Python-Accurate-Solution-using-HashMap-oror-Documented | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
MOD = 10 ** 9 + 7
arr.sort()
# store number of factored BTs rooted at given key
dict = {}
for i in range(len(arr)): # i points to root of Factored BT
dict[arr[i]] = 1 # arr[i] is itself BT, set 1 for it (1 way)
for j in range(i): # j points to first factor
if arr[i] % arr[j] == 0: # does arr[j] can be a factor of root arr[i]?
fact2 = arr[i] // arr[j] # calculate another one fact-2
if fact2 in dict: # does fact-2 present the dict
dict[arr[i]] += dict[arr[j]]*dict[fact2] # multiply number of ways recorded for both factors; add to dict for key arr[i]
dict[arr[i]] %= MOD
# add the values and return the result
return sum(dict.values()) % MOD | binary-trees-with-factors | [Python] Accurate Solution using HashMap || Documented | Buntynara | 0 | 6 | binary trees with factors | 823 | 0.5 | Medium | 13,351 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2403004/Python3-Solution-with-using-dp | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
val2idx = {}
for i in range(len(arr)):
val2idx[arr[i]] = i
dp = [1] * len(arr)
mod = 10 ** 9 + 7
for i in range(len(arr)):
for j in range(i):
val = arr[i] / arr[j]
if val in val2idx:
dp[i] += (dp[j] * dp[val2idx[val]]) % mod
return sum(dp) % mod | binary-trees-with-factors | [Python3] Solution with using dp | maosipov11 | 0 | 5 | binary trees with factors | 823 | 0.5 | Medium | 13,352 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2401827/Python-Hashmap%3A-O(N*N) | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
n = len(arr)
m = 10**9 + 7
# All the value can be a root without leaf, therefore
# the initial value of ans is as same as array size
ans = n
# We have to contruct the root with smaller value in arr.
# The number of small value node will be used by contructing
# the bigger value root
arr.sort()
# The bag is recording the number of methods can
# contruct the specific root.
# The initial count is one, root without any leaf
bag = collections.defaultdict(int)
for num in arr:
bag[num] = 1
for l in range(n):
# Target root: how many methods can contruct the target value
target = arr[l]
for i in range(0, l):
# left node value
left = arr[i]
if target % left == 0:
# Try to get the right node value
right = target // left
else:
continue
# if right node value is find in bag,
# we can contruct the binary tree with factors
if right in bag:
tmp = bag[left] * bag[right]
ans += tmp % m
bag[target] += tmp % m
return ans % m | binary-trees-with-factors | Python Hashmap: O(N*N) | TerryHung | 0 | 10 | binary trees with factors | 823 | 0.5 | Medium | 13,353 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2400910/Python3-Memoization-approach | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
@cache
def num_subtree(root: int) -> int:
ret = 1
for num in arr:
if num >= root:
break
modulo = root % num
if modulo > 0:
continue
quotient = root // num
if quotient in arr_set:
ret += num_subtree(num) * num_subtree(quotient)
return ret
arr.sort()
arr_set = set(arr)
ret = 0
for num in arr:
ret += num_subtree(num)
ret %= 1000_000_007
return ret | binary-trees-with-factors | [Python3] Memoization approach | geka32 | 0 | 23 | binary trees with factors | 823 | 0.5 | Medium | 13,354 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2400745/GolangPython-O(n2)-time-or-O(n)-space | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
modulo = 10 ** 9 + 7
arr.sort()
dp = [1 for _ in range(len(arr))]
index = {value: i for i, value in enumerate(arr)}
for i, value in enumerate(arr):
for j in range(i):
left = arr[j]
if value % left == 0:
right = value // arr[j]
if right in index:
dp[i] += dp[j] * dp[index[right]]
dp[i] %= modulo
return sum(dp) % modulo | binary-trees-with-factors | Golang/Python O(n^2) time | O(n) space | vtalantsev | 0 | 9 | binary trees with factors | 823 | 0.5 | Medium | 13,355 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2400031/Binary-Trees-With-Factors | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
children = {num: [] for num in arr}
trees = {num: 1 for num in arr}
MOD = 10 ** 9 + 7
for i in range(len(arr) - 1):
for j in range(i, len(arr) - 1):
product = arr[i] * arr[j]
if product in children:
children[product].append((arr[i], arr[j]))
elif product > arr[-1]:
break
res = 0
for num in arr:
for pair in children[num]:
trees[num] += (trees[pair[0]] * trees[pair[1]]
if pair[0] == pair[1]
else 2 * (trees[pair[0]] * trees[pair[1]]))
trees[num] %= MOD
res = (res + trees[num]) % MOD
return res | binary-trees-with-factors | Binary Trees With Factors | klu_2100031497 | 0 | 13 | binary trees with factors | 823 | 0.5 | Medium | 13,356 |
https://leetcode.com/problems/binary-trees-with-factors/discuss/2399969/Python3-DP-%2B-Hash-Solution-TC-O(n2) | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
arr.sort()
memo={}
memo[arr[0]] = 1
for i in range(1, len(arr)):
count = 1
for j in range(0, i):
if arr[i]/arr[j] in memo:
count+=memo[arr[j]]*memo[arr[i]/arr[j]]
memo[arr[i]] = count
return sum(memo.values()) % (10**9+7) | binary-trees-with-factors | Python3 DP + Hash Solution TC O(n^2) | EnergyBoy | 0 | 17 | binary trees with factors | 823 | 0.5 | Medium | 13,357 |
https://leetcode.com/problems/goat-latin/discuss/1877272/Python-3-Simple-Solution-w-Explanation | class Solution:
def toGoatLatin(self, sentence: str) -> str:
new = sentence.split() # Breaks up the input into individual sentences
count = 1 # Starting at 1 since we only have one "a" to begin with.
for x in range(len(new)):
if new[x][0].casefold() in 'aeiou': # Checks if the first value of x is a vowel. The casefold, can be replaced with lower, lowers the case. Can also just be removed and have "in 'aeiouAEIOU'
new[x] = new[x] + 'ma' + 'a'*count # Brings it together with the count multiplying number of "a"'s as needed.
count += 1
elif new[x].casefold() not in 'aeiou': # Same comment as above.
new[x] = new[x][1:] + new[x][0] + 'ma' + 'a'*count # Just moves the first value to the end then does the a.
count += 1
return " ".join(x for x in new) # Converts the list back into a string. | goat-latin | [Python 3] - Simple Solution w Explanation | IvanTsukei | 4 | 110 | goat latin | 824 | 0.678 | Easy | 13,358 |
https://leetcode.com/problems/goat-latin/discuss/947781/Simple-Python-Solution | class Solution:
def toGoatLatin(self, S: str) -> str:
out=''
l=S.split()
for i in range(len(l)):
if l[i][0] in 'aeiouAEIOU':
out+=l[i]+'m'+'a'*(i+2)+' '
else:
out+=l[i][1:]+l[i][0]+'m'+'a'*(i+2)+' '
return out[:-1] | goat-latin | Simple Python Solution | lokeshsenthilkumar | 2 | 143 | goat latin | 824 | 0.678 | Easy | 13,359 |
https://leetcode.com/problems/goat-latin/discuss/353398/Solution-in-Python-3-(beats-~100)-(one-line) | class Solution:
def toGoatLatin(self, S: str) -> str:
return " ".join([(s if s[0].lower() in 'aeiou' else s[1:]+s[0])+'maa'+'a'*i for i,s in enumerate(S.split())])
- Junaid Mansuri
(LeetCode ID)@hotmail.com | goat-latin | Solution in Python 3 (beats ~100%) (one line) | junaidmansuri | 2 | 187 | goat latin | 824 | 0.678 | Easy | 13,360 |
https://leetcode.com/problems/goat-latin/discuss/2742745/Python-Easy | class Solution:
def toGoatLatin(self, sentence: str) -> str:
lst = sentence.split(" ")
lst2 = []
vowels = ["a", "e", "i", "o", "u"]
for i, word in enumerate(lst):
tmp = word
if (word[0].lower() in vowels):
tmp = tmp + "ma"
else:
tmp2 = tmp[1:] + tmp[0] + "ma"
tmp = tmp2
tmp = tmp + ("a" * (i + 1))
lst2.append(tmp)
sentence_latin = " ".join(lst2)
return sentence_latin | goat-latin | Python Easy | lucasschnee | 1 | 34 | goat latin | 824 | 0.678 | Easy | 13,361 |
https://leetcode.com/problems/goat-latin/discuss/2028834/Simple-python-solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vwl_lst = ['a','e','i','o','u','A','E','I','O','U']
sentence = sentence.split()
for i in range(len(sentence)):
if sentence[i][0] in vwl_lst:
sentence[i] = sentence[i]+"ma"+ ("a"*(i+1))
else:
a = sentence[i][0]
sentence[i] = sentence[i][1:]
sentence[i] = sentence[i]+a
sentence[i] = sentence[i]+"ma"+("a"*(i+1))
return ' '.join(sentence) | goat-latin | Simple python solution | __Dhruv__ | 1 | 40 | goat latin | 824 | 0.678 | Easy | 13,362 |
https://leetcode.com/problems/goat-latin/discuss/1829931/python3-simple-solution-or-86-fatser-or-Easy-to-understand | class Solution:
def toGoatLatin(self, sentence: str) -> str:
sentence = sentence.split()
for i in range(len(sentence)):
if sentence[i][0].lower() in ["a","e","i","o","u"]:
sentence[i] = sentence[i]+"ma"+"a"*(i+1)
else:
sentence[i] = sentence[i][1:]+sentence[i][0]+"ma"+"a"*(i+1)
return " ".join(sentence) | goat-latin | ✔python3 simple solution | 86% fatser | Easy to understand | Coding_Tan3 | 1 | 48 | goat latin | 824 | 0.678 | Easy | 13,363 |
https://leetcode.com/problems/goat-latin/discuss/2823387/Simple-Python-solution-beats-90 | class Solution:
def toGoatLatin(self, sentence: str) -> str:
sentence = sentence.split(" ")
vowels = "aeiou"
result = []
for i,word in enumerate(sentence):
if word[0].lower() in vowels:
word += "ma"
else:
word += word[0] + "ma"
word = word[1:]
word += (i+1)*"a"
result.append(word)
return " ".join(result) | goat-latin | Simple Python solution beats 90% | aruj900 | 0 | 2 | goat latin | 824 | 0.678 | Easy | 13,364 |
https://leetcode.com/problems/goat-latin/discuss/2794432/Python3 | class Solution:
def toGoatLatin(self, sentence: str) -> str:
words = sentence.split(' ')
def goatify(word,idx):
vowels = ['a', 'e', 'i', 'o', 'u']
if word[0].lower() in vowels:
return word+'ma'+'a'*idx
else:
return word[1:]+word[0]+'ma'+'a'*idx
words = [goatify(w,i+1) for i,w in enumerate(words)]
return ' '.join(words) | goat-latin | Python3 | jsheng | 0 | 3 | goat latin | 824 | 0.678 | Easy | 13,365 |
https://leetcode.com/problems/goat-latin/discuss/2673733/Python-1-long-long-line-%3A) | class Solution:
def toGoatLatin(self, sentence: str) -> str:
return " ".join([((c if c[0].lower() in {"a", "e", "i", "o", "u"} else (c[1:] + c[0])) + "ma" + "a"*(i + 1)) for i, c in enumerate(sentence.split(" "))]) | goat-latin | Python - 1 long long line :) | phantran197 | 0 | 2 | goat latin | 824 | 0.678 | Easy | 13,366 |
https://leetcode.com/problems/goat-latin/discuss/2672402/32ms-or-13.8Mb-or-Python | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels = ['a','e','i','o','u' , 'A' , 'E' , 'I','O','U']
words = sentence.split()
# print(words)
word = [list(i) for i in words]
# print(word)
c = 0
for i in word:
c += 1
# print(i)
if i[0] not in vowels:
i.append(i.pop(0))
i.append('m')
i.append('a')
else:
i.append('m')
i.append('a')
for j in range(c):
# print(c)
i.append("a")
a =["".join(i) for i in word]
ans = " ".join(a)
return ans | goat-latin | 32ms | 13.8Mb | Python | hk_davy | 0 | 2 | goat latin | 824 | 0.678 | Easy | 13,367 |
https://leetcode.com/problems/goat-latin/discuss/2666574/Python-easy-solution-faster-then-95 | class Solution:
def toGoatLatin(self, sentence: str) -> str:
words = sentence.split()
result = ''
i = 0
for word in words:
i += 1
t = 'a'*i
if word[0] in 'aeiouAEIOU':
result += f" {word}ma{t}"
else:
temp = word[0]
result += f" {word[1:]}{temp}ma{t}"
return result.lstrip() | goat-latin | Python easy solution faster then 95% | vivek4045 | 0 | 2 | goat latin | 824 | 0.678 | Easy | 13,368 |
https://leetcode.com/problems/goat-latin/discuss/2563263/python-solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
unli = 'aeuioAEUIO'
s = ''
for index, word in enumerate(sentence.split(), 1):
s += (word if word[0] in unli else word[1:] + word[:1]) + 'ma' + index * 'a'
s += ' '
return s[:-1] | goat-latin | python solution | shohruh223 | 0 | 14 | goat latin | 824 | 0.678 | Easy | 13,369 |
https://leetcode.com/problems/goat-latin/discuss/2218381/Beginner-Friendly-Solution-oror-46ms-oror-Python | class Solution:
def toGoatLatin(self, sentence: str) -> str:
word_list = sentence.split()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
new_sentence = ''
end_str = 'a'
for word in word_list:
if word[0] in vowels:
new_sentence += word + 'ma' + end_str + ' '
else:
new_sentence += word[1:] + word[0] + 'ma' + end_str + ' '
end_str += 'a'
return new_sentence[:len(new_sentence) - 1] | goat-latin | Beginner Friendly Solution || 46ms || Python | cool-huip | 0 | 29 | goat latin | 824 | 0.678 | Easy | 13,370 |
https://leetcode.com/problems/goat-latin/discuss/2088686/Python-or-Very-simple-python-solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1}
arr = sentence.split(' ')
for i in range(len(arr)):
if arr[i][0] not in vowels:
arr[i] = arr[i][1:] + arr[i][0]
arr[i] += 'ma'
arr[i] += 'a'*(i+1)
return " ".join(arr) | goat-latin | Python | Very simple python solution | shreeruparel | 0 | 31 | goat latin | 824 | 0.678 | Easy | 13,371 |
https://leetcode.com/problems/goat-latin/discuss/2031409/Python-solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
ans = []
for ind, i in enumerate(sentence.split()):
if i[0].lower() in ('a', 'e', 'i', 'o', 'u'):
ans.append(i + 'ma' + 'a'*(ind+1))
else:
ans.append(i[1:]+i[0]+'ma' +'a'*(ind+1))
return ' '.join(ans) | goat-latin | Python solution | StikS32 | 0 | 27 | goat latin | 824 | 0.678 | Easy | 13,372 |
https://leetcode.com/problems/goat-latin/discuss/1980867/Easiest-and-Simplest-Python3-Solution-or-Easy-to-Read-and-Understand-or-100-Faster | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels=['a', 'e', 'i', 'o','u','A','E','I','O','U']
x=sentence.split(" ")
ct=0
temp=[]
for i in x:
ct+=1
if i[0] in vowels:
ss=i+'ma'+ct*'a'
temp.append(ss)
elif i[0] not in vowels:
ss=i[1:]+i[0]+'ma'+ct*'a'
temp.append(ss)
return (" ".join(temp)) | goat-latin | Easiest & Simplest Python3 Solution | Easy to Read & Understand | 100% Faster | RatnaPriya | 0 | 38 | goat latin | 824 | 0.678 | Easy | 13,373 |
https://leetcode.com/problems/goat-latin/discuss/1965973/Python-easy-to-read-and-understand | class Solution:
def __init__(self):
self.vow = ["a", "A", "e", "E", "i", "I", "o", "O", "u", "U"]
def toGoatLatin(self, sentence: str) -> str:
words = sentence.split(" ")
for i, word in enumerate(words):
suffix = "ma" + "a"*(i+1)
if word[0] in self.vow:
words[i] = word+suffix
else:
words[i] = word[1:] + word[0] + suffix
return " ".join(words) | goat-latin | Python easy to read and understand | sanial2001 | 0 | 19 | goat latin | 824 | 0.678 | Easy | 13,374 |
https://leetcode.com/problems/goat-latin/discuss/1936943/Python-Clean-and-Simple! | class Solution:
def toGoatLatin(self, sentence):
self.aCount = 1
return " ".join(map(self.getWord, sentence.split()))
def getWord(self, word):
self.aCount += 1
if self.isVowel(word[0]): return word + "m" + ("a" * self.aCount)
else: return word[1:] + word[0] + "m" + ("a" * self.aCount)
def isVowel(self, letter):
return letter.lower() in ["a","e","i","o","u"] | goat-latin | Python - Clean and Simple! | domthedeveloper | 0 | 49 | goat latin | 824 | 0.678 | Easy | 13,375 |
https://leetcode.com/problems/goat-latin/discuss/1891718/Python-easy-solution-for-beginners | class Solution:
def toGoatLatin(self, sentence: str) -> str:
res = ""
pos = 1
for i in sentence.split():
if i[0] in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:
res += (i + "ma" + "a" * pos) + " "
pos += 1
else:
res += (i[1:] + i[0] + "ma" + "a" * pos) + " "
pos += 1
return res.strip() | goat-latin | Python easy solution for beginners | alishak1999 | 0 | 19 | goat latin | 824 | 0.678 | Easy | 13,376 |
https://leetcode.com/problems/goat-latin/discuss/1856962/Goat-Latin-Easy-Solution | class Solution:
def toGoatLatin(self, s: str) -> str:
s = s.split()
vowel = ['a', 'e', 'i', 'o', 'u']
for i in range(len(s)):
if s[i][0].lower() not in vowel:
s[i] = s[i][1:] + s[i][0]
s[i] += 'ma' + ('a' * (i + 1))
return ' '.join(s) | goat-latin | Goat Latin - Easy Solution | jenil_095 | 0 | 22 | goat latin | 824 | 0.678 | Easy | 13,377 |
https://leetcode.com/problems/goat-latin/discuss/1720252/python3-Solution | class Solution:
def postfix(self, index) -> str:
return "ma" + "a" * (index + 1)
def reformat(self, word, index) -> str:
vowels = ["a", "e", "i", "o", "u"]
if word[0].lower() in vowels:
return word + self.postfix(index)
else:
return word[1:] + word[0] + self.postfix(index)
def toGoatLatin(self, sentence: str) -> str:
return " ".join([self.reformat(v, i) for i, v in enumerate(sentence.split())]) | goat-latin | python3 Solution | khalidhassan3011 | 0 | 36 | goat latin | 824 | 0.678 | Easy | 13,378 |
https://leetcode.com/problems/goat-latin/discuss/1702626/easy-solution-using-enumerate | class Solution:
def toGoatLatin(self, sentence: str) -> str:
res=[]
for i, v in enumerate(sentence.split()):
if v[0].lower() in ('aeiou'):
res.append(v+'ma'+ (i+1)*'a')
else:
res.append(v[1:]+v[0]+'ma'+ (i+1)*'a')
return ' '.join(res) | goat-latin | easy solution using enumerate | sc618445 | 0 | 17 | goat latin | 824 | 0.678 | Easy | 13,379 |
https://leetcode.com/problems/goat-latin/discuss/1634005/Python3-99.18-Faster | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels = ["a", "e", "i", "o", "u"]
s = sentence.split(" ")
new = []
i = 1
for word in s:
if word[0].lower() in vowels:
newword = word + "ma"
else:
newword = word[1:] + word[0] + "ma"
newword += "a" * i
i += 1
new.append(newword)
new = " ".join(new)
return new
``` | goat-latin | [Python3] 99.18% Faster | Ghadeer_Elsalhawy | 0 | 56 | goat latin | 824 | 0.678 | Easy | 13,380 |
https://leetcode.com/problems/goat-latin/discuss/1611779/Python-3-very-easy-solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U'}
words = sentence.split()
for i in range(len(words)):
if words[i][0] not in vowels:
words[i] = words[i][1:] + words[i][0]
words[i] += 'ma' + ('a' * (i + 1))
return ' '.join(words) | goat-latin | Python 3 very easy solution | dereky4 | 0 | 98 | goat latin | 824 | 0.678 | Easy | 13,381 |
https://leetcode.com/problems/goat-latin/discuss/1553359/Python-Easy-Solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowels = "aeiouAEIOU"
sentence = sentence.split(" ")
l = []
for i , word in enumerate(sentence,1):
if word[0] in vowels:
word += "ma"
else:
word = word[1:] + word[0] + "ma"
word += i* "a"
l.append(word)
return " ".join(l) | goat-latin | [Python] Easy Solution | gl_9 | 0 | 31 | goat latin | 824 | 0.678 | Easy | 13,382 |
https://leetcode.com/problems/goat-latin/discuss/1337639/Python3-dollarolution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
s = sentence.split(' ')
v = ['a','e','i','o','u','A','E','I','O','U']
j = 2
for i in range(len(s)):
if s[i][0] not in v:
s[i] += s[i][0]
s[i] = s[i][1:]
s[i] += 'm' + j*'a'
j += 1
return ' '.join(s) | goat-latin | Python3 $olution | AakRay | 0 | 66 | goat latin | 824 | 0.678 | Easy | 13,383 |
https://leetcode.com/problems/goat-latin/discuss/1277482/Python-easy-to-understand-solution | class Solution:
def toGoatLatin(self, sentence: str) -> str:
vovels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
sent = sentence.split(" ")
for i in range(len(sent)):
li = list(sent[i])
# print(li)
if li[0] in vovels:
sent[i] = sent[i] + 'ma' + (i+1)*'a'
else:
firstLetter = li.pop(0)
newWord = ''.join(li) + firstLetter + 'ma' + (i+1)*'a'
sent[i] = newWord
return ' '.join(sent) | goat-latin | Python easy to understand solution | satyu | 0 | 70 | goat latin | 824 | 0.678 | Easy | 13,384 |
https://leetcode.com/problems/goat-latin/discuss/1276896/Easy-Python-Solution(98.85) | class Solution:
def toGoatLatin(self, sentence: str) -> str:
s=sentence.split(" ")
g=""
t=['a','e','i','o','u']
for i,v in enumerate(s):
# print(v[0])
if(v[0].lower() in t):
g+=v+'ma'
elif(v[0].lower() not in t):
g+=v[1:]+v[0]+'ma'
if(i<len(s)-1):
g+='a'*(i+1)+' '
else:
g+='a'*(i+1)
return "".join(g) | goat-latin | Easy Python Solution(98.85%) | Sneh17029 | 0 | 89 | goat latin | 824 | 0.678 | Easy | 13,385 |
https://leetcode.com/problems/goat-latin/discuss/1176063/PythonPython3-solution-with-explanation | class Solution:
def toGoatLatin(self, S: str) -> str:
lis = [] #Empty list to store the modified String
cnt = 1 #To add extra 'a' based on the count
for i in S.split(): #traverse the list
if i[0].lower() in 'aeiou': #If i[0] is a vowel
lis.append(i+'ma'+'a'*cnt) # then simple add ma and 'a' * cnt
else: #else take the first letter of the string and add it to the last and add 'ma' and 'a' * cnt
lis.append(i[1:]+i[0]+'ma'+'a'*cnt)
cnt += 1 #increment the count by one
#print(lis)
return ' '.join(lis) | goat-latin | Python/Python3 solution with explanation | prasanthksp1009 | 0 | 47 | goat latin | 824 | 0.678 | Easy | 13,386 |
https://leetcode.com/problems/goat-latin/discuss/1176063/PythonPython3-solution-with-explanation | class Solution:
def toGoatLatin(self, S: str) -> str:
S = S.split()
cnt = 1
for i in range(len(S)):
if S[i][0].lower() in 'a' or S[i][0].lower() == 'e' or S[i][0].lower() == 'i' or S[i][0].lower() == 'o' or S[i][0].lower() == 'u':
S[i] = S[i] +'ma'+'a'*cnt
else:
S[i] = S[i][1:]+S[i][0]+'ma'+'a'*cnt
cnt += 1
return ' '.join(S) | goat-latin | Python/Python3 solution with explanation | prasanthksp1009 | 0 | 47 | goat latin | 824 | 0.678 | Easy | 13,387 |
https://leetcode.com/problems/goat-latin/discuss/1128449/Solution-in-Python-or-Faster-than-95 | class Solution:
def toGoatLatin(self, S: str) -> str:
l = S.split()
for i in range(len(l)):
if l[i][0] in ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']:
l[i] = l[i]+'ma'+('a'*(i+1))
else:
l[i] = l[i][1:]+l[i][0]+'ma'+('a'*(i+1))
return ' '.join(l) | goat-latin | Solution in Python | Faster than 95% | Annushams | 0 | 133 | goat latin | 824 | 0.678 | Easy | 13,388 |
https://leetcode.com/problems/goat-latin/discuss/1127711/Python-simple-solution | class Solution:
def toGoatLatin(self, S: str) -> str:
words = S.split(' ')
result = []
for i,word in enumerate(words):
if word[0].lower() in 'aeiou':
result.append(word+'ma'+'a'*(i+1))
elif word[0].lower() not in 'aeiou':
result.append(word[1:]+word[0]+'ma'+ 'a'*(i+1))
return ' '.join(x for x in result) | goat-latin | [Python] simple solution | svalak | 0 | 48 | goat latin | 824 | 0.678 | Easy | 13,389 |
https://leetcode.com/problems/goat-latin/discuss/1112852/Python-fast-clear-pythonic | class Solution:
def toGoatLatin(self, S: str) -> str:
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
S = S.split()
for index, value in enumerate(S):
if value[0] in vowels:
S[index] = value + 'm' + 'a' * (index + 2)
else:
S[index] = value[1:] + value[:1] + 'm' + 'a' * (index + 2)
return ' '.join(S) | goat-latin | Python, fast, clear, pythonic | cruim | 0 | 57 | goat latin | 824 | 0.678 | Easy | 13,390 |
https://leetcode.com/problems/goat-latin/discuss/1106324/Python-Simple-Solution-98-faster-20ms | class Solution:
def toGoatLatin(self, S: str) -> str:
ns = ""
i = 1
for ele in S.split():
if ele[0] in "aeiouAEIOU":
ns += ele + "ma"
else:
ns += "".join(ele for ele in list(ele)[1:])+ele[0]+"ma"
ns += 'a'*i + " "
i += 1
return ns.strip() | goat-latin | Python Simple Solution 98% faster 20ms | abhisek_ | 0 | 89 | goat latin | 824 | 0.678 | Easy | 13,391 |
https://leetcode.com/problems/goat-latin/discuss/1084678/Python3-simple-2-line-solution-faster-than-85 | class Solution:
def toGoatLatin(self, S: str) -> str:
vowels, words = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}, S.split(" ")
return " ".join([word+"ma"+"a"*(i+1) if word[0] in vowels else word[1:]+word[0]+"ma"+"a"*(i+1) for i, word in enumerate(words)]) | goat-latin | Python3 simple 2 line solution faster than 85% | amol1729 | 0 | 67 | goat latin | 824 | 0.678 | Easy | 13,392 |
https://leetcode.com/problems/goat-latin/discuss/1060119/Python3-simple-solution | class Solution:
def toGoatLatin(self, S: str) -> str:
vowel = ['a','e', 'i', 'o', 'u']
words = S.split(' ')
for i,j in enumerate(words):
a = j.lower()
if a[0] not in vowel:
words[i] = j[1:] + j[0]
words[i] += 'ma' + 'a'*(i+1)
return ' '.join(words) | goat-latin | Python3 simple solution | EklavyaJoshi | 0 | 61 | goat latin | 824 | 0.678 | Easy | 13,393 |
https://leetcode.com/problems/goat-latin/discuss/800164/Simple-Python-Solution | class Solution:
def toGoatLatin(self, s: str) -> str:
l=[]
S=list(s.split())
for i in range(len(S)):
if S[i][0].lower() in 'aeiou':
y=S[i]+'ma'
x='a'*(i+1)
k=y+x
l.append(k)
else:
y=S[i][0]
k=S[i][1:]
z=k+y+'ma'
x='a'*(i+1)
m=z+x
l.append(m)
return ' '.join(l) | goat-latin | Simple Python Solution | Ayu-99 | 0 | 22 | goat latin | 824 | 0.678 | Easy | 13,394 |
https://leetcode.com/problems/goat-latin/discuss/574400/Simple-Python-Solution | class Solution:
def toGoatLatin(self, S: str) -> str:
l=[]
# s=""
l1=list(S.split())
for i in range(len(l1)):
m=""
s=l1[i]
if s[0]=='a' or s[0]=='e' or s[0]=='i' or s[0]=='o' or s[0]=='u' or s[0]=='A' or s[0]=='E' or s[0]=='I' or s[0]=='O' or s[0]=='U':
m+=s
m+="ma"
else:
k=""
x=s[0]
k=s[1:]
m+=k
m+=x
m+="ma"
d=""
for j in range(i+1):
d+='a'
m+=d
l.append(m)
return ' '.join(l) | goat-latin | Simple Python Solution | Ayu-99 | 0 | 32 | goat latin | 824 | 0.678 | Easy | 13,395 |
https://leetcode.com/problems/goat-latin/discuss/537218/Two-Pythonic-sol-sharing.-90%2B-w-Explanation | class Solution:
def toGoatLatin(self, S: str) -> str:
vowel = set("aeiouAEIOU")
return ' '.join( t +'ma'+'a'*idx if t[0] in vowel else t[1:] + t[0] + 'ma'+'a'*idx for idx, t in enumerate( S.split(), 1 ) ) | goat-latin | Two Pythonic sol sharing. 90%+ [w/ Explanation] | brianchiang_tw | 0 | 49 | goat latin | 824 | 0.678 | Easy | 13,396 |
https://leetcode.com/problems/goat-latin/discuss/537218/Two-Pythonic-sol-sharing.-90%2B-w-Explanation | class Solution:
def toGoatLatin(self, S: str) -> str:
vowel = set("aeiouAEIOU")
return ' '.join([ t +'ma'+'a'*idx if t[0] in vowel else t[1:] + t[0] + 'ma'+'a'*idx for idx, t in enumerate( S.split(), 1 ) ]) | goat-latin | Two Pythonic sol sharing. 90%+ [w/ Explanation] | brianchiang_tw | 0 | 49 | goat latin | 824 | 0.678 | Easy | 13,397 |
https://leetcode.com/problems/goat-latin/discuss/440656/easy-to-understand-efficient-solution | class Solution:
def toGoatLatin(self, S: str) -> str:
vowel = 'aeiouAEIOU'
conso = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
lst = S.split()
new = []
count_num = 1
for word in lst:
if word[0] in vowel:
new.append(word[:] + 'ma' + 'a'*count_num)
count_num += 1
elif word[0] in conso:
new.append(word[1:] + word[0] + 'ma' + 'a'*count_num)
count_num += 1
return ' '.join(new) | goat-latin | easy to understand efficient solution | manish007143 | 0 | 40 | goat latin | 824 | 0.678 | Easy | 13,398 |
https://leetcode.com/problems/goat-latin/discuss/365998/Python3-split-then-join-comprehension-simple-solution | class Solution:
def toGoatLatin(self, S: str) -> str:
return " ".join( self.goatify(i, word) for i, word in enumerate(S.split(" ")) )
def goatify(self, idx: int, word: str) -> str:
maa = "maa" + "a" * idx
prefix = word if word[0] in "aeiouAEIOU" else word[1:] + word[0]
return prefix + maa | goat-latin | Python3 split then join comprehension simple solution | llanowarelves | 0 | 61 | goat latin | 824 | 0.678 | Easy | 13,399 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.