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/verifying-an-alien-dictionary/discuss/1448977/Python3Python-Simple-solution-using-dictionary-w-comments | class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
# 'โ
' is defined as the blank character which
# is less than any other character
order = {c: i for i,c in enumerate(order)}
# Get num of words
m = len(words)
# loop from index 1 to m
for k in range(1,m):
# Get length of current and previous word
a = len(words[k-1])
b = len(words[k])
# get min of length of current and previous word
n = min(a,b)
# If k is prefix of k-1 return false else true
if words[k-1][:n] == words[k][:n]:
if a > b:
return False
else:
return True
# Loop through all the charactes till n
for i in range(n):
# If order of a character in previous word is greater return false
if order[words[k-1][i]] > order[words[k][i]]:
return False
# If order of a character in current word is greater no need to look ahead
elif order[words[k-1][i]] < order[words[k][i]]:
break
# if order of character at same index in current and previous
# word is same, continue checking
else:
pass
return True | verifying-an-alien-dictionary | [Python3/Python] Simple solution using dictionary w/ comments | ssshukla26 | 0 | 91 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,500 |
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1426071/Python3-Faster-Than-85.26-Memory-Less-Than-98.32 | class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
d, i = {}, 0
for index, letter in enumerate(order):
d[letter] = index
while(i < len(words) - 1):
equal = True
s1, s2, j = words[i], words[i + 1], 0
while j < min(len(s1), len(s2)):
if d[s1[j]] < d[s2[j]]:
equal = False
break
elif d[s1[j]] > d[s2[j]]:
return False
else:
j += 1
if equal:
if len(s2) < len(s1):
return False
i += 1
return True | verifying-an-alien-dictionary | Python3 Faster Than 85.26%, Memory Less Than 98.32% | Hejita | 0 | 96 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,501 |
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1265077/Python-Non-One-Liner-With-Explanation | class Solution(object):
def isAlienSorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
# 1. Create a dict which assigns a value to each letter in dictionary
# 2. Iterate through words, checking letter by letter for if value of letter is >, <, ==
# 3. Return true or false based on that iteration
alienDict = dict()
value = 0
if len(words) == 1:
return True
for c in order:
alienDict[c] = value
value += 1
i = 0
while i + 1 < len(words):
shorter = min(len(words[i]), len(words[i+1]))
for c in range(shorter):
if alienDict[words[i][c]] > alienDict[words[i+1][c]]:
return False
elif alienDict[words[i][c]] == alienDict[words[i+1][c]]:
equalChar = True
else:
equalChar = False
break
if equalChar:
if len(words[i]) > len(words[i+1]):
return False
i += 1
return True | verifying-an-alien-dictionary | Python Non-One Liner With Explanation | jmwyds | 0 | 128 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,502 |
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1149951/Simple-solution-in-Python-using-a-Hashmap-and-sorting | class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
hashmap = dict()
for i in range(len(order)):
hashmap[order[i]] = i
score = [[hashmap[i] for i in word] for word in words]
return sorted(score) == score | verifying-an-alien-dictionary | Simple solution in Python using a Hashmap and sorting | amoghrajesh1999 | 0 | 39 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,503 |
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/541049/Python-sol-by-comparison.-90%2B-wHint | class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
# alphabet dictionary with alien order
dictionary = { letter : idx for idx, letter in enumerate(order) }
def chk_in_order( word1: str, word2: str):
for i in range( min(len(word1), len(word2) ) ):
# current letter is out-of-order
if dictionary[ word1[i] ] > dictionary[ word2[i] ]:
return False
# current letter is in-order
elif dictionary[ word1[i] ] < dictionary[ word2[i] ]:
return True
# if current letter is the same, then compare next one
# if all the same, then comapre string length
return ( len(word1) < len(word2) )
# --------------------------------------------------------
for idx in range( len(words)-1 ):
if not chk_in_order( words[idx], words[idx+1] ):
return False
return True | verifying-an-alien-dictionary | Python sol by comparison. 90%+ [w/Hint] | brianchiang_tw | 0 | 243 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,504 |
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/382166/Solution-in-Python-3-(one-line) | class Solution:
def isAlienSorted(self, w: List[str], a: str) -> bool:
return (lambda x: all([w[i].translate(x) < w[i+1].translate(x) for i in range(len(w)-1)]))(str.maketrans(a,string.ascii_lowercase))
- Junaid Mansuri
(LeetCode ID)@hotmail.com | verifying-an-alien-dictionary | Solution in Python 3 (one line) | junaidmansuri | -2 | 559 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,505 |
https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1378617/Best-code-Explaination-or-Any-programmer-can-understand-or-Python-Code-or-Very-easy-to-understand | class Solution:
def compare(self, cache, word1, word2):
i, j = 0,0
while i < len(word1) and j < len(word2):
if cache[word1[i]] < cache[word2[j]]:
return True
elif cache[word1[i]] > cache[word2[j]]:
return False
else: #letters equal case
i += 1
j += 1
if i < len(word1):
return False
"""
why false?
In some cases word1 can be aaa, word2 can be aa
here we must return false becoz they are not in lexicographic order
becoz word2 appears first than word1
"""
return True #same words case and shorter words case like aa, aaa i will definitely reach end
def isAlienSorted(self, words: List[str], order: str) -> bool:
"""
Main Idea behind this is,
How we see our Oxford or Some english Dictionary (So called lexicographic order)
Eg:
Case 1:
Assume we have words like ad, af, ag, ba, bba, bbaaaag in our oxford Dictionary
at diff page numbers Now compare the page numbers of these words once it is for sure
pageNumber(ad) < pageNumber(af) < pageNumber(ag) < ... pageNumber(bbaaag)
Case 2:
if we go in depth
if two 2 words are in same page, say x, xy
it is for sure LineNumber(x) < lineNumber(xy) (Note < operator is Strictly lesser)
Case 3:
Words like a, aa, aaa, aaaa are in our dictionary
definitly appearance(a) < appearance(aa) < appearance(aaa) < appearance(aaaa)
appearance may be a line number or page number
"""
"""
In our Question there are asking for a different alphabetical order and asking us to check
whether appearance(word1) < appearance(word2) < appearance(word3) < ... < appearance(wordn) or not
Just compare
word1 with word2
word2 with word3
word3 with word4
....
wordn-1 with wordn
Reason: if word1 < word2 it is for sure lesser than word3 and so on
"""
cache = {}
for i in range(len(order)):
cache[order[i]] = i
for i in range(1, len(words)):
if not self.compare(cache, words[i-1], words[i]):
return False
return True | verifying-an-alien-dictionary | Best code Explaination | Any programmer can understand | Python Code | Very easy to understand | sathwickreddy | -3 | 404 | verifying an alien dictionary | 953 | 0.527 | Easy | 15,506 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/1840844/python-3-oror-O(nlogn) | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
count = collections.Counter(arr)
for n in sorted(arr, key=abs):
if count[n] == 0:
continue
if count[n * 2] == 0:
return False
count[n] -= 1
count[n * 2] -= 1
return True | array-of-doubled-pairs | python 3 || O(nlogn) | dereky4 | 1 | 81 | array of doubled pairs | 954 | 0.391 | Medium | 15,507 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/1810465/Python-Optimised-Counter-Solution-Explained | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
arr.sort(key=abs) # Sort the array based on the absolute value
cnt = Counter(arr) # Count the number of each element in arr
while cnt:
x = next(iter(cnt.keys())) # Get the next unique element x
# Handle conditionals (written on multiple lines for clarity)
if 2*x not in cnt or \ # Condition 1: 2x does not exist in arr
(x == 0 and cnt[x]&1) or \ # Condition 2: Odd number of 0s in arr
cnt[2*x] < cnt[x]: # Condition 3: Insufficient 2x to pair with x in arr
return False
cnt[2*x] -= cnt[x] # Remove the number of 2x elements needed for pairing with x
_ = cnt.pop(x) # All x paired; remove x entirely (for iteration purposes)
if cnt[2*x] == 0 and x != 0:
_ = cnt.pop(2*x) # Only remove 2x if there are no more 2x left
return True | array-of-doubled-pairs | [Python] Optimised Counter Solution Explained | zayne-siew | 1 | 69 | array of doubled pairs | 954 | 0.391 | Medium | 15,508 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/1398727/Greedy-oror-O(NlogN)-oror-Clean-and-Concise-oror-93-faster | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
dic = Counter(arr)
res = []
for n in sorted(arr):
if dic[n]>0:
dic[n]-=1 # This is to check 0 if it present take e.g. : [4,0]
if 2*n in dic and dic[2*n]>0:
dic[2*n]-=1
res.append((n,2*n))
else:
dic[n]+=1
return len(res)*2==len(arr) | array-of-doubled-pairs | ๐ Greedy || O(NlogN) || Clean & Concise || 93% faster ๐๐ | abhi9Rai | 0 | 73 | array of doubled pairs | 954 | 0.391 | Medium | 15,509 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/1397824/python3-oror-clean-oror-simple-approach | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
d={}
arr.sort()
print(arr)
for i in range (0,len(arr)):
if arr[i] in d:
d[arr[i]] +=1
else:
d[arr[i]]=1
print(d)
for key in d:
if d[key]==0:
continue
if key <0:
target=key//2
else:
target=key*2
if target not in d:
return False
if key < 0 and key%2!=0:
return False
if d[key]> d[target]:
return False
else:
d[target]=d[target]-d[key]
return True | array-of-doubled-pairs | python3 || clean || simple approach | minato_namikaze | 0 | 93 | array of doubled pairs | 954 | 0.391 | Medium | 15,510 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/1397426/Just-did-what-I-know-! | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
def helper(nums) :
stack = []
while nums :
top = nums.pop(0)
if stack and 2*stack[0] == top :
stack.pop(0)
else:
stack.append(top)
if not stack :
return True
return False
nega = []
posi = []
zero = 0
for num in arr :
if num < 0 :
nega.append(num)
elif num > 0 :
posi.append(num)
else :
zero += 1
if zero%2 != 0 or len(nega)%2 != 0 or len(posi)%2 != 0 :
return False
nega.sort(reverse=True)
posi.sort()
return helper(nega) and helper(posi) | array-of-doubled-pairs | Just did what I know ! | abhijeetgupto | 0 | 47 | array of doubled pairs | 954 | 0.391 | Medium | 15,511 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/975041/Python3-freq-table | class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
freq = Counter(arr)
for x in sorted(freq, key=abs):
if freq[2*x] < freq[x]: return False
freq[2*x] -= freq[x]
return True | array-of-doubled-pairs | [Python3] freq table | ye15 | 0 | 81 | array of doubled pairs | 954 | 0.391 | Medium | 15,512 |
https://leetcode.com/problems/array-of-doubled-pairs/discuss/838398/Python-3-or-Hash-Table-or-Explanations | class Solution:
def canReorderDoubled(self, A: List[int]) -> bool:
A = sorted([-i if i < 0 else i for i in A], reverse=True)
n, c, cnt = len(A), collections.Counter(A), 0
for i in range(n):
if c[2*A[i]] > 0:
c[2*A[i]] -= 1
c[A[i]] -= 1
cnt += 1
return cnt >= n // 2 | array-of-doubled-pairs | Python 3 | Hash Table | Explanations | idontknoooo | -2 | 156 | array of doubled pairs | 954 | 0.391 | Medium | 15,513 |
https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/844457/Python-3-or-Greedy-DP-(28-ms)-or-Explanation | class Solution:
def minDeletionSize(self, A: List[str]) -> int:
m, n = len(A), len(A[0])
ans, in_order = 0, [False] * (m-1)
for j in range(n):
tmp_in_order = in_order[:]
for i in range(m-1):
# previous step, rows are not in order; and current step rows are not in order, remove this column
if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break
# previous step, rows are not in order, but they are in order now
elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True
# if column wasn't removed, update the row order information
else: in_order = tmp_in_order
# not necessary, but speed things up
if all(in_order): return ans
return ans | delete-columns-to-make-sorted-ii | Python 3 | Greedy, DP (28 ms) | Explanation | idontknoooo | 6 | 550 | delete columns to make sorted ii | 955 | 0.346 | Medium | 15,514 |
https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/1906030/PYTHON-SOL-oror-EXPLAINED-oror-WELL-COMMENTED-SOLUTION-oror-GREEDY-oror | class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
n = len(strs)
col_size = len(strs[0])
# a b c d e f g h i j k l m n o p q r s t u v w x y z
i = 0
ans = 0
def getRemoved(idx):
# removing the idx column
for x in range(n):
strs[x] = strs[x][:idx] + strs[x][idx+1:]
while i < col_size:
tmp = strs[0][:i+1]
flag = True
similar = False
for j in range(1,n):
if strs[j][:i+1] < tmp :
# previous element is larger ( unsorted )
flag = False
break
elif strs[j][:i+1] > tmp :
# previous element is smaller ( sorted )
tmp = strs[j][:i+1]
else:
# previous element is equal ( not clear )
tmp = strs[j][:i+1]
similar = True
if flag == True and similar == False:
# all are sorted and we are ready to return ans
return ans
elif flag == True and similar == True:
# all are sorted but can't be decided for further columns. check for next col
i += 1
elif flag == False:
# unsorted column = removal
getRemoved(i)
# increment the answer and since we removed i th col decrement col_size
ans += 1
col_size -= 1
return ans | delete-columns-to-make-sorted-ii | PYTHON SOL || EXPLAINED || WELL COMMENTED SOLUTION || GREEDY || | reaper_27 | 0 | 124 | delete columns to make sorted ii | 955 | 0.346 | Medium | 15,515 |
https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/1294831/Python3-greedy | class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
m, n = len(strs), len(strs[0]) # dimensions
ans, grp = 0, [0]*m
for j in range(n):
for i in range(1, m):
if grp[i-1] == grp[i] and strs[i-1][j] > strs[i][j]:
ans += 1
break
else:
for i in range(1, m):
grp[i] = max(grp[i-1], grp[i])
if grp[i-1] == grp[i] and strs[i-1][j] < strs[i][j]: grp[i] = i
return ans | delete-columns-to-make-sorted-ii | [Python3] greedy | ye15 | -1 | 105 | delete columns to make sorted ii | 955 | 0.346 | Medium | 15,516 |
https://leetcode.com/problems/tallest-billboard/discuss/1561795/Python3-dp-and-binary-search | class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
dp = {0: 0}
for x in rods:
for k, v in dp.copy().items():
dp[k+x] = max(dp.get(k+x, 0), v)
if k >= x: dp[k-x] = max(dp.get(k-x, 0), v+x)
else: dp[x-k] = max(dp.get(x-k, 0), v+k)
return dp[0] | tallest-billboard | [Python3] dp & binary search | ye15 | 0 | 273 | tallest billboard | 956 | 0.399 | Hard | 15,517 |
https://leetcode.com/problems/tallest-billboard/discuss/1561795/Python3-dp-and-binary-search | class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
def fn(arr):
"""Possible a mapping from diff to length"""
mp = defaultdict(int)
for t in range(1, len(arr)+1):
for total in combinations(arr, t):
tt = sum(total)
for p in range(0, t+1):
for part in combinations(total, p):
pp = sum(part)
mp[pp*2 - tt] = max(mp[pp*2 - tt], pp)
return mp
left = rods[:len(rods)//2]
right = rods[len(rods)//2:]
mp = fn(left)
keys = sorted(mp.keys())
ans = 0
for diff, v in fn(right).items():
k = bisect_left(keys, -diff)
if k < len(keys) and keys[k] == -diff:
ans = max(ans, mp[-diff] + v)
return ans | tallest-billboard | [Python3] dp & binary search | ye15 | 0 | 273 | tallest billboard | 956 | 0.399 | Hard | 15,518 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/347500/Python3-Prison-Cells-After-N-days%3A-dictionary-to-store-pattern | class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
def nextday(cells):
next_day_cells = [0] *len(cells)
for i in range(1,len(cells)-1):
if cells[i-1] == cells[i+1]:
next_day_cells[i] = 1
else:
next_day_cells[i] = 0
return next_day_cells
seen = {}
while N > 0:
c = tuple(cells)
if c in seen:
N %= seen[c] - N
seen[c] = N
if N >= 1:
N -= 1
cells = nextday(cells)
return cells | prison-cells-after-n-days | [Python3] Prison Cells After N days: dictionary to store pattern | zhanweiting | 33 | 3,800 | prison cells after n days | 957 | 0.391 | Medium | 15,519 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/744326/Very-Intuitive-Python-Detailed-Solution-with-Example | class Solution(object):
def prisonAfterNDays(self, cells, N):
"""
:type cells: List[int]
:type N: int
:rtype: List[int]
"""
def next(state):
return tuple([1 if i>0 and i<len(state)-1 and state[i-1] == state[i+1] else 0 for i in range(len(state))])
seen = {}
state = tuple(cells)
i = 0
remaining = 0
while i < N:
if state in seen:
cycle = i - seen[state]
remaining = (N-i)%cycle
break
seen[state] = i
state = next(state)
i+=1
while remaining > 0:
state = next(state)
remaining-=1
return state | prison-cells-after-n-days | Very Intuitive Python Detailed Solution with Example | ivankatrump | 11 | 841 | prison cells after n days | 957 | 0.391 | Medium | 15,520 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/2077309/EXPLAINED-by-picture | class Solution:
def prisonAfterNDays(self, c, n) :
return self.prisonAfterNDays([0, c[0]==c[2], c[1]==c[3], c[2]==c[4], c[3]==c[5], c[4]==c[6], c[5]==c[7], 0], (n-1)%14) if n else [int(i) for i in c] | prison-cells-after-n-days | ๐ฉ EXPLAINED by picture ^^ | andrii_khlevniuk | 3 | 199 | prison cells after n days | 957 | 0.391 | Medium | 15,521 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/2077309/EXPLAINED-by-picture | class Solution:
def prisonAfterNDays(self, c, n) :
for _ in range(1+(n-1)%14) :
p=-1
for i in range(8) :
p, c[i] = c[i], int(i<7 and p==c[i+1])
return c | prison-cells-after-n-days | ๐ฉ EXPLAINED by picture ^^ | andrii_khlevniuk | 3 | 199 | prison cells after n days | 957 | 0.391 | Medium | 15,522 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/2518634/Python-Detecting-repeated-patterns-No-Dictionary-With-Intuition | class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
# since the first and the last cell will always be zero after the
# first day, the array only has 2**(8-2) = 64 states
# therefore the cells will be repeated after more than 64 days
#
# in addition to that the rules are deterministic. So as soon
# as we encounter our state after one day (Note: not the state
# of day one, as out cells might be occupied there), we found
# a cycle and can go on from there.
if not n:
return cells
cells = convert_cells(cells)
day1 = str(cells)
n -= 1
counter = 0
while n:
# get the new cells
new_cells = convert_cells(cells)
n -= 1
counter += 1
# compare to the day1
if str(new_cells) == day1:
# our pattern is repeated and we found the cycle length (counter)
# therefore we can shorten all cycles from here and just do the
# leftover steps in the unfinished cycle.
n = n % counter
cells = new_cells
# the solution does not accept bools
return map(int, cells)
def convert_cells(cells):
# make a new cell
cells2 = cells.copy()
# iterate over all cells
# other than the outer ones
for index in range(1, len(cells)-1):
cells2[index] = cells[index-1] == cells[index+1]
cells2[0] = False
cells2[-1] = False
return cells2 | prison-cells-after-n-days | [Python] - Detecting repeated patterns - No Dictionary - With Intuition | Lucew | 2 | 140 | prison cells after n days | 957 | 0.391 | Medium | 15,523 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/1918973/PYTHON-SOL-oror-FAST-oror-MATHS-oror-WELL-EXPLAINED-oror-PATTERN-oror-LOGIC-EXPLAINED-oror | class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
n = n%14 if n%14!=0 else 14
for _ in range(n):
new = [0]*8
for i in range(1,7):
if cells[i-1]==cells[i+1]: new[i] = 1
cells = new
return cells | prison-cells-after-n-days | PYTHON SOL || FAST || MATHS || WELL EXPLAINED || PATTERN || LOGIC EXPLAINED || | reaper_27 | 2 | 207 | prison cells after n days | 957 | 0.391 | Medium | 15,524 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/2129910/Easy-Python-Solution-Faster-than-95-(36ms) | class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
new_cells = [0] * len(cells)
if n % 14 != 0:
n = n % 14
else:
n = 14
while n > 0:
for i in range(1, len(cells)-1):
if cells[i-1] == cells[i+1]:
new_cells[i] = 1
else:
new_cells[i] = 0
cells = new_cells.copy()
n -= 1
return new_cells | prison-cells-after-n-days | Easy Python Solution - Faster than 95% (36ms) | kn_vardhan | 1 | 87 | prison cells after n days | 957 | 0.391 | Medium | 15,525 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/1743890/Python-Dynamic-and-Fix-Loop | class Solution:
def prisonAfterNDays(self, nums: List[int], n: int) -> List[int]:
n=(n-1)%14+1
for i in range(1,n+1):
temp=list(nums)
temp[0],temp[7] = 0,0
for j in range(1,7):
if nums[j-1]==nums[j+1]:
temp[j]=1
else: temp[j]=0
nums=list(temp)
return nums | prison-cells-after-n-days | Python Dynamic and Fix Loop | shandilayasujay | 1 | 204 | prison cells after n days | 957 | 0.391 | Medium | 15,526 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/1743890/Python-Dynamic-and-Fix-Loop | class Solution:
def prisonAfterNDays(self, nums: List[int], n: int) -> List[int]:
s=[]
for i in range(1,n+1):
temp=list(nums)
temp[0],temp[7] = 0,0
for j in range(1,7):
if nums[j-1]==nums[j+1]:
temp[j]=1
else: temp[j]=0
nums=list(temp)
if nums in s:
return s[n%(i-1)-1]
else:
s.append(nums)
return nums | prison-cells-after-n-days | Python Dynamic and Fix Loop | shandilayasujay | 1 | 204 | prison cells after n days | 957 | 0.391 | Medium | 15,527 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/864181/Python-3-or-Cycle-Hash-Table-or-Explanation | class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
id_cells, cells_id = dict(), dict()
prev, loop = cells[:], None
for k in range(N):
for i in range(1, 7):
cells[i] = 1 if prev[i+1] == prev[i-1] else 0
cells[0] = cells[7] = 0
if tuple(cells) in cells_id:
loop = k-cells_id[tuple(cells)]
break
id_cells[k], cells_id[tuple(cells)] = cells[:], k
prev = cells[:]
return id_cells[(N-k-1)%loop] if loop else cells | prison-cells-after-n-days | Python 3 | Cycle, Hash Table | Explanation | idontknoooo | 1 | 464 | prison cells after n days | 957 | 0.391 | Medium | 15,528 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/717747/Python-3-solution-with-concise-explanation | class Solution:
def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
"""
1. The first and the last element will always become 0 after one
transformation step.
2. So the actual loop happened between the combinations of the 6
numbers in the middle.
3. If initially the first and the last number is not zero, after one
transformation step, it will enter the loop.
4. If initially the first and the last number are zeros, after one
transformation step, it will still be inside that loop.
5. So we tried to record all the previous unique states until an
existing state is found again, where cycleLen will hold the total
length of the cycle.
6. Then the last state will be determined by the target index
as (N - 1) % cycleLen.
"""
visited = []
currState = self.get_next_state(cells)
cycleLen = 0
while currState not in visited:
visited.append(currState)
currState = self.get_next_state(currState)
cycleLen += 1
return visited[(N - 1) % cycleLen]
def get_next_state(self, currState: List[int]) -> List[int]:
nextState = [0] * 8
for i in range(1, 7):
nextState[i] = currState[i - 1] ^ currState[i + 1] ^ 1
return nextState | prison-cells-after-n-days | Python 3 solution with concise explanation | eroneko | 1 | 56 | prison cells after n days | 957 | 0.391 | Medium | 15,529 |
https://leetcode.com/problems/prison-cells-after-n-days/discuss/1304180/Python-Bit-manipulation-and-memory-table | class Solution:
def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:
counter = 0
bitmap = 0
# cells to bitmap
for b in cells:
bitmap = (bitmap<<1)|b
# memory table
idToCount = {bitmap:counter}
countToCells = {counter:bitmap}
for j in range(n):
# bin(126) = 1111110
bitmap = ~((bitmap<<1)^(bitmap>>1))&126
counter += 1
if bitmap in idToCount:
dis = idToCount[bitmap]
# mod
bitmap = countToCells[(n-dis)%(counter-dis)+dis]
break
else:
idToCount[bitmap] = counter
countToCells[counter] = bitmap
# bitmap to cells
for i in range(8):
cells[7-i] = (bitmap>>i)&1
return cells | prison-cells-after-n-days | Python Bit manipulation and memory table | johnnylu305 | 0 | 130 | prison cells after n days | 957 | 0.391 | Medium | 15,530 |
https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/2287813/Python3-oror-bfs-8-lines-w-explanation-oror-TM%3A-9797 | class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
# The criteria for an n-level complete tree:
#
# โข The first n-1 rows have no null nodes.
#
# โข The nth row has no non-null nodes to the right of the left-most null
# node encountered (if it exists).
#
# The plan is to bfs the tree, left to right, level by level. We mark the
# instance of the first null popped from the queue and then ensure the remaining
# queue is only null nodes. If so, both criteria are satisfied and True is
# returned. If not, False is returned.
queue = deque([root]) # <-- initialize the queue
while queue[0]: # <-- if and while top queue node is not null, pop
node = queue.popleft() # it and then push its left child and right
queue.extend([node.left, node.right]) # child onto the queue.
while queue and not queue[0]: # <-- if and while top queue node is null, pop it.
queue.popleft() #
if queue: return False # <-- If the queue is not empty, it must be non-null, so
return True # return False; if the queue is empty, return True. | check-completeness-of-a-binary-tree | Python3 || bfs, 8 lines, w/ explanation || T/M: 97%/97% | warrenruud | 3 | 111 | check completeness of a binary tree | 958 | 0.538 | Medium | 15,531 |
https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/1775415/Easy-python3-solution-using-BFS-and-indexes | class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
res=[]
from collections import deque
q=deque()
q.append((root,1))
while q:
node,ind=q.popleft()
res.append(ind)
if node.left:
q.append((node.left,2*ind))
if node.right:
q.append((node.right,2*ind+1))
for i in range(len(res)-1):
if res[i+1]-res[i]!=1:
return False
return True | check-completeness-of-a-binary-tree | Easy python3 solution using BFS and indexes | Karna61814 | 1 | 74 | check completeness of a binary tree | 958 | 0.538 | Medium | 15,532 |
https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/2234169/Python-BFS | class Solution:
def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
q = deque([root])
missing = False
while q:
length = len(q)
for _ in range(length):
node = q.popleft()
if node.left:
if missing:
return False
q.append(node.left)
else:
missing = True
if node.right:
if missing:
return False
q.append(node.right)
else:
missing = True
return True | check-completeness-of-a-binary-tree | Python, BFS | blue_sky5 | 0 | 24 | check completeness of a binary tree | 958 | 0.538 | Medium | 15,533 |
https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/977153/Python3-BFS-O(N) | class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
i = -1
prev = 1/2
queue = [root]
while queue:
newq = []
flag = False
if prev != 2**i: return False # check previous level is full
for node in queue:
for child in (node.left, node.right):
if child:
if flag: return False
else: newq.append(child)
else: flag = True
i += 1
prev = len(queue)
queue = newq
return True | check-completeness-of-a-binary-tree | [Python3] BFS O(N) | ye15 | 0 | 90 | check completeness of a binary tree | 958 | 0.538 | Medium | 15,534 |
https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/860671/python-queue-appending-check-final-array-for-non-Nones | class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
queue = [root]
while queue[0]:
node = queue[0]
queue = queue[1:]
queue.append(node.left)
queue.append(node.right)
return not any(queue) | check-completeness-of-a-binary-tree | python, queue appending, check final array for non-Nones | anthcor | 0 | 68 | check completeness of a binary tree | 958 | 0.538 | Medium | 15,535 |
https://leetcode.com/problems/regions-cut-by-slashes/discuss/205674/DFS-on-upscaled-grid | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
def dfs(i: int, j: int) -> int:
if min(i, j) < 0 or max(i, j) >= len(g) or g[i][j] != 0:
return 0
g[i][j] = 1
return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1)
n, regions = len(grid), 0
g = [[0] * n * 3 for i in range(n * 3)]
for i in range(n):
for j in range(n):
if grid[i][j] == '/':
g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1
elif grid[i][j] == '\\':
g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1
for i in range(n * 3):
for j in range(n * 3):
regions += 1 if dfs(i, j) > 0 else 0
return regions | regions-cut-by-slashes | DFS on upscaled grid | votrubac | 733 | 23,400 | regions cut by slashes | 959 | 0.691 | Medium | 15,536 |
https://leetcode.com/problems/regions-cut-by-slashes/discuss/1311948/DFS-PYTHON-CLEAN | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
def check(x,y,t):
if x>=0 and y>=0 and x<row and y<col and (x,y,t) not in visited:
return True
return False
row,col=len(grid),len(grid[0])
visited=set()
def dfs(r,c,t):
if check(r,c,t):
visited.add((r,c,t))
if t==1:
dfs(r,c+1,3)# going right
elif t==2:
dfs(r+1,c,0)# going down
elif t==3:
dfs(r,c-1,1) # going back
elif t==0:
dfs(r-1,c,2)# going up
if grid[r][c]!="/":
dfs(r,c,t^1) #trick to traverse 0 to 1 or 3 to 2 and viceversa
if grid[r][c]!="\\":
dfs(r,c,t^3)#trick to traverse 3 to 0 or 1 to 2 and viceversa
cntofregion=0
for i in range(row):
for j in range(col):
for typ in range(4):
if (i,j,typ) not in visited:
dfs(i,j,typ)
cntofregion+=1
return cntofregion | regions-cut-by-slashes | DFS-PYTHON-CLEAN | manmohan1105 | 2 | 221 | regions cut by slashes | 959 | 0.691 | Medium | 15,537 |
https://leetcode.com/problems/regions-cut-by-slashes/discuss/2129956/Python-or-Flood-Fill-like-DFS-solution-Not-short-But-Clear~ | class Solution:
def regionsBySlashes(self, grid):
return self.flood_fill(grid)
def flood_fill(self, grid):
''' |\0/|
set area of cell like: |3X1|
|/2\|
dye and count like flood fill
'''
N = len(grid)
dye = [[[False] * 4 for _ in range(N)] for _ in range(N)]
def dfs(r, c, i):
if not 0 <= r < N or not 0 <= c < N: return # out of boundary
if dye[r][c][i]: return # already dyed
if grid[r][c] == ' ':
dye[r][c] = [True] * 4
dfs(r - 1, c, 2) # ^
dfs(r + 1, c, 0) # v
dfs(r, c - 1, 1) # <
dfs(r, c + 1, 3) # >
elif grid[r][c] == '/':
if i in [0, 3]:
dye[r][c][0] = True
dye[r][c][3] = True
dfs(r - 1, c, 2) # ^
dfs(r, c - 1, 1) # <
else:
dye[r][c][1] = True
dye[r][c][2] = True
dfs(r, c + 1, 3) # >
dfs(r + 1, c, 0) # v
else: # \
if i in [0, 1]:
dye[r][c][0] = True
dye[r][c][1] = True
dfs(r - 1, c, 2) # ^
dfs(r, c + 1, 3) # >
else:
dye[r][c][2] = True
dye[r][c][3] = True
dfs(r, c - 1, 1) # <
dfs(r + 1, c, 0) # v
count = 0
for r in range(N):
for c in range(N):
for i in range(4):
# skip if already dyed
if dye[r][c][i]: continue
# count and dye dfs
count += 1
dfs(r, c, i)
return count | regions-cut-by-slashes | Python | Flood-Fill-like DFS solution, Not short But Clear~ | steve-jokes | 0 | 92 | regions cut by slashes | 959 | 0.691 | Medium | 15,538 |
https://leetcode.com/problems/regions-cut-by-slashes/discuss/1920789/Python3-or-3x3-Matrix-or-DFS-or-Faster-than-81 | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
n, n3 = len(grid), len(grid) * 3
mat = [[0] * n3 for _ in range(n3)]
for i in range(n):
for j in range(n):
if grid[i][j] == "/":
mat[i * 3][j * 3 + 2] = 1;
mat[i * 3 + 1][j * 3 + 1] = 1;
mat[i * 3 + 2][j * 3] = 1;
if grid[i][j] == "\\":
mat[i * 3][j * 3] = 1;
mat[i * 3 + 1][j * 3 + 1] = 1;
mat[i * 3 + 2][j * 3 + 2] = 1;
def dfs(grid: List[List[int]], count: int, x, y, n):
if grid[x][y] != 0: return
grid[x][y] = count
if x + 1 < n :
dfs(grid, count, x + 1, y, n)
if y + 1 < n:
dfs(grid, count, x, y + 1, n)
if x - 1 >= 0:
dfs(grid, count, x - 1, y, n)
if y - 1 >= 0:
dfs(grid, count, x, y - 1, n)
count = 0
for i in range(n3):
for j in range(n3):
if mat[i][j] == 0:
count += 1
dfs(mat, count, i, j, n3)
return count | regions-cut-by-slashes | Python3 | 3x3 Matrix | DFS | Faster than 81% | milannzz | 0 | 79 | regions cut by slashes | 959 | 0.691 | Medium | 15,539 |
https://leetcode.com/problems/regions-cut-by-slashes/discuss/815325/Python-3-better-than-98-(DSU-method) | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
n,m=len(grid),len(grid[0])
parent=[i for i in range((n+1)*(m+1))]
rank=[1 for i in range((n+1)*(m+1))]
matrix=[]
cc=0
for i in range(n+1):
li=[]
for j in range(m+1):
li.append(cc)
cc+=1
matrix.append(li)
boundary=[]
boundary+=matrix[0]
for row in range(1,len(matrix)-1):
li=[matrix[row][0],matrix[row][-1]]
boundary+=li
boundary+=matrix[-1]
boundary=boundary[1:]
def find(x):
if parent[x]==x:
return x
temp=find(parent[x])
parent[x]=temp
return temp
def union(x,y):
parentx=find(x)
parenty=find(y)
if parentx!=parenty:
if rank[parentx]<rank[parenty]:
parent[parentx]=parenty
elif rank[parentx]>rank[parenty]:
parent[parenty]=parentx
else:
parent[parentx]=parenty
rank[parenty]+=1
for b in boundary:
union(0,b)
count=1
for row in range(n):
for col in range(m):
if grid[row][col]==" ":
continue
elif grid[row][col]=="\\":
point1=row*(m+1)+col
point2=(row+1)*(m+1)+(col+1)
else:
point1=((row+1)*(m+1))+(col)
point2=(row*(m+1))+(col+1)
pp1=find(point1)
pp2=find(point2)
union(point1,point2)
if pp1==pp2:
count+=1
return count | regions-cut-by-slashes | Python 3 better than 98% (DSU method) | codeenrrun | 0 | 153 | regions cut by slashes | 959 | 0.691 | Medium | 15,540 |
https://leetcode.com/problems/regions-cut-by-slashes/discuss/730936/Python-3-Easy-understanding-Union-Find-with-explanation | class Solution:
def regionsBySlashes(self, grid: List[str]) -> int:
'''
--------
| \ 0 / |
| 3\ / |
| /\ 1 |
|/ 2 \ |
|-------|
'''
self.N = len(grid)
# m_ = [i for i in range(self.N * self.N * 4)]
m_ = list(range(self.N * self.N * 4))
self.count = self.N * self.N * 4
for r in range(self.N):
line = grid[r]
for c in range(self.N):
w = line[c]
if r > 0: # no horizontal line '-'
self.u(m_, self.g(r - 1, c, 2), self.g(r, c, 0))
if c > 0: # no vertical line '|'
self.u(m_, self.g(r, c - 1, 1), self.g(r, c, 3))
if w != '/': # if not '/', then region 0 and 1 will be in the same region(set)
self.u(m_, self.g(r, c, 0), self.g(r, c, 1))
self.u(m_, self.g(r, c, 3), self.g(r, c, 2))
if w != '\\': # if not '\\', then region 1 and 2 will be in the same region(set)
self.u(m_, self.g(r, c, 0), self.g(r, c, 3))
self.u(m_, self.g(r, c, 1), self.g(r, c, 2))
return self.count
def f(self, m_, a): # find set
if m_[a] == a: # if parent found, return, else continue finding
return a
return self.f(m_, m_[a])
def u(self, m_, a, b): # union sets
pa = self.f(m_, a)
pb = self.f(m_, b)
if (pa == pb):
return
m_[pa] = pb
self.count -= 1
def g(self, r, c, i): # find exact region(set) for every element in grid
return (r * self.N + c) * 4 + i | regions-cut-by-slashes | Python 3 - Easy understanding Union Find -- with explanation | nbismoi | 0 | 282 | regions cut by slashes | 959 | 0.691 | Medium | 15,541 |
https://leetcode.com/problems/delete-columns-to-make-sorted-iii/discuss/1258211/Python3-top-down-dp | class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
m, n = len(strs), len(strs[0]) # dimensions
@cache
def fn(k, prev):
"""Return min deleted columns to make sorted."""
if k == n: return 0
ans = 1 + fn(k+1, prev) # delete kth column
if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(m)):
ans = min(ans, fn(k+1, k)) # retain kth column
return ans
return fn(0, -1) | delete-columns-to-make-sorted-iii | [Python3] top-down dp | ye15 | 2 | 139 | delete columns to make sorted iii | 960 | 0.571 | Hard | 15,542 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1337509/PYTHON-3-%3A-SUPER-EASY-99.52-FASTER | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
list1 = []
for i in nums :
if i in list1 :
return i
else :
list1.append(i) | n-repeated-element-in-size-2n-array | PYTHON 3 : SUPER EASY 99.52% FASTER | rohitkhairnar | 11 | 510 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,543 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1337509/PYTHON-3-%3A-SUPER-EASY-99.52-FASTER | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
set1 = set()
for i in nums :
if i in set1 :
return i
else :
set1.add(i) | n-repeated-element-in-size-2n-array | PYTHON 3 : SUPER EASY 99.52% FASTER | rohitkhairnar | 11 | 510 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,544 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1337509/PYTHON-3-%3A-SUPER-EASY-99.52-FASTER | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for i in nums :
if nums.count(i) == len(nums)/2 :
return i | n-repeated-element-in-size-2n-array | PYTHON 3 : SUPER EASY 99.52% FASTER | rohitkhairnar | 11 | 510 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,545 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1337509/PYTHON-3-%3A-SUPER-EASY-99.52-FASTER | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
dic = {}
for i in nums :
if i in dic :
dic[i] += 1
if dic[i] == len(nums)/2 :
return i
else :
dic[i] = 1 | n-repeated-element-in-size-2n-array | PYTHON 3 : SUPER EASY 99.52% FASTER | rohitkhairnar | 11 | 510 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,546 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1209477/Python-Explained-Simple-one-liner-Counter | class Solution(object):
def repeatedNTimes(self, nums):
return Counter(nums).most_common(1)[0][0] | n-repeated-element-in-size-2n-array | [Python Explained] Simple one-liner Counter | akashadhikari | 2 | 81 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,547 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1182101/python-or-faster-than-97.20 | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
d = {}
for i in A:
if i not in d:
d[i] = 1
else:
return i | n-repeated-element-in-size-2n-array | python | faster than 97.20% | prachijpatel | 2 | 133 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,548 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1562650/Python3-one-line-solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
return (sum(nums) - sum(set(nums))) // (len(nums) // 2 - 1) | n-repeated-element-in-size-2n-array | Python3 one line solution | sirenescx | 1 | 78 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,549 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1376630/Python-3-%3A-FASTER-THAN-99.66-O(N)-TIME-COMPLEXITY | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
dic = {}
for i in nums:
if i in dic:
return i
if i not in dic:
dic[i] = 1 | n-repeated-element-in-size-2n-array | Python 3 : FASTER THAN 99.66% , O(N) TIME COMPLEXITY | iron_man_365 | 1 | 90 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,550 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2821341/Simple-One-Line-Python3 | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0] | n-repeated-element-in-size-2n-array | Simple One Line Python3 | Jlonerawesome | 0 | 3 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,551 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2809876/Easiest-Python-Solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
s = set()
for num in nums:
if num in s:
return num
s.add(num) | n-repeated-element-in-size-2n-array | Easiest Python Solution | namashin | 0 | 4 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,552 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2770013/Simple-Python-Solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for i in nums :
if nums.count(i) == len(nums)/2 :
return i | n-repeated-element-in-size-2n-array | Simple Python Solution | dnvavinash | 0 | 4 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,553 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2711402/3-lines-Python3-SolutionororO(n) | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for i in nums:
if nums.count(i)!=1:
return i | n-repeated-element-in-size-2n-array | 3 lines Python3 Solution||O(n) | sowmika_chaluvadi | 0 | 6 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,554 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2659808/Easy-to-Understand-or-Beginner's-Friendly-or-Python | class Solution(object):
def repeatedNTimes(self, nums):
nums.sort()
n = len(nums) // 2
if nums[n + 1] == nums[n]: return nums[n]
return nums[n - 1] | n-repeated-element-in-size-2n-array | Easy to Understand | Beginner's Friendly | Python | its_krish_here | 0 | 8 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,555 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2619751/O(1)-space-python3 | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
n =len(nums)
for i in range(2,n):
if nums[i]==nums[i-1] or nums[i]==nums[i-2]:
return nums[i]
return nums[0] | n-repeated-element-in-size-2n-array | O(1) space python3 | abhayCodes | 0 | 14 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,556 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2619698/return-first-element-to-occur-2-times-python | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
s=set()
for i in nums:
if i in s:
return i
s.add(i) | n-repeated-element-in-size-2n-array | return first element to occur 2 times python | abhayCodes | 0 | 7 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,557 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2466512/Python-solution-using-dictionary | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
num_dict = {}
for i in nums:
if i in num_dict:
num_dict[i] += 1
else:
num_dict[i] = 1
for k, v in num_dict.items():
if v > 1:
return k | n-repeated-element-in-size-2n-array | Python solution using dictionary | samanehghafouri | 0 | 10 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,558 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2414318/Python3-Simple-Set-Solution-beats-95 | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num) | n-repeated-element-in-size-2n-array | [Python3] Simple Set Solution, beats 95% | ivnvalex | 0 | 39 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,559 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2328821/Simple-Python3-Solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
unique = len(set(nums))
cnt = Counter(nums)
for k, v in cnt.items():
if v == unique - 1:
return k | n-repeated-element-in-size-2n-array | Simple Python3 Solution | vem5688 | 0 | 26 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,560 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2309975/My-Solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for element in nums:
if nums.count(element) == len(nums) // 2:
return element | n-repeated-element-in-size-2n-array | My Solution ๐ | ibrahimbayburtlu5 | 0 | 7 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,561 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2181996/Simple-Logic | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
freq = Counter(nums)
return freq.most_common(1)[0][0] | n-repeated-element-in-size-2n-array | Simple Logic | writemeom | 0 | 42 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,562 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/2095052/PYTHON-or-Simple-python-solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
hashMap = {}
for i in nums:
hashMap[i] = 1 + hashMap.get(i, 0)
n = len(nums) // 2
for i in hashMap:
if hashMap[i] == n:
return i | n-repeated-element-in-size-2n-array | PYTHON | Simple python solution | shreeruparel | 0 | 50 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,563 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1928296/easy-python-code | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
x = {}
for i in nums:
if i in x:
return i
else:
x[i] = 0 | n-repeated-element-in-size-2n-array | easy python code | dakash682 | 0 | 32 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,564 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1882796/easy-simple-python-solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
n = len(nums)//2
d={}
for num in nums:
if num in d:
d[num]+=1
else:
d[num]=1
for key in d:
if d[key] == n :
return key | n-repeated-element-in-size-2n-array | easy simple python solution | Buyanjargal | 0 | 35 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,565 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1807550/1-Line-Python-Solution-oror-80-Faster-oror-Memory-less-than-75 | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
return Counter(nums).most_common(1)[0][0] | n-repeated-element-in-size-2n-array | 1-Line Python Solution || 80% Faster || Memory less than 75% | Taha-C | 0 | 46 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,566 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1805255/Python-Easy-to-Understand-Hashmap | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
dic = {}
for n in nums:
if n in dic:
dic[n]+=1
else:
dic[n]=1
for k in dic:
# print(f'Ans is {k} -> {dic[k]}') k -> d[k] # 1->1,2->1,3->2 # {1:1,2:1,3:2}
if dic[k] == len(nums)//2:
return k | n-repeated-element-in-size-2n-array | Python Easy to Understand [Hashmap] | Ron99 | 0 | 37 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,567 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1725426/(JavaScript%2BPython3)-solution-using-Frequency-counter | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
dic = dict()
for item in nums:
if dic.get(item):
dic[item] += 1
else:
dic[item] = 1
items = dic.items()
ab = sorted(dic.items(), key=lambda x: x[1], reverse=True)
return ab[0][0] | n-repeated-element-in-size-2n-array | (JavaScript+Python3) solution using - Frequency-counter | shakilbabu | 0 | 28 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,568 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1491902/Python-dollarolution-(95-Faster) | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
for i in range(len(nums)):
if nums[i] in nums[i+1:]:
return nums[i] | n-repeated-element-in-size-2n-array | Python $olution (95% Faster) | AakRay | 0 | 87 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,569 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1476997/Python-O(n)-time-O(1)-space-solution | class Solution:
def repeatedNTimes(self, nums: List[int]) -> int:
n = len(nums)
if n == 4:
return sum(nums)-sum(list(set(nums)))
for i in range(n-2):
a, b, c = nums[i], nums[i+1], nums[i+2]
if a== b or b ==c or c ==a:
return a+b+c-max(a,b,c)-min(a,b,c) | n-repeated-element-in-size-2n-array | Python O(n) time, O(1) space solution | byuns9334 | 0 | 62 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,570 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1082166/ONE-LINER-PYTHON-CODE | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
return ([a for a,c in Counter(A).items() if c==len(A)//2][0]) | n-repeated-element-in-size-2n-array | ONE LINER PYTHON CODE | yashwanthreddz | 0 | 47 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,571 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1030407/Python3-easy-solution | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
d = {}
for i in A:
d[i] = d.get(i,0)+1
return list(d.keys())[list(d.values()).index(len(A)//2)] | n-repeated-element-in-size-2n-array | Python3 easy solution | EklavyaJoshi | 0 | 75 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,572 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/985049/O(1)-Space-and-O(n)-time-solution | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
a,b = A[0], A[1]
for i in range(2,len(A)):
if A[i]==a or A[i]==b:
return A[i]
else:
a = b
b = A[i]
return b | n-repeated-element-in-size-2n-array | O(1) Space and O(n) time solution | majinlion | 0 | 81 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,573 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/679849/Python-Easy-to-Understand | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
l=[]
A.sort()
for i in A:
if i not in l:
l.append(i)
else:
return i | n-repeated-element-in-size-2n-array | Python Easy to Understand | sulabh98 | 0 | 42 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,574 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/580070/Python-One-Liner-(Slow) | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
return max(collections.Counter(A),key = collections.Counter(A).get) | n-repeated-element-in-size-2n-array | Python One Liner (Slow) | pratushah | 0 | 89 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,575 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/382179/Three-Solutions-in-Python-3 | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
return (lambda x: max(x, key = lambda y: x[y]))(collections.Counter(A)) | n-repeated-element-in-size-2n-array | Three Solutions in Python 3 | junaidmansuri | 0 | 365 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,576 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/382179/Three-Solutions-in-Python-3 | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
S = set()
for a in A:
if a in S: return a
else: S.add(a) | n-repeated-element-in-size-2n-array | Three Solutions in Python 3 | junaidmansuri | 0 | 365 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,577 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/382179/Three-Solutions-in-Python-3 | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
for a in set(A):
if A.count(a) != 1: return a
- Junaid Mansuri
(LeetCode ID)@hotmail.com | n-repeated-element-in-size-2n-array | Three Solutions in Python 3 | junaidmansuri | 0 | 365 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,578 |
https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/318920/Easy-way-by-python | class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
length = len(A)
for i in A:
if A.count(i)>1:
return i | n-repeated-element-in-size-2n-array | Easy way by python | PPdog520 | 0 | 68 | n repeated element in size 2n array | 961 | 0.759 | Easy | 15,579 |
https://leetcode.com/problems/maximum-width-ramp/discuss/977244/Python3-binary-search-O(NlogN)-and-stack-O(N) | class Solution:
def maxWidthRamp(self, A: List[int]) -> int:
ans = 0
stack = []
for i in range(len(A)):
if not stack or A[stack[-1]] > A[i]: stack.append(i)
else:
lo, hi = 0, len(stack)
while lo < hi:
mid = lo + hi >> 1
if A[stack[mid]] <= A[i]: hi = mid
else: lo = mid + 1
ans = max(ans, i - stack[lo])
return ans | maximum-width-ramp | [Python3] binary search O(NlogN) & stack O(N) | ye15 | 8 | 299 | maximum width ramp | 962 | 0.49 | Medium | 15,580 |
https://leetcode.com/problems/maximum-width-ramp/discuss/977244/Python3-binary-search-O(NlogN)-and-stack-O(N) | class Solution:
def maxWidthRamp(self, A: List[int]) -> int:
ans = 0
stack = []
for i in range(len(A)):
if not stack or A[stack[-1]] > A[i]: stack.append(i)
for i in reversed(range(len(A))):
while stack and A[stack[-1]] <= A[i]:
ans = max(ans, i - stack.pop())
return ans | maximum-width-ramp | [Python3] binary search O(NlogN) & stack O(N) | ye15 | 8 | 299 | maximum width ramp | 962 | 0.49 | Medium | 15,581 |
https://leetcode.com/problems/maximum-width-ramp/discuss/1938716/Python-easy-to-read-and-understand-or-stack | class Solution:
def maxWidthRamp(self, nums: List[int]) -> int:
stack = []
n = len(nums)
for i in range(n):
if not stack or nums[stack[-1]] > nums[i]:
stack.append(i)
ans = 0
for i in range(n-1, -1, -1):
while stack and nums[i] >= nums[stack[-1]]:
idx = stack.pop()
ans = max(ans, i-idx)
return ans | maximum-width-ramp | Python easy to read and understand | stack | sanial2001 | 2 | 183 | maximum width ramp | 962 | 0.49 | Medium | 15,582 |
https://leetcode.com/problems/maximum-width-ramp/discuss/1592965/Simple-and-Readable%3A-O(N)-Time-O(N)-Space | class Solution:
def maxWidthRamp(self, nums: List[int]) -> int:
if not nums: return 0
max_vals = self.create_max_vals(nums)
max_width = 0
i = 0
while i + max_width < len(nums):
j = i + max_width
while j < len(nums) and nums[i] <= max_vals[j]:
j += 1
max_width = max(max_width, j - i - 1)
i += 1
return max_width
def create_max_vals(self, nums: List[int]) -> List[int]:
max_val = 0
max_vals = [0] * len(nums)
for i in range(len(nums)-1, -1, -1):
max_val = max(max_val, nums[i])
max_vals[i] = max_val
return max_vals | maximum-width-ramp | Simple and Readable: O(N) Time, O(N) Space | owenc343 | 0 | 243 | maximum width ramp | 962 | 0.49 | Medium | 15,583 |
https://leetcode.com/problems/minimum-area-rectangle-ii/discuss/980956/Python3-center-point-O(N2) | class Solution:
def minAreaFreeRect(self, points: List[List[int]]) -> float:
ans = inf
seen = {}
for i, (x0, y0) in enumerate(points):
for x1, y1 in points[i+1:]:
cx = (x0 + x1)/2
cy = (y0 + y1)/2
d2 = (x0 - x1)**2 + (y0 - y1)**2
for xx, yy in seen.get((cx, cy, d2), []):
area = sqrt(((x0-xx)**2 + (y0-yy)**2) * ((x1-xx)**2 + (y1-yy)**2))
ans = min(ans, area)
seen.setdefault((cx, cy, d2), []).append((x0, y0))
return ans if ans < inf else 0 | minimum-area-rectangle-ii | [Python3] center point O(N^2) | ye15 | 28 | 1,200 | minimum area rectangle ii | 963 | 0.547 | Medium | 15,584 |
https://leetcode.com/problems/minimum-area-rectangle-ii/discuss/2340767/Runtime%3A-96-ms-faster-than-97.40-of-Python3-oror-Python-solution | class Solution:
def minAreaFreeRect(self, points: List[List[int]]) -> float:
N = len(points)
seen = set()
for point in points:
seen.add(tuple(point))
# length^2
def length2(a, b):
return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])
best = 1e30
for i in range(N):
for j in range(N):
if i == j:
continue
lij = length2(points[i], points[j])
for k in range(N):
if i == k or j == k:
continue
# given i->j line, add to k to find l
dx, dy = points[j][0] - points[i][0], points[j][1] - points[i][1]
pl = (points[k][0] + dx, points[k][1] + dy)
if pl not in seen:
continue
lik = length2(points[i], points[k])
ljk = length2(points[j], points[k])
lil = length2(points[i], pl)
ljl = length2(points[j], pl)
lkl = length2(points[k], pl)
if lij == lkl and lik == ljl and lil == ljk:
best = min(best, sqrt(lij * lik * lil) / sqrt(max(lij, lik, lil)))
if best >= 1e29:
return 0
return best | minimum-area-rectangle-ii | Runtime: 96 ms, faster than 97.40% of Python3 || Python solution | vimla_kushwaha | 1 | 82 | minimum area rectangle ii | 963 | 0.547 | Medium | 15,585 |
https://leetcode.com/problems/least-operators-to-express-number/discuss/1367268/Python3-top-down-dp | class Solution:
def leastOpsExpressTarget(self, x: int, target: int) -> int:
@cache
def fn(val):
"""Return min ops to express val."""
if val < x: return min(2*val-1, 2*(x-val))
k = int(log(val)//log(x))
ans = k + fn(val - x**k)
if x**(k+1) < 2*val:
ans = min(ans, k + 1 + fn(x**(k+1) - val))
return ans
return fn(target) | least-operators-to-express-number | [Python3] top-down dp | ye15 | 4 | 277 | least operators to express number | 964 | 0.48 | Hard | 15,586 |
https://leetcode.com/problems/least-operators-to-express-number/discuss/1925389/PYTHON-SOL-oror-RECURSION-%2B-MEMOIZATION-oror-WELL-EXPLAINED-oror-APPROACH-EXPLAINED-oror-WELL-COMMENTED-oror | class Solution:
def solve(self,x,target):
if target in self.dp : return self.dp[target]
# when target == 1 we can solve just by doing x/x
if target == 1: return 1
# current value = x and operations performed = 0
cur = x
op = 0
# if cur < target : the best decision is to multiply
while cur < target:
cur *= x
op += 1
# if cur == target : we reached using minimum possible operations
if cur == target :
return op
if op == 0:
# cur is already larger than target
# x/x + make(target-1) : make 2 operations + solve(target-1)
ans = 2 + self.solve(x,target - 1)
else:
# we try to reach nearest val via multiply less than target
# and find ans for remaining i.e. target - cur/x
# here op becomes op - 1 so op - 1 + 1 becomes op
ans = op + self.solve(x,target-(cur//x))
if cur - target < target :
# diff between cur and target is less than target
# i.e. we can make cur and remove cur - target
tmp = op + 1 + self.solve(x,cur - target)
if tmp < ans : ans = tmp
# finally use dp for memoization
self.dp[target] = ans
return ans | least-operators-to-express-number | PYTHON SOL || RECURSION + MEMOIZATION || WELL EXPLAINED || APPROACH EXPLAINED || WELL COMMENTED || | reaper_27 | 1 | 88 | least operators to express number | 964 | 0.48 | Hard | 15,587 |
https://leetcode.com/problems/univalued-binary-tree/discuss/1569046/python-dfs-recursion-faster-than-97 | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
val = root.val
def helper(root):
return root is None or (root.val == val and helper(root.left) and helper(root.right))
return helper(root) | univalued-binary-tree | python dfs recursion faster than 97% | dereky4 | 2 | 89 | univalued binary tree | 965 | 0.693 | Easy | 15,588 |
https://leetcode.com/problems/univalued-binary-tree/discuss/469876/Python-3-(five-lines)-(beats-~93)-(Simple-Recursion) | class Solution:
def isUnivalTree(self, R: TreeNode) -> bool:
def IUT(n):
if n == None: return True
if n.val != R.val: return False
return IUT(n.left) and IUT(n.right)
return IUT(R)
- Junaid Mansuri
- Chicago, IL | univalued-binary-tree | Python 3 (five lines) (beats ~93%) (Simple Recursion) | junaidmansuri | 2 | 259 | univalued binary tree | 965 | 0.693 | Easy | 15,589 |
https://leetcode.com/problems/univalued-binary-tree/discuss/1600243/Python-short-recursive-solution-or-faster-than-96.1-submission | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
self.value=root.val
self.flag=True
def helper(node):
if node is None:
return True
if node.val!=self.value:
return False
flag=helper(node.left) and helper(node.right)
return flag
return helper(root) | univalued-binary-tree | Python short recursive solution | faster than 96.1% submission | diksha_choudhary | 1 | 30 | univalued binary tree | 965 | 0.693 | Easy | 15,590 |
https://leetcode.com/problems/univalued-binary-tree/discuss/1167940/WEEB-DOES-PYTHON-BFS | class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
queue, Unival = deque([root]), root.val
while queue:
curNode = queue.popleft()
if curNode.val != Unival: return False
if curNode.left:
queue.append(curNode.left)
if curNode.right:
queue.append(curNode.right)
return True | univalued-binary-tree | WEEB DOES PYTHON BFS | Skywalker5423 | 1 | 48 | univalued binary tree | 965 | 0.693 | Easy | 15,591 |
https://leetcode.com/problems/univalued-binary-tree/discuss/2823623/Faster-than-98-python-solution | class Solution:
def isUnivalTree(self, root) -> bool:
x=root.val
q=[root]
while q:
node=q.pop(0)
if node.val!=x:
return False
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return True | univalued-binary-tree | Faster than 98% python solution | sushants007 | 0 | 3 | univalued binary tree | 965 | 0.693 | Easy | 15,592 |
https://leetcode.com/problems/univalued-binary-tree/discuss/2823623/Faster-than-98-python-solution | class Solution:
def isUnivalTree(self, root) -> bool:
if not root:
return True
if root.left:
if root.val!=root.left.val :
return False
if root.right:
if root.val!=root.right.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right) | univalued-binary-tree | Faster than 98% python solution | sushants007 | 0 | 3 | univalued binary tree | 965 | 0.693 | Easy | 15,593 |
https://leetcode.com/problems/univalued-binary-tree/discuss/2789350/Explained-recursive-Python-solution | class Solution:
def isUnivalTree(self, root, value=float('inf')):
if not(root):
return True
if value==float('inf'):
return self.isUnivalTree(root.left, root.val) and self.isUnivalTree(root.right, root.val)
else:
return root.val==value and self.isUnivalTree(root.left, root.val) and self.isUnivalTree(root.right, root.val) | univalued-binary-tree | Explained recursive Python solution | Pirmil | 0 | 1 | univalued binary tree | 965 | 0.693 | Easy | 15,594 |
https://leetcode.com/problems/univalued-binary-tree/discuss/2654035/DFS-Solution | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
i = set()
def inorderTraversal(root):
if root:
inorderTraversal(root.left)
i.add(root.val)
inorderTraversal(root.right)
inorderTraversal(root)
return True if len(i) == 1 else False | univalued-binary-tree | DFS Solution | jaisalShah | 0 | 2 | univalued binary tree | 965 | 0.693 | Easy | 15,595 |
https://leetcode.com/problems/univalued-binary-tree/discuss/2334018/Python-greater98-Time | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
uni = []
def search(root):
if root == None:
return
uni.append(root.val)
search(root.left)
search(root.right)
search(root)
return len(set(uni)) == 1 | univalued-binary-tree | Python >98% Time | tq326 | 0 | 12 | univalued binary tree | 965 | 0.693 | Easy | 15,596 |
https://leetcode.com/problems/univalued-binary-tree/discuss/2073728/Python-Easy-Solution | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
res=[]
def tree(node):
if not node: return
tree(node.left)
res.append(node.val)
tree(node.right)
tree(root)
print(res)
v=res[0]
for x in range(1,len(res)):
if v!=res[x]:
return False
return True | univalued-binary-tree | [Python] Easy Solution | Perindhavallipadem | 0 | 25 | univalued binary tree | 965 | 0.693 | Easy | 15,597 |
https://leetcode.com/problems/univalued-binary-tree/discuss/1913648/Python3-Recursion-Solution-With-Prev-Variable-No-Memory-Needed-Faster-Than-88.92 | class Solution:
def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
flag = [True]
def dfs(tree, prev):
if not tree:
return
if tree.val != prev:
flag[0] = False
dfs(tree.left, tree.val)
dfs(tree.right, tree.val)
dfs(root, root.val)
return flag[0] | univalued-binary-tree | Python3 Recursion Solution With Prev Variable, No Memory Needed, Faster Than 88.92% | Hejita | 0 | 27 | univalued binary tree | 965 | 0.693 | Easy | 15,598 |
https://leetcode.com/problems/univalued-binary-tree/discuss/1878371/Python-Simple-and-Elegant!-Recursive | class Solution(object):
def isUnivalTree(self, root):
if root.left and root.right:
return root.val == root.left.val == root.right.val and self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
elif root.left:
return root.val == root.left.val and self.isUnivalTree(root.left)
elif root.right:
return root.val == root.right.val and self.isUnivalTree(root.right)
else:
return True | univalued-binary-tree | Python - Simple and Elegant! Recursive | domthedeveloper | 0 | 58 | univalued binary tree | 965 | 0.693 | Easy | 15,599 |
Subsets and Splits
Top 2 Solutions by Upvotes
Identifies the top 2 highest upvoted Python solutions for each problem, providing insight into popular approaches.