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/check-whether-two-strings-are-almost-equivalent/discuss/2385068/Ugly-but-fast-hashmap | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
d1={}
for i in word1:
if i in d1:
d1[i]+=1
else:
d1[i]=1
d2={}
for i in word2:
if i in d2:
d2[i]+=1
else:
d2[i]=1
for i in d1:
c=0
if i in d2:
c= abs(d1[i]-d2[i])
else:
c=d1[i]
if c>3:
return False
for i in d2:
c=0
if i in d1:
c= abs(d1[i]-d2[i])
else:
c=d2[i]
if c>3:
return False
return True | check-whether-two-strings-are-almost-equivalent | Ugly but fast -hashmap | sunakshi132 | 0 | 44 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,600 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2343204/32ms-Linear-Python-List-Dict-Set-comprehension-Explained-(Easy-to-follow) | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
self.res = True
dict1 = {}
dict2 = {}
def verify( word1: list, word2: list) -> dict:
for c in word1:
if c in dict1:
dict1[c] += 1
elif c not in dict1:
dict1[c] = 1
for c in word2:
if c in dict2:
dict2[c] += 1
elif c not in dict2:
dict2[c] = 1
set_same = set(word1).intersection(set(word2))
set_diff = set(word1).symmetric_difference(set(word2))
for c in set_diff:
if c in dict1 and dict1[c] > 3:
self.res = False
return
elif c in dict2 and dict2[c] > 3:
self.res = False
return
for c in set_same:
if abs(dict1[c] - dict2[c]) > 3:
self.res = False
return
verify(list(word1), list(word2))
return self.res | check-whether-two-strings-are-almost-equivalent | 32ms Linear Python List Dict Set comprehension Explained (Easy to follow) | chingling7 | 0 | 52 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,601 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/2036182/Python-Clean-and-Simple! | class Solution:
def checkAlmostEquivalent(self, word1, word2):
counter1 = [0] * 26
counter2 = [0] * 26
for c in word1: counter1[ord(c)-ord("a")] += 1
for c in word2: counter2[ord(c)-ord("a")] += 1
diffs = [v1-v2 if v1 >= v2 else v2-v1 for v1,v2 in zip(counter1,counter2)]
return all(d <= 3 for d in diffs) | check-whether-two-strings-are-almost-equivalent | Python - Clean and Simple! | domthedeveloper | 0 | 81 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,602 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1914849/Python-dollarolution-(95-Faster) | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
words = set(word1 + word2)
for i in words:
if abs(word1.count(i) - word2.count(i)) > 3:
return False
return True | check-whether-two-strings-are-almost-equivalent | Python $olution (95% Faster) | AakRay | 0 | 66 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,603 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1795985/3-Lines-Python-Solution-oror-80-Faster-(34ms)-oror-Memory-less-than-90 | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
for w in set(word1+word2):
if abs(word1.count(w) - word2.count(w)) > 3: return False
return True | check-whether-two-strings-are-almost-equivalent | 3-Lines Python Solution || 80% Faster (34ms) || Memory less than 90% | Taha-C | 0 | 127 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,604 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1697822/Python3-accepted-solution | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
alpha = [chr(i) for i in range(97,123)] # all letters
keyval1 = dict()
keyval2 = dict()
for i in range(len(alpha)):
if(alpha[i] not in word1):
keyval1[alpha[i]] = 0
else:
keyval1[alpha[i]] = word1.count(alpha[i])
if(alpha[i] not in word2):
keyval2[alpha[i]] = 0
else:
keyval2[alpha[i]] = word2.count(alpha[i])
#print(keyval2)
for i in range(len(keyval1)):
if(abs(int(keyval1[list(keyval1.keys())[i]]) - int(keyval2[list(keyval2.keys())[i]])) >3):
return False
return True | check-whether-two-strings-are-almost-equivalent | Python3 accepted solution | sreeleetcode19 | 0 | 64 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,605 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1643440/Python-Easy-Solution-with-Explanation-or-Beats-92-in-time-and-space | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
d1={}#For storing the frequency of Word1 chracters
d2={}#For storing the frequency of Word2 chracters
for i in word1:
if i in d1:
d1[i]+=1
else:
d1[i]=1
for i in word2:
if i in d2:
d2[i]+=1
else:
d2[i]=1
#Now iterate through the word1 and word2, and check the frequencies difference in chars
for i in word1+word2:
#If char in both word1 and word2
if i in d1 and i in d2:
if abs(d1[i]-d2[i])>3:
return False
#If char in either of word1 or word2
elif (i in d1 and d1[i]>3) or (i in d2 and d2[i]>3):
return False
return True
#Space->O(n+n)->O(2n)->O(n)
#Time->O(n+n+n)->O(3n)->O(n) | check-whether-two-strings-are-almost-equivalent | Python Easy Solution with Explanation | Beats 92% in time and space | deleted_user | 0 | 60 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,606 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1639298/Python-straightforward-solution-using-hashmap | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
cnt1 = defaultdict(int)
cnt2 = defaultdict(int)
for w in word1:
cnt1[w] += 1
for w in word2:
cnt2[w] += 1
for k in cnt1:
v = cnt1[k]
if abs(v-cnt2[k]) > 3:
return False
for k in cnt2:
v = cnt2[k]
if abs(v-cnt1[k]) > 3:
return False
return True | check-whether-two-strings-are-almost-equivalent | Python straightforward solution using hashmap | byuns9334 | 0 | 66 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,607 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1594052/Python-3-Easy-to-understand-simple | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
for i in word1:
if(abs(word1.count(i)-word2.count(i))>3):
return False
for i in word2:
if(abs(word2.count(i)-word1.count(i))>3):
return False
return True | check-whether-two-strings-are-almost-equivalent | Python 3 Easy to understand simple | Deepika_P15 | 0 | 55 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,608 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1578815/Python-or-Counter-%2B-Subtract-or-3-lines-or-O(m-%2B-n)-Time-O(1)-Space | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
counts = Counter(word1)
counts.subtract(Counter(word2))
return all(abs(counts[x]) <= 3 for x in ascii_lowercase) | check-whether-two-strings-are-almost-equivalent | Python | Counter + Subtract | 3 lines | O(m + n) Time O(1) Space | leeteatsleep | 0 | 49 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,609 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1576214/Python-straightforward-counters | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
w1, w2 = Counter(word1), Counter(word2)
return all(abs(w1.get(c, 0) - w2.get(c, 0)) <= 3 for c in w1.keys() | w2.keys()) | check-whether-two-strings-are-almost-equivalent | Python, straightforward counters | blue_sky5 | 0 | 120 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,610 |
https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1575923/Python-hashmap-solution | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
f1 = Counter(word1)
f2 = Counter(word2)
for ch in string.ascii_lowercase:
if abs(f1[ch]-f2[ch]) > 3:
return False
return True | check-whether-two-strings-are-almost-equivalent | Python hashmap solution | abkc1221 | 0 | 136 | check whether two strings are almost equivalent | 2,068 | 0.646 | Easy | 28,611 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1596922/Well-Explained-oror-99-faster-oror-Mainly-for-Beginners | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
items.sort()
dic = dict()
res = []
gmax = 0
for p,b in items:
gmax = max(b,gmax)
dic[p] = gmax
keys = sorted(dic.keys())
for q in queries:
ind = bisect.bisect_left(keys,q)
if ind<len(keys) and keys[ind]==q:
res.append(dic[q])
elif ind==0:
res.append(0)
else:
res.append(dic[keys[ind-1]])
return res | most-beautiful-item-for-each-query | ππ Well-Explained || 99% faster || Mainly for Beginners π | abhi9Rai | 4 | 124 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,612 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1576585/Python3-greedy | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
items.sort()
ans = [0]*len(queries)
prefix = ii = 0
for x, i in sorted((x, i) for i, x in enumerate(queries)):
while ii < len(items) and items[ii][0] <= x:
prefix = max(prefix, items[ii][1])
ii += 1
ans[i] = prefix
return ans | most-beautiful-item-for-each-query | [Python3] greedy | ye15 | 3 | 53 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,613 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1580782/Dictionary-of-max-beauties-99.55-speed | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
max_beauty = defaultdict(int)
for price, beauty in items:
max_beauty[price] = max(beauty, max_beauty[price])
prices = sorted(max_beauty.keys())
for p1, p2 in zip(prices, prices[1:]):
max_beauty[p2] = max(max_beauty[p2], max_beauty[p1])
return [max_beauty[prices[idx - 1]]
if (idx := bisect_right(prices, q)) > 0 else 0
for q in queries] | most-beautiful-item-for-each-query | Dictionary of max beauties, 99.55% speed | EvgenySH | 1 | 87 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,614 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/2840443/Python3-greater-Let-me-know-if-it-can-be-improved-further | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
items.sort(key = lambda x: (x[0]))
base = [i for i in range(len(queries))]
partialRes = {}
i = beauty = 0
for query, b in sorted(zip(queries, base), key = lambda x: x[0]):
while i < len(items) and items[i][0] <= query:
beauty = max(beauty, items[i][1])
i += 1
partialRes[b] = beauty
return [beauty for b, beauty in sorted(partialRes.items(), key = lambda x:x[0])] | most-beautiful-item-for-each-query | Python3 -> Let me know if it can be improved further | mediocre-coder | 0 | 1 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,615 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/2721416/Intuitive-Solution-or-Beginner-Friendly | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
def binarySearch(l, i, j, target):
while i < j:
mid = (i+j)>>1
if l[mid][0] <= target:
i = mid + 1
else:
j = mid
return l[i][1] if target >= l[i][0] else l[i-1][1]
items.sort(key = lambda x : x[0])
i, n = 0, len(items)
currmax = items[0][1]
mincost = items[0][0]
for i in range(n):
currmax = max(currmax, items[i][1])
items[i][1] = currmax
ans = []
for q in queries:
if q < mincost:
ans.append(0)
continue
else:
ans.append(binarySearch(items, 0, n -1 , q))
return ans | most-beautiful-item-for-each-query | Intuitive Solution | Beginner-Friendly | tejtharun625 | 0 | 2 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,616 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/2601502/Python3-or-Solved-Using-Sorting-%2B-Binary-Search | class Solution:
#Let n = len(items) and m = len(queries)!
#Time-Complexity: O(nlog(n) + n + m*log(n)) -> O((n+m) * logn)
#Space-Complexity: O(1)
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
#First of all, I need to sort the list of items by the increasing price!
items.sort(key = lambda x: x[0])
#initialize empty ans array!
ans = []
#iterate through each and every item and update the beauty of item to reflect
#the maximum beauty seen so far! This is so that answering the query becomes
#more convenient!
bestBeauty = float(-inf)
for i in range(len(items)):
bestBeauty = max(bestBeauty, items[i][1])
items[i][1] = bestBeauty
#now, for each query, we can perform binary search to get the maximum beauty
#of item out of all items whose price is less or equal to the queried price!
for query in queries:
#initialize search space!
L, R = 0, len(items) - 1
#as long as binary search has at least one element to consider,
#continue iterations of binary search!
maxBeauty = 0
while L <= R:
mid = (L + R) // 2
mid_item = items[mid]
if(mid_item[0] <= query):
maxBeauty = max(maxBeauty, mid_item[1])
L = mid + 1
continue
else:
R = mid - 1
continue
#check if we don't have answer to current query!
if(L == 0):
ans.append(0)
continue
ans.append(maxBeauty)
return ans | most-beautiful-item-for-each-query | Python3 | Solved Using Sorting + Binary Search | JOON1234 | 0 | 9 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,617 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/2092410/Python3-SImple-Solution | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
N, M = len(items), len(queries)
qpairs = [(queries[i], i) for i in range(M)]
ans = [0]*M
items.sort()
qpairs.sort()
j = last = 0
for budget, i in qpairs:
ans[i] = last
while j < N and items[j][0] <= budget:
ans[i] = max(items[j][1], ans[i])
j += 1
last = ans[i]
return ans | most-beautiful-item-for-each-query | Python3 SImple Solution | Lazinous | 0 | 43 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,618 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1660178/python3-solutions | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
item1, total = sorted(items, key = lambda x:x[0]), len(items) #sort by price
offset, curr_max = 0,0 #curr_max initialised with 0, which is insistence with the case that no available beauty
queries1 = sorted(queries) # as initially, queries does not promise the order
ans = {} #reason is same with above
for i in queries1:
while offset < total:
if item1[offset][0] <= i:
curr_max = max(curr_max, item1[offset][1]) #record a curr_max
offset += 1
else:break
ans[i] = curr_max
result = []
for i in queries:
result.append(ans[i])
return result | most-beautiful-item-for-each-query | python3 solutions | 752937603 | 0 | 57 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,619 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1660178/python3-solutions | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
item1, total = sorted(items, key = lambda x:(x[0], x[1])), len(items) #search by prices and beauty
offset, curr_max = 0,0
queries1 = sorted(queries)
ans = {}
for i in queries1:
if item1[offset][0] > i:
ans[i] = curr_max
continue
#the code below works actually same with before, but I use binary search to get all the available nodes
low, high = offset, total - 1
mid = (low + high) // 2
while high - low > 1:
if item1[mid][0] > i:
high = mid
else: low = mid
mid = (low + high) // 2
offset1 = high if item1[high][0] <= i else low
#then iterate among the previous and new offset
for itr in range(offset, offset1 + 1):
curr_max = max(item1[itr][1], curr_max)
offset = offset1
ans[i] = curr_max
result = []
for i in queries:
result.append(ans[i])
return result | most-beautiful-item-for-each-query | python3 solutions | 752937603 | 0 | 57 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,620 |
https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1576362/Python-Easy-Solution-Binary-Search-Tree-or-O(NlogN)-%2B-O(QlogN) | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
class Node:
def __init__(self, key, maximum):
self.key = key
self.maximum = maximum
self.left = None
self.right = None
head = Node(items[0][0], items[0][1])
for i in range(1, len(items)):
node = head
new_node = Node(items[i][0], items[i][1])
while True:
if new_node.key > node.key:
new_node.maximum = max(new_node.maximum, node.maximum)
if node.right:
node = node.right
else:
node.right = new_node
break
elif new_node.key < node.key:
node.maximum = max(new_node.maximum, node.maximum)
if node.left:
node = node.left
else:
node.left = new_node
break
else:
node.maximum = max(new_node.maximum, node.maximum)
break
answer = []
for query in queries:
node = head
maximum = 0
while node:
if query > node.key:
maximum = max(maximum, node.maximum)
node = node.right
elif query < node.key:
node = node.left
else:
maximum = max(maximum, node.maximum)
break
answer.append(maximum)
return answer | most-beautiful-item-for-each-query | Python Easy Solution - Binary Search Tree | O(NlogN) + O(QlogN) | dilwalacoder | 0 | 44 | most beautiful item for each query | 2,070 | 0.498 | Medium | 28,621 |
https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/discuss/1588356/python-binary-search-%2B-greedy-with-deque-O(nlogn) | class Solution:
def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:
# workers sorted in reverse order, tasks sorted in normal order
def can_assign(n):
task_i = 0
task_temp = deque()
n_pills = pills
for i in range(n-1,-1,-1):
while task_i < n and tasks[task_i] <= workers[i]+strength:
task_temp.append(tasks[task_i])
task_i += 1
if len(task_temp) == 0:
return False
if workers[i] >= task_temp[0]:
task_temp.popleft()
elif n_pills > 0:
task_temp.pop()
n_pills -= 1
else:
return False
return True
tasks.sort()
workers.sort(reverse = True)
l = 0
r = min(len(tasks), len(workers))
res = -1
while l <= r:
m = (l+r)//2
if can_assign(m):
res = m
l = m+1
else:
r = m-1
return res | maximum-number-of-tasks-you-can-assign | [python] binary search + greedy with deque O(nlogn) | hkwu6013 | 9 | 403 | maximum number of tasks you can assign | 2,071 | 0.346 | Hard | 28,622 |
https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/discuss/1576586/Python3-binary-search | class Solution:
def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:
tasks.sort()
workers.sort()
def fn(k, p=pills):
"""Return True if k tasks can be completed."""
ww = workers[-k:]
for t in reversed(tasks[:k]):
if t <= ww[-1]: ww.pop()
elif t <= ww[-1] + strength and p:
p -= 1
i = bisect_left(ww, t - strength)
ww.pop(i)
else: return False
return True
lo, hi = 0, min(len(tasks), len(workers))
while lo < hi:
mid = lo + hi + 1 >> 1
if fn(mid): lo = mid
else: hi = mid - 1
return lo | maximum-number-of-tasks-you-can-assign | [Python3] binary search | ye15 | 9 | 523 | maximum number of tasks you can assign | 2,071 | 0.346 | Hard | 28,623 |
https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/discuss/2389960/faster-than-100.00-or-pythonor-easiest-or-solution | class Solution:
def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:
from sortedcontainers import SortedList
tasks.sort()
workers.sort()
def check_valid(ans):
# _tasks = SortedList(tasks[:ans])
_tasks = deque(tasks[:ans])
_workers = workers[-ans:]
remain_pills = pills
for worker in _workers:
task = _tasks[0]
if worker >= task:
# the worker can finish the min task without pill, just move on
# _tasks.pop(0)
_tasks.popleft()
elif worker + strength >= task and remain_pills:
# the worker cannot finish the min task without pill, but can solve it with pill
# remove the max task that the strengthened worker can finish instead
# remove_task_idx = _tasks.bisect_right(worker + strength)
remove_task_idx = bisect.bisect_right(_tasks, worker + strength)
# _tasks.pop(remove_task_idx - 1)
del _tasks[remove_task_idx - 1]
remain_pills -= 1
else:
return False
return True
lo, hi = 0, min(len(workers), len(tasks))
while lo < hi:
mid = (lo + hi + 1) // 2
if check_valid(mid):
lo = mid
else:
hi = mid - 1
return lo | maximum-number-of-tasks-you-can-assign | faster than 100.00% | python| easiest | solution | vimla_kushwaha | 2 | 107 | maximum number of tasks you can assign | 2,071 | 0.346 | Hard | 28,624 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1577018/Python-or-BruteForce-and-O(N) | class Solution:
def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:
secs = 0
i = 0
while tickets[k] != 0:
if tickets[i] != 0: # if it is zero that means we dont have to count it anymore
tickets[i] -= 1 # decrease the value by 1 everytime
secs += 1 # increase secs by 1
i = (i + 1) % len(tickets) # since after getting to the end of the array we have to return to the first value so we use the mod operator
return secs | time-needed-to-buy-tickets | [Python] | BruteForce and O(N) | GigaMoksh | 30 | 1,600 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,625 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1577018/Python-or-BruteForce-and-O(N) | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
return sum(min(x, tickets[k] if i <= k else tickets[k] - 1) for i, x in enumerate(tickets)) | time-needed-to-buy-tickets | [Python] | BruteForce and O(N) | GigaMoksh | 30 | 1,600 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,626 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1778911/Python-O(N)-easy-method | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
#Loop through all elements in list only once.
nums = tickets
time_sec = 0
# save the number of tickets to be bought by person standing at k position
least_tickets = nums[k]
#(3) Any person nums[i] having tickets more than the k pos person, will buy tickets least_tickets times only.
#(2) Person nums[i] having tickets less than kth person ( nums[i] < least_tickets ), and standing before him(i<k), will be able to buy nums[i] amount.
#(1) Person nums[i] standing after kth person having more tickets than kth person, will be able to buy one less than the ticket kth person can buy(condition: least_tickets - 1).
for i in range(len(nums)):
if k < i and nums[i] >= least_tickets : #(1)
time_sec += (least_tickets - 1)
elif nums[i] < least_tickets : #(2)
time_sec += nums[i]
else: #(3)
time_sec += least_tickets
return time_sec
Please upvote if you find it useful and well-explained! | time-needed-to-buy-tickets | Python O(N) easy method | Smita2195 | 9 | 611 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,627 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2084750/Python-Simple-readable-easy-to-understand-solution-(beats-69) | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
num_seconds = 0
while tickets[k] > 0:
for i in range(len(tickets)):
if tickets[i] > 0 and tickets[k] > 0:
tickets[i] -= 1
num_seconds += 1
return num_seconds | time-needed-to-buy-tickets | [Python] Simple, readable, easy to understand solution (beats 69%) | FedMartinez | 2 | 131 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,628 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1604802/Python-One-Pass-O(1)-Solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
x=tickets[k]
answer=0
for i in range(0,k+1):
answer+=min(x,tickets[i])
for i in range(k+1,len(tickets)):
answer+=min(x-1,tickets[i])
return answer | time-needed-to-buy-tickets | Python One Pass O(1) Solution | Harry_VIT | 2 | 179 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,629 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1576949/Python3-1-line | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
return sum(min(tickets[k]-int(i>k), x) for i, x in enumerate(tickets)) | time-needed-to-buy-tickets | [Python3] 1-line | ye15 | 2 | 109 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,630 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1576949/Python3-1-line | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ans = behind = 0
for i, x in enumerate(tickets):
if i > k: behind = 1
if x < tickets[k] - behind: ans += x
else: ans += tickets[k] - behind
return ans | time-needed-to-buy-tickets | [Python3] 1-line | ye15 | 2 | 109 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,631 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2319753/O(n)-Python-treat-lesskth-and-kth-differently | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
c=0
l=len(tickets)
for i in range(l):
if i <= k:
c+= min(tickets[k],tickets[i])
else:
c+= min(tickets[k]-1,tickets[i])
return c | time-needed-to-buy-tickets | O(n) Python - treat <=kth and kth differently | sunakshi132 | 1 | 63 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,632 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2296280/Python-Easy-Solution | class Solution(object):
def timeRequiredToBuy(self, tickets, k):
"""
:type tickets: List[int]
:type k: int
:rtype: int
"""
seconds = 0
while tickets[k]!=0:
for i in range(len(tickets)):
if tickets[i]!=0 and tickets[k]!=0:
tickets[i] = tickets[i]-1
seconds +=1
return seconds | time-needed-to-buy-tickets | Python Easy Solution | Abhi_009 | 1 | 85 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,633 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1857998/Python-simple-solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
seconds = 0
while True:
for i in range(len(tickets)):
if tickets[i] != 0:
seconds += 1
tickets[i] -= 1
else:
continue
if tickets[k] == 0:
return seconds | time-needed-to-buy-tickets | Python simple solution | alishak1999 | 1 | 82 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,634 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1632040/Easy-one-pass-O(n) | class Solution(object):
def timeRequiredToBuy(self, tickets, k):
"""
:type tickets: List[int]
:type k: int
:rtype: int
"""
tot, idx = 0, len(tickets)-1
while(idx>=0):
tot += min(tickets[k], tickets[idx]) if idx<=k else min(tickets[k]-1, tickets[idx])
idx-=1
return tot | time-needed-to-buy-tickets | Easy - one pass - O(n) | azhw1983 | 1 | 106 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,635 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1580231/Python-O(n)-faster-than-99 | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
x = tickets[k]
res = 0
for i in range(k + 1):
res += min(x, tickets[i])
for i in range(k + 1, len(tickets)):
res += min(x - 1, tickets[i])
return res | time-needed-to-buy-tickets | Python O(n) faster than 99% | dereky4 | 1 | 62 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,636 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1579383/Python-one-pass-solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
n = len(tickets)
res = tickets[k] #it has to buy all at kth position
for i in range(n):
if i < k:
res += min(tickets[i], tickets[k]) # for all pos before k it will exhaust all tickets or get till number till kth place
elif i > k:
res += min(tickets[i], tickets[k]-1) #for all pos after k it can exhaust all tickets or get 1 less than the kth gets finished
return res | time-needed-to-buy-tickets | Python one pass solution | abkc1221 | 1 | 86 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,637 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2846255/Python3-easy-to-understand | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
result = 0
while tickets[k] > 0:
result += len([k1 for k1 in tickets if k1 > 0]) if tickets[k] > 1 else len([i for i in list(enumerate(tickets)) if i[0] <=k and i[1] > 0])
tickets = [k1 - 1 if k1 > 0 else k1 for k1 in tickets]
return result | time-needed-to-buy-tickets | Python3 easy to understand | DNST | 0 | 1 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,638 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2838407/Python3-Two-approaches-with-thought-process. | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
# Time Complexity: O(N), Memory Complexity: O(1)
# N: number of person
# Imagine the time that person k just finished buying all the necessary tickets.
total = 0
V = tickets[k]
for i, v in enumerate(tickets): # i = person id, v = ticket to buy by that person.
if i < k:
total += min(v, V)
elif i > k:
total += min(v, V-1)
else:
total += V
return total | time-needed-to-buy-tickets | Python3 Two approaches with thought process. | Asayu123 | 0 | 1 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,639 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2809324/python-brute-force | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ticket = tickets[k]
result = 0
for i in range(len(tickets)):
if tickets[i] <= ticket and tickets[i] > 0 :
result += tickets[i]
if tickets[i] > ticket and tickets[i] > 0:
result += ticket
if i>k and tickets[i] >= ticket:
result -= 1
return result | time-needed-to-buy-tickets | python brute force | BhavyaBusireddy | 0 | 3 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,640 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2695873/Python-one-pass-O(n) | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
res = 0
i = 0
while tickets[k] > 0 :
if tickets[i%len(tickets)] > 0 :
tickets[i%len(tickets)] -= 1
res += 1
i += 1
return res | time-needed-to-buy-tickets | Python one pass O(n) | mohamedWalid | 0 | 10 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,641 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2644686/python-easy-solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
t=0
while tickets[k] != 0:
for i in range(len(tickets)):
if tickets[i] !=0 and tickets[k] !=0:
tickets[i] -= 1
t+=1
return t | time-needed-to-buy-tickets | python easy solution | anshsharma17 | 0 | 15 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,642 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2302595/Python3-Two-solutions-Using-Deque-and-One-pass | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
# Using queue
q = collections.deque([(i, ticket) for i, ticket in enumerate(tickets)])
timeTaken = 0
while True:
index, ticket = q.popleft()
timeTaken += 1
ticket -= 1
if index == k and ticket == 0:
return timeTaken
if ticket > 0:
q.append((index, ticket))
# One pass
timeTaken = 0
for i, ticket in enumerate(tickets):
if i <= k:
timeTaken += min(ticket, tickets[k])
else:
timeTaken += min(tickets[k] - 1, ticket)
return timeTaken | time-needed-to-buy-tickets | [Python3] Two solutions - Using Deque and One pass | Gp05 | 0 | 45 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,643 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/2003013/Python-Clean-and-Simple! | class Solution:
def timeRequiredToBuy(self, tickets, k):
t = 0
while True:
for i in range(len(tickets)):
if tickets[i] > 0:
tickets[i] -= 1
t += 1
if tickets[k] == 0:
return t | time-needed-to-buy-tickets | Python - Clean and Simple! | domthedeveloper | 0 | 75 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,644 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1974632/Python-single-pass-solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
total = 0
for i, t in enumerate(tickets):
if i < k and tickets[i] > 0:
total += min(tickets[i], tickets[k])
if i > k and tickets[i] > 0:
total += min(tickets[i], tickets[k] - 1)
if i == k:
total += tickets[k]
return total | time-needed-to-buy-tickets | Python single pass solution | user6397p | 0 | 45 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,645 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1927027/python3 | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
time = 0
for i, x in enumerate(tickets):
if i <= k:
time += min(tickets[i], tickets[k])
else:
time += min(tickets[i], tickets[k] - 1)
return time | time-needed-to-buy-tickets | python3 | Mr_Watermelon | 0 | 31 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,646 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1759792/Easy-Python-Solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ans = 0
for i in range(len(tickets)):
if tickets[i] < tickets[k]:
ans += tickets[i]
else:
if i <= k:
ans += tickets[k]
else:
ans += tickets[k]-1
return ans | time-needed-to-buy-tickets | Easy Python Solution | MengyingLin | 0 | 58 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,647 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1724335/easy-understanding | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
h = {}
for i in range(len(tickets)) :
h[i] = tickets[i]
count = 0
while(h[k] != 0):
for i in h:
if(h[i]>0):
h[i] = h[i] - 1
count = count + 1
if(h[k] == 0):
return count
return count | time-needed-to-buy-tickets | easy understanding | jagdishpawar8105 | 0 | 41 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,648 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1707521/Python3-O(n)-One-Pass-Memory-Less-Than-99.13-With-Easy-Explanation | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
s = 0
for i in range(0, len(tickets)):
if i < k:
if tickets[i] > tickets[k]: s += tickets[k]
else: s += tickets[i]
elif i == k: s += tickets[k]
else:
if tickets[i] < tickets[k]: s += tickets[i]
else : s += tickets[k] - 1
return s | time-needed-to-buy-tickets | Python3 O(n) One Pass Memory Less Than 99.13% With Easy Explanation | Hejita | 0 | 121 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,649 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1625123/Easy-python3-solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
i=0
res=0
while tickets[k]!=0:
if tickets[i]!=0:
tickets[i]=tickets[i]-1
res+=1
i=(i+1)%len(tickets)
return res | time-needed-to-buy-tickets | Easy python3 solution | Karna61814 | 0 | 58 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,650 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1606255/Python3-Simple-Brute-Force-Solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ans = 0
while tickets[k]:
for i in range(len(tickets)):
if tickets[i]:
tickets[i] -= 1
ans += 1
if not tickets[k]:
break
return ans | time-needed-to-buy-tickets | [Python3] Simple Brute Force Solution | terrencetang | 0 | 66 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,651 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1589491/Well-Explained-oror-One-pass-oror-Easiest-Approach | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
res = 0
target = tickets[k]
for i,t in enumerate(tickets):
res+=min(t,target-(i>k))
return res
# Execute this Example once
# [8,9,2,4,7,7,8,1]
# 3 | time-needed-to-buy-tickets | ππ Well-Explained || One-pass || Easiest Approach π | abhi9Rai | 0 | 67 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,652 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1577142/Python | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
result = 0
for idx, t in enumerate(tickets):
if idx <= k:
result += min(t, tickets[k])
else:
result += min(t, tickets[k] - 1)
return result | time-needed-to-buy-tickets | Python | blue_sky5 | 0 | 74 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,653 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1646814/O(n)-python | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
ans, n = 0, len(tickets)
count = dict(zip(range(n), tickets))
while count[k]:
for i in range(n):
if count[i]:
count[i] -= 1
ans += 1
if not count[k]:
break
return ans | time-needed-to-buy-tickets | O(n), python | emwalker | -1 | 87 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,654 |
https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1642294/Python-O(n)-simple-solution | class Solution:
def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:
total = sum(tickets)
n = len(tickets)
idx = 0
days = 0
while total > 0:
idx = idx % n
if tickets[idx] > 0:
tickets[idx] -= 1
days += 1
total -= 1
if idx == k and tickets[idx] == 0:
return days
idx += 1
return days | time-needed-to-buy-tickets | Python O(n) simple solution | byuns9334 | -1 | 105 | time needed to buy tickets | 2,073 | 0.62 | Easy | 28,655 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1577058/Python3-using-stack | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
n, node = 0, head
while node: n, node = n+1, node.next
k, node = 0, head
while n:
k += 1
size = min(k, n)
stack = []
if not size & 1:
temp = node
for _ in range(size):
stack.append(temp.val)
temp = temp.next
for _ in range(size):
if stack: node.val = stack.pop()
node = node.next
n -= size
return head | reverse-nodes-in-even-length-groups | [Python3] using stack | ye15 | 11 | 445 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,656 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/2519575/Python-Simple-or-Neat-Solution-or-O(n)-Time-O(1)-Space | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
start_joint = head
group_size = 1
while start_joint and start_joint.next:
group_size += 1
start = end = start_joint.next
group_num = 1
while end and end.next and group_num < group_size:
end = end.next
group_num += 1
end_joint = end.next
if group_num % 2 != 0:
start_joint = end
continue
start_joint.next = self.reverse(start, end, end_joint)
start_joint = start
return head
def reverse(self, start, end, end_joint):
prev, curr = end_joint, start
while curr and curr != end_joint:
next_node = curr.next
curr.next = prev
prev, curr = curr, next_node
return prev | reverse-nodes-in-even-length-groups | Python Simple | Neat Solution | O(n) Time, O(1) Space | Nytex | 4 | 245 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,657 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1652176/Python-O(1)-space | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
groupCount = 0
ptr1 = None
ptr2 = head
while ptr2:
count = 0
ptr3 = ptr2
ptr4 = None
while ptr3 and count<groupCount+1:
ptr4 = ptr3
ptr3 = ptr3.next
count += 1
if count%2:
ptr1 = ptr4
else:
ptr1.next = self.reverse(ptr2, ptr3)
ptr1 = ptr2
ptr2 = ptr3
groupCount += 1
return head
def reverse(self, curr, until):
prev = until
next = curr.next
while next!=until:
curr.next = prev
prev = curr
curr = next
next = next.next
curr.next = prev
return curr | reverse-nodes-in-even-length-groups | Python O(1) space | chinmaysalvi207 | 1 | 114 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,658 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/2846274/O(n)-Converting-into-an-array-and-build-back-in-Python3 | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
arr, curr = [], head
while curr:
arr.append(curr.val)
curr = curr.next
i, counter = 0, 1
arr2 = []
while i < len(arr):
if len(arr[i:i + counter]) % 2 == 0:
arr2 += arr[i:i + counter][::-1]
else:
arr2 += arr[i:i + counter]
i += counter
counter += 1
if i >= len(arr):
break
curr = head
for item in arr2:
curr.val = item
curr = curr.next
return head | reverse-nodes-in-even-length-groups | O(n) Converting into an array and build back in Python3 | DNST | 0 | 1 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,659 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1731615/Python3-simple-solution | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return
l = []
temp = head
i = 1
while temp:
z = []
for j in range(i):
if temp:
z.append(temp.val)
temp = temp.next
if len(z) % 2 == 0:
z = z[::-1]
l.append((z))
i += 1
head = ListNode(l[0][0])
temp = head
i = 1
while i < len(l):
for j in range(len(l[i])):
p = ListNode(l[i][j])
temp.next = p
temp = temp.next
i += 1
return head | reverse-nodes-in-even-length-groups | Python3 simple solution | EklavyaJoshi | 0 | 78 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,660 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1577982/Python-Easy-Solution | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
num_node = 0
dummy = head
while dummy:
dummy = dummy.next
num_node += 1
def get_group(i):
'''
1: 0-1
2: 1-3
3: 3-6
[start, end)
'''
prev = i*(i-1)//2
curr = (1+i)*i//2
return prev, curr
def reverse(head, start, end):
prev, curr, nxt = None, head, None
i = start
while curr and i < end:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
i += 1
return prev, curr
dummy = ListNode(-1, head)
prev = dummy
curr = head
group = 1
while curr:
need_reverse = group % 2 == 0
start, end = get_group(group)
if end > num_node:
left = num_node - start
if left % 2 == 0:
need_reverse = True
else:
need_reverse = False
if need_reverse:
_head, nxt = reverse(curr, start, end)
prev.next = _head
curr.next = nxt
prev = curr
curr = nxt
else:
i = start
while curr and i < end:
prev = curr
curr = curr.next
i += 1
group += 1
return dummy.next | reverse-nodes-in-even-length-groups | [Python] Easy Solution | nightybear | 0 | 70 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,661 |
https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1611501/dfs-Easy-to-understand-solution | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.helper(head, 1)
def helper(self, head, size, lvl = 0):
# check if we should reverse
count, node = 0, head
for _ in range(size):
if not node:
break
count += 1
node = node.next
if count == 0:
return head
#print(lvl * 2 * ' ', count, size)
if count % 2 == 1:
# do not reverse
node = head
for _ in range(count - 1):
node = node.next
node.next = self.helper(node.next, size + 1, lvl + 1)
return head
else:
# perform reverse
prev, curr = None, head
for _ in range(count):
tmp = curr.next # prepare
curr.next = prev # link
prev = curr # move
curr = tmp # move
head.next = self.helper(curr, size + 1, lvl + 1)
return prev | reverse-nodes-in-even-length-groups | [dfs] Easy to understand solution | mtx2d | -1 | 88 | reverse nodes in even length groups | 2,074 | 0.521 | Medium | 28,662 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1576914/Jump-Columns-%2B-1 | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
cols, res = len(encodedText) // rows, ""
for i in range(cols):
for j in range(i, len(encodedText), cols + 1):
res += encodedText[j]
return res.rstrip() | decode-the-slanted-ciphertext | Jump Columns + 1 | votrubac | 57 | 2,000 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,663 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1588641/Simple-Python-Solution-using-matrix-and-performing-operations-as-given-in-question%3A-Brute-force | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
#print(len(encodedText),rows,len(encodedText)//rows)
if len(encodedText)==0:
return ""
ans =''
x =[]
c = len(encodedText)//rows
for i in range(0,len(encodedText),c):
x.append(list(encodedText[i:i+c]))
#print(x)
for i in range(c):
k = i
p=''
for j in range(rows):
try:
p = p+x[j][k]
except:
pass
k = k+1
ans = ans+p
return ans.rstrip() | decode-the-slanted-ciphertext | Simple Python Solution using matrix and performing operations as given in question: Brute force | user8744WJ | 2 | 124 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,664 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1753881/Python | class Solution:
def decodeCiphertext(self, s: str, rows: int) -> str:
if not s: return ""
n=len(s)
cols=n//rows
arr=[" "]*n
for i in range(rows):
for j in range(cols):
if i>j: continue
arr[i+rows*(j-i)]=s[i*cols+j]
i=n-1
while i>=0 and arr[i]==" ":
i-=1
return ''.join(arr[:i+1]) | decode-the-slanted-ciphertext | Python | ketan_raut | 1 | 58 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,665 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1627031/Python3-260ms-runtime-Faster-than-96-and-uses-91-less-memory | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
op = ''
total_cols = int( len(encodedText) / rows )
row = 0
col = 0
while True:
try:
calc = (row*total_cols)+row+col
char = encodedText[calc]
except IndexError:
break
op += char
row+=1
if row == rows:
row = 0
col+=1
return op.rstrip() | decode-the-slanted-ciphertext | [Python3] 260ms runtime, Faster than 96% and uses 91% less memory | GauravKK08 | 1 | 69 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,666 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1579817/Python-simple-solution | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
n = len(encodedText)
res = []
cols = n // rows
for i in range(cols):
for j in range(i, n, cols+1):
res.append(encodedText[j]) # it is observed that skipping cols+1 from a given pos gives the required char
return ''.join(res).rstrip(' ') # removes trailing spaces from right | decode-the-slanted-ciphertext | Python simple solution | abkc1221 | 1 | 71 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,667 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1577063/Python3-simulation | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
cols = len(encodedText)//rows
ans = []
for offset in range(cols):
i, j = 0, offset
while i*cols+j < len(encodedText):
ans.append(encodedText[i*cols+j])
i, j = i+1, j+1
return "".join(ans).rstrip() | decode-the-slanted-ciphertext | [Python3] simulation | ye15 | 1 | 94 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,668 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/2849828/Python-simple-iterative-solution | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
cols = len(encodedText)//rows
res = ""
for i in range(cols):
idx = i
for j in range(rows):
if idx >= len(encodedText):
break
res += encodedText[idx]
idx += (cols+1)
i = len(res)-1
while i >= 0:
if res[i] != " ":
break
i -= 1
return res[:i+1] | decode-the-slanted-ciphertext | Python simple iterative solution | ankurkumarpankaj | 0 | 2 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,669 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/2690629/Python-Easy-Way | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
if rows == 1:
return encodedText
col = int(len(encodedText) / rows)
lines = [[' ' for _ in range(col)] for _ in range(rows)]
for idx, c in enumerate(encodedText):
lines[idx // col][(idx % col)] = c
originalText = ""
for c in range(col):
begin = c
i = 0
for r in range(rows):
if c+i >= col:
break
originalText += lines[r][c+i]
i += 1
return originalText.rstrip() | decode-the-slanted-ciphertext | Python Easy Way | ash1209 | 0 | 12 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,670 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/2366242/Python-or-Simple-solution-and-a-bonus-one-liner-solution! | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
n = len(encodedText)
cols = n // rows
step = cols + 1
res = ""
for i in range(cols):
for j in range(i, n, step):
res += encodedText[j]
return res.rstrip() | decode-the-slanted-ciphertext | Python | Simple solution and a bonus one-liner solution! | ahmadheshamzaki | 0 | 24 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,671 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/2366242/Python-or-Simple-solution-and-a-bonus-one-liner-solution! | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
return "".join(encodedText[j] for i in range(len(encodedText) // rows) for j in range(i, len(encodedText), len(encodedText) // rows + 1)).rstrip() | decode-the-slanted-ciphertext | Python | Simple solution and a bonus one-liner solution! | ahmadheshamzaki | 0 | 24 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,672 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1976128/Python-solution-by-building-the-grid | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
n = len(encodedText)
ans = [""] * n
cols = n//rows
grid = [[" "] * cols for _ in range(rows)]
k = 0
for i, j in product(range(rows), range(cols)):
grid[i][j] = encodedText[k]
k += 1
i, j = 0, 0
l = 0
t = 0
while i < rows and j < cols:
ans[l] = grid[i][j]
i += 1
j += 1
l += 1
if i >= rows:
t += 1
i = 0
j = t
if j >= cols:
break
finalAns = (''.join(ans)).rstrip()
return finalAns | decode-the-slanted-ciphertext | Python solution by building the grid | user6397p | 0 | 27 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,673 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1579310/Cut-the-string-and-zip_longest-100-speed-100-memory | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
if rows == 1:
return encodedText
cols = len(encodedText) // rows
matrix = [encodedText[i * cols + i: (i + 1) * cols] for i in range(rows)]
return "".join("".join(c)
for c in zip_longest(*matrix, fillvalue=" ")).rstrip(" ") | decode-the-slanted-ciphertext | Cut the string and zip_longest, 100% speed 100% memory | EvgenySH | 0 | 20 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,674 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1576986/Simple-Python-or-easy-to-Understand | class Solution:
def decodeCiphertext(self, et: str, rows: int) -> str:
n=len(et)
col=n//rows
mat=[[' ' for i in range(col)] for j in range(rows)]
x=0
for i in range(rows):
for j in range(col):
mat[i][j]=et[x]
x+=1
ans=""
j=0
for j in range(col):
for i in range(rows):
if i<rows and i+j<col:
ans+=mat[i][i+j]
return ans.rstrip() | decode-the-slanted-ciphertext | Simple Python | easy to Understand | acloj97 | 0 | 37 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,675 |
https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1868651/Python3-SIMULATION | class Solution:
def decodeCiphertext(self, et: str, rows: int) -> str:
L = len(et)
if not L: return et
cols, ans, start = L//rows, et[0], 0
i, j = 0, start
while start < cols - 1:
i, j = i + 1, j + 1
if i == rows or j == cols:
start += 1
i, j = 0, start
ans += et[start]
continue
ans += et[cols*i + j]
return ans.rstrip() | decode-the-slanted-ciphertext | [Python3] SIMULATION | artod | -2 | 35 | decode the slanted ciphertext | 2,075 | 0.502 | Medium | 28,676 |
https://leetcode.com/problems/process-restricted-friend-requests/discuss/1577153/Python-272-ms36-MB-Maintain-connected-components-of-the-graph | class Solution:
def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:
result = [False for _ in requests]
connected_components = [{i} for i in range(n)]
connected_comp_dict = {}
for i in range(n):
connected_comp_dict[i] = i
banned_by_comps = [set() for i in range(n)]
for res in restrictions:
banned_by_comps[res[0]].add(res[1])
banned_by_comps[res[1]].add(res[0])
for i,r in enumerate(requests):
n1, n2 = r[0], r[1]
c1, c2 = connected_comp_dict[n1], connected_comp_dict[n2]
if c1 == c2:
result[i] = True
else:
if not (connected_components[c1].intersection(banned_by_comps[c2]) or connected_components[c2].intersection(banned_by_comps[c1])):
connected_components[c1].update(connected_components[c2])
banned_by_comps[c1].update(banned_by_comps[c2])
for node in connected_components[c2]:
connected_comp_dict[node] = c1
result[i] = True
return result | process-restricted-friend-requests | [Python] [272 ms,36 MB] Maintain connected components of the graph | LonelyQuantum | 2 | 189 | process restricted friend requests | 2,076 | 0.532 | Hard | 28,677 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1589119/Python3-one-of-end-points-will-be-used | class Solution:
def maxDistance(self, colors: List[int]) -> int:
ans = 0
for i, x in enumerate(colors):
if x != colors[0]: ans = max(ans, i)
if x != colors[-1]: ans = max(ans, len(colors)-1-i)
return ans | two-furthest-houses-with-different-colors | [Python3] one of end points will be used | ye15 | 25 | 887 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,678 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1908014/90-O(n)-Fast-and-Easy-2-pointer-Greedy | class Solution:
def maxDistance(self, colors: List[int]) -> int:
#first pass
l, r = 0, len(colors)-1
dist = 0
while r > l:
if colors[r] != colors[l]:
dist = r-l
#slight performance increase, break out if you find it
#because it can't get bigger than this
break
r -= 1
#second pass, backwards
l, r = 0, len(colors)-1
while r > l:
if colors[r] != colors[l]:
dist = max(dist, r-l)
break
l += 1
return dist | two-furthest-houses-with-different-colors | 90% O(n) - Fast & Easy 2-pointer / Greedy | bwlee13 | 4 | 381 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,679 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1775316/Python3-or-both-side-checking-or-fastest | class Solution:
def maxDistance(self, colors: List[int]) -> int:
clr1=colors[0]
clr2=colors[-1]
mx=0
for i in range(len(colors)-1,-1,-1):
if clr1!=colors[i]:
mx=max(mx,i)
break
for i in range(len(colors)):
if clr2!=colors[i]:
mx=max(mx,len(colors)-i-1)
return mx | two-furthest-houses-with-different-colors | Python3 | both side checking | fastest | Anilchouhan181 | 4 | 249 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,680 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/2324246/Two-solutions-O(n)-and-O(n2) | class Solution:
def maxDistance(self, colors: List[int]) -> int:
i=0
l=len(colors)
j=l-1
while colors[j] == colors[0]:
j-=1
while colors[-1] == colors[i]:
i+=1
return max(j,l-1-i) | two-furthest-houses-with-different-colors | Two solutions O(n) and O(n^2) | sunakshi132 | 3 | 195 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,681 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1616071/Simple-Python-Solution%3A-O(n) | class Solution:
def maxDistance(self, colors: List[int]) -> int:
n = len(colors)
if n < 2:
return 0
if colors[0]!=colors[-1]:
return n-1
d = 0
for i in range(n):
if colors[i] != colors[0]:
d = max(d,i)
if colors[i] != colors[-1]:
d = max(d,n-1-i)
return d | two-furthest-houses-with-different-colors | Simple Python Solution: O(n) | smaranjitghose | 3 | 276 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,682 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1955608/Python3-simple-solution | class Solution:
def maxDistance(self, colors: List[int]) -> int:
x = []
for i in range(len(colors)-1):
for j in range(i+1,len(colors)):
if colors[i] != colors[j]:
x.append(j-i)
return max(x) | two-furthest-houses-with-different-colors | Python3 simple solution | EklavyaJoshi | 2 | 48 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,683 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/2832543/Two-Farthest-Houses-oror-Python-Easy-with-one-pointer-fixed-oror-O(n) | class Solution:
def maxDistance(self, colors: List[int]) -> int:
# take one color from front and another from back
# return the distance b/w them
front = 0
rear = len(colors) - 1
while rear >= 0 and colors[front] == colors[rear]:
rear -= 1
v1 = rear - front
front = 0
rear = len(colors) - 1
while front < len(colors) and colors[front] == colors[rear]:
front += 1
v2 = rear - front
return max(v1, v2) | two-furthest-houses-with-different-colors | Two Farthest Houses || Python Easy with one pointer fixed || O(n) | darsigangothri0698 | 0 | 1 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,684 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/2811796/Python3-Solution-with-using-two-pointers | class Solution:
def maxDistance(self, colors: List[int]) -> int:
first_diff_color, last_diff_color = 0, len(colors) - 1
while colors[len(colors) - 1] == colors[first_diff_color]:
first_diff_color += 1
while colors[0] == colors[last_diff_color]:
last_diff_color -= 1
return max(last_diff_color - 0, len(colors) - 1 - first_diff_color) | two-furthest-houses-with-different-colors | [Python3] Solution with using two-pointers | maosipov11 | 0 | 1 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,685 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/2776847/Python-simple-solution-with-explanation | class Solution:
def maxDistance(self, colors: List[int]) -> int:
maxcount = 0
for i in range(len(colors)):
count = 0
for j in range(len(colors)):
if colors[i]!=colors[j]:
count = abs(i-j)
if count>maxcount:
maxcount = count
return maxcount | two-furthest-houses-with-different-colors | Python simple solution with explanation | Rajeev_varma008 | 0 | 1 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,686 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/2455047/Easy-Python-Solution | class Solution:
def maxDistance(self, colors: List[int]) -> int:
n = len(colors)
firstHouseIdx = 0
lastHouseIdx = n - 1
if colors[firstHouseIdx] != colors[lastHouseIdx]:
return lastHouseIdx - firstHouseIdx
ans = 0
for i in range(1, n-1):
if colors[firstHouseIdx] != colors[i]:
ans = max(ans, abs(firstHouseIdx-i))
if colors[lastHouseIdx] != colors[i]:
ans = max(ans, abs(lastHouseIdx-i))
return ans | two-furthest-houses-with-different-colors | Easy Python Solution | yash921 | 0 | 69 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,687 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/2114265/Python-simple-solution | class Solution:
def maxDistance(self, colors: List[int]) -> int:
ans = []
for i in range(len(colors)):
for j in range(i, len(colors)):
if i == j: continue
if colors[i] != colors[j]:
ans.append(j-i)
return max(ans) | two-furthest-houses-with-different-colors | Python simple solution | StikS32 | 0 | 71 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,688 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1963242/Python-Two-Pointers-Clean-and-Simple! | class Solution:
def maxDistance(self, colors):
l = 0; r = n = len(colors)-1
while colors[l] == colors[r]: l += 1
while colors[r] == colors[0]: r -= 1
return max(r, n-l) | two-furthest-houses-with-different-colors | Python - Two-Pointers - Clean and Simple! | domthedeveloper | 0 | 103 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,689 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1963242/Python-Two-Pointers-Clean-and-Simple! | class Solution:
def maxDistance(self, colors):
l = 0; r = n = len(colors)-1
while colors[l] == colors[r]: r -= 1
while colors[n] == colors[l]: l += 1
return max(r, n-l) | two-furthest-houses-with-different-colors | Python - Two-Pointers - Clean and Simple! | domthedeveloper | 0 | 103 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,690 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1930428/Python-dollarolution | class Solution:
def maxDistance(self, colors: List[int]) -> int:
s = {}
for i in range(len(colors)):
if colors[i] in s:
s[colors[i]][1] = i
else:
s[colors[i]] = [i,i]
b, e = [],[]
for i in s:
b.append(s[i][0])
e.append(s[i][1])
m = 0
for i in range(len(b)):
x = max(e[:i] + e[i+1:]) - b[i]
if x > m:
m = x
return m | two-furthest-houses-with-different-colors | Python $olution | AakRay | 0 | 26 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,691 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1915526/Python-easy-solution-for-beginners | class Solution:
def maxDistance(self, colors: List[int]) -> int:
dist = 0
for i in range(len(colors)):
for j in range(len(colors)-1, 0, -1):
if colors[i] != colors[j]:
if abs(i - j) > dist:
dist = abs(i - j)
return dist | two-furthest-houses-with-different-colors | Python easy solution for beginners | alishak1999 | 0 | 63 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,692 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1865406/Python-(Simple-Approach-and-Beginner-Friendly) | class Solution:
def maxDistance(self, colors: List[int]) -> int:
maxi = 0
for i in range(0, len(colors)):
for j in range(1, len(colors)):
if colors[i]!=colors[j]:
maxi = max(maxi, abs(i-j))
return maxi | two-furthest-houses-with-different-colors | Python (Simple Approach and Beginner-Friendly) | vishvavariya | 0 | 47 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,693 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1702115/Python3-Two-Scans-O(N)-Memory-Less-Than-91.32 | class Solution:
def maxDistance(self, colors: List[int]) -> int:
first, second = colors[0], colors[-1]
for i in range(1, len(colors)):
if colors[i] != first:
t1 = i
for i in range(len(colors) -1, -1, -1):
if colors[i] != second:
t2 = i
return max(t1, len(colors) - 1 - t2) | two-furthest-houses-with-different-colors | Python3, Two Scans O(N), Memory Less Than 91.32% | Hejita | 0 | 98 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,694 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1690776/WEEB-DOES-PYTHON-2-POINTERS-(BEATS-99.02) | class Solution:
def maxDistance(self, colors: List[int]) -> int:
low = 0
result = 0
for high in range(len(colors)-1, -1, -1):
if colors[high] != colors[low]:
result = high - low
break
high = len(colors) - 1
for low in range(len(colors)):
if colors[low] != colors[high]:
result = max(result, high - low)
break
return result | two-furthest-houses-with-different-colors | WEEB DOES PYTHON 2 POINTERS (BEATS 99.02%) | Skywalker5423 | 0 | 109 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,695 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1625655/Easy-Python-Code-Runtime-98.96 | class Solution:
def maxDistance(self, colors: List[int]) -> int:
ans=0
for left in range(len(colors)):
right=len(colors)-1
while right > left:
if colors[right]!=colors[left]:
ans=max(right-left,ans)
break
else:
right-=1
if len(colors)-1-left < ans:
return(ans)
return(ans) | two-furthest-houses-with-different-colors | Easy Python Code Runtime 98.96% | w597111034 | 0 | 111 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,696 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1591255/Python-fastest-solution | class Solution:
def maxDistance(self, colors: List[int]) -> int:
if colors[0] != colors[-1]:
return len(colors) -1
is_not_found = True
pointer_left = 2
pointer_right = 1
while is_not_found:
if colors[0] != colors[-pointer_left]:
is_not_found = False
else:
pointer_left +=1
is_not_found = True
while is_not_found:
if colors[-1] != colors[pointer_right]:
is_not_found = False
else:
pointer_right +=1
#print(pointer_right, pointer_left)
if pointer_right < pointer_left:
return len(colors) - 1 - pointer_right
else:
return len(colors) - pointer_left | two-furthest-houses-with-different-colors | Python fastest solution | kaibauerle | 0 | 47 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,697 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1590597/Python-3-O(n)-time-O(1)-space | class Solution:
def maxDistance(self, colors: List[int]) -> int:
first = colors[0]
last = colors[-1]
n = len(colors) - 1
for i in range(n // 2 + 1):
if colors[i] != last or colors[-i-1] != first:
return n - i | two-furthest-houses-with-different-colors | Python 3 O(n) time, O(1) space | dereky4 | 0 | 88 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,698 |
https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1590502/Python-O(N)O(1) | class Solution:
def maxDistance(self, colors: List[int]) -> int:
idx = len(colors) - 1
first = colors[0]
while colors[idx] == first:
idx -= 1
distance = idx
idx = 0
last = colors[-1]
while colors[idx] == last:
idx += 1
return max(distance, len(colors) - 1 - idx) | two-furthest-houses-with-different-colors | Python, O(N)/O(1) | blue_sky5 | 0 | 41 | two furthest houses with different colors | 2,078 | 0.671 | Easy | 28,699 |
Subsets and Splits