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/orderly-queue/discuss/2784826/Python-O(n2)-solution-explained
class Solution: def orderlyQueue(self, s: str, k: int) -> str: return "".join(sorted(s)) if k > 1 else min(s[i:] + s[:i] for i in range(len(s)))
orderly-queue
Python O(n^2) solution explained
olzh06
0
6
orderly queue
899
0.665
Hard
14,600
https://leetcode.com/problems/orderly-queue/discuss/2784819/Python3-solution
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k > 1 : return "".join(sorted(s)) return min(s[i:]+s[:i] for i in range(len(s)))
orderly-queue
Python3 solution
avs-abhishek123
0
7
orderly queue
899
0.665
Hard
14,601
https://leetcode.com/problems/orderly-queue/discuss/2784749/Beats-95-Better-TC-than-official
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k > 1: return "".join(sorted(s)) else: smallest = ord('z') smallestI = [] for i, l in enumerate(s): if ord(l) == smallest: smallestI.append(i) elif ord(l) < smallest: smallest = ord(l) smallestI = [i] return min(s[index:] + s[:index] for index in smallestI)
orderly-queue
Beats 95% - Better TC than official
gaetanherry
0
8
orderly queue
899
0.665
Hard
14,602
https://leetcode.com/problems/orderly-queue/discuss/2784702/Runtime-beats-90-Solution-(with-explanation)
class Solution: def orderlyQueue(self, s: str, k: int) -> str: # case1 : 若 s 內字元全部相同,則直接 return 原本的 s 即可 if len(set(s)) == 1: return s # case2 : 若 k 不為 1,則直接 return 從最小字典排序即可(不論如何都可全數排序完成) if k != 1: return "".join(sorted(s)) # case3 : 若 k 為 1,則答案必定照原本序列的順序排列 Len = len(s) Min = "{" Min_idxs = dict() # 儲存所有最小字元 index 的字典,key = index, val = smallest char for i in range(Len): if Min > s[i]: # 若小於最小字元,則將字典重設為 {index:char},更改完的長度 == 1 Min = s[i] Min_idxs = {i:s[i]} elif Min == s[i]: # 若等於最小字元,新增鍵值對 index:char,更改完的長度 > 1 Min_idxs[i] = s[i] step = 1 # 往每個最小 index 後做比對,看誰相對來說最小 # 若字典長度等於 1 (代表已找到按字典大小排序的最小字串的起點),或是已比對完整個字串,則結束迴圈 while len(Min_idxs) != 1 and step < Len: Min = "{" for idx in Min_idxs: comp_idx = (idx+step)%Len # 若 index 超過 s 長度,則從 s[0] 繼續往後走 if Min > s[comp_idx]: # 尋找每個 index 後 step 個字元的最小字元 Min = s[comp_idx] Min_idxs[idx] = s[comp_idx] # 將每個 k,v 對的 value 更改為後面 step 個字元 # 將 value 不等於最小字元的 key 儲存起來 del_list = [k for k, v in Min_idxs.items() if v != Min] # 刪除 value 不等於最小字元的 k,v 對 for idx in del_list: Min_idxs.pop(idx) # 再往後一個 step 做比對 step += 1 split_idx = list(Min_idxs.keys())[0] # 抓取新的起點 return s[split_idx:] + s[:split_idx] # 重組字串並 return
orderly-queue
Runtime beats 90% Solution (with explanation)
child70370636
0
4
orderly queue
899
0.665
Hard
14,603
https://leetcode.com/problems/orderly-queue/discuss/2784685/Python-oror-Easy-Solution
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k == 1: lnth = len(s) ans = s while lnth > 0: s = s[-1] + s[:-1] ans = min(ans, s) lnth -= 1 return ans else: return "".join(sorted(s))
orderly-queue
Python || Easy Solution
Rahul_Kantwa
0
8
orderly queue
899
0.665
Hard
14,604
https://leetcode.com/problems/orderly-queue/discuss/2784432/Lexicographically-minimal-string-rotation-if-k-is-1-otherwise-sort-all
class Solution: def orderlyQueue(self, s: str, k: int) -> str: n = len(s) if k == 1: ss = s + s return min(ss[i:i+n] for i in range(n)) return "".join(sorted(s))
orderly-queue
Lexicographically minimal string rotation if k is 1 otherwise sort all
theabbie
0
4
orderly queue
899
0.665
Hard
14,605
https://leetcode.com/problems/orderly-queue/discuss/2784286/Prove-of-k-greater-2
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k == 1: return min((s[i: ] + s[: i] for i in range(len(s)))) return ''.join(sorted(s))
orderly-queue
Prove of k >= 2
JasonDecode
0
5
orderly queue
899
0.665
Hard
14,606
https://leetcode.com/problems/orderly-queue/discuss/2784268/94.5-Simple-Python-Solution(-9-lines-of-code-)
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k>1: return ''.join(sorted(s)) else: res = s for i in range(len(s)): res = min(res, s[i:] + s[0:i]) return res
orderly-queue
94.5% Simple Python Solution( 9 lines of code )
Erk32
0
4
orderly queue
899
0.665
Hard
14,607
https://leetcode.com/problems/orderly-queue/discuss/2784154/Python3-Brute-Force-(Hard-lol)
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k > 1: return "".join(sorted(s)) m = s c = s for i in range(len(s)-1): c = c[1:] + c[0] if c < m: m = c return m
orderly-queue
Python3 Brute Force (Hard? lol)
godshiva
0
5
orderly queue
899
0.665
Hard
14,608
https://leetcode.com/problems/orderly-queue/discuss/2784084/Python-(Faster-than-98)
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k == 1: smallest = s for i in range(1, len(s)): newS = s[i:] + s[:i] smallest = min(smallest, newS) return smallest else: return ''.join(sorted(s))
orderly-queue
Python (Faster than 98%)
KevinJM17
0
4
orderly queue
899
0.665
Hard
14,609
https://leetcode.com/problems/orderly-queue/discuss/2784046/98-beats-oror-Easy-to-understand-C%2B%2B(78.8-beats)-Java(65-beats)-Python3(98.8-beats)-code
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k==1: return min(s[i:] + s[:i] for i in range(len(s))) return "".join(sorted(s))
orderly-queue
98% beats || Easy to understand C++(78.8% beats), Java(65% beats), Python3(98.8% beats) code
harahman
0
42
orderly queue
899
0.665
Hard
14,610
https://leetcode.com/problems/orderly-queue/discuss/2783700/Extremely-easy-solution-with-explanation-sort-or-rotate-oror-Python3-oror-O(N2)
class Solution: def orderlyQueue(self, s: str, k: int) -> str: def lexicographicallySmallestRotation(s: str) -> str: min_rotation = s for i in range(len(s)): cur = s[i:] + s[:i] if cur < min_rotation: min_rotation = cur return min_rotation if k == 1: return lexicographicallySmallestRotation(s) else: return "".join(sorted(s))
orderly-queue
Extremely easy solution with explanation, sort or rotate || Python3 || O(N^2)
drevil_no1
0
2
orderly queue
899
0.665
Hard
14,611
https://leetcode.com/problems/orderly-queue/discuss/2783563/Python-Solution-or-Full-Clean-Code-One-Liner-or-Sort-Rotate-Based
class Solution: def orderlyQueue(self, s: str, k: int) -> str: # pattern for k > 1 is if k > 1: # sort the string and return it as answer return ''.join(sorted(s)) # for k = 1 case # check for each rotation, and update the min lexico string else: store = s for i in range(len(s)): s = s[k:] + s[:k] store = min(store,s) return store # one liner for above def orderlyQueue(self, s: str, k: int) -> str: return ''.join(sorted(s)) if k > 1 else min(s[pivot:] + s[:pivot] for pivot in range(len(s)))
orderly-queue
Python Solution | Full Clean Code / One Liner | Sort / Rotate Based
Gautam_ProMax
0
11
orderly queue
899
0.665
Hard
14,612
https://leetcode.com/problems/orderly-queue/discuss/2783400/python-solution-using-list-comprehension-or-only-three-line-code
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k>1: return "".join(sorted(s)) #print(s) return min([s[i:]+s[:i] for i in range(len(s))])
orderly-queue
python solution using list comprehension | only three line code
ashishneo
0
6
orderly queue
899
0.665
Hard
14,613
https://leetcode.com/problems/orderly-queue/discuss/2783128/Python-O(N-2-)-solution
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k > 1: return "".join(sorted(s)) return min([s[i:] + s[:i] for i in range(len(s))])
orderly-queue
Python O(N ^2 ), solution
Sangeeth_psk
0
4
orderly queue
899
0.665
Hard
14,614
https://leetcode.com/problems/orderly-queue/discuss/2783049/One-Liner-or-Python
class Solution: def orderlyQueue(self, s: str, k: int) -> str: return min(s[i:] + s[:i] for i in range(len(s))) if k == 1 else "".join(sorted(s))
orderly-queue
One Liner | Python
RajatGanguly
0
10
orderly queue
899
0.665
Hard
14,615
https://leetcode.com/problems/orderly-queue/discuss/2782916/Python-easy-solution-or-One-liner
class Solution: def orderlyQueue(self, s: str, k: int) -> str: return min(s[i:]+s[:i] for i in range(len(s))) if k==1 else ''.join(sorted(s))
orderly-queue
Python easy solution | One liner
praknew01
0
14
orderly queue
899
0.665
Hard
14,616
https://leetcode.com/problems/orderly-queue/discuss/2782848/Python3-Very-easy-Solution
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k>1: return "".join(sorted(s)) return min(s[i:]+s[:i] for i in range(len(s)))
orderly-queue
Python3 Very easy Solution
Motaharozzaman1996
0
18
orderly queue
899
0.665
Hard
14,617
https://leetcode.com/problems/orderly-queue/discuss/2782840/Python3-easy-approach
class Solution: def orderlyQueue(self, s: str, k: int) -> str: if k==0: return s elif k>1: return "".join(sorted(s)) else: ans = s for i in range(len(s)): s = s[k:]+s[:k] #since k==1 we can replace k with 1 ans = min(ans,s) # print(ans) return ans
orderly-queue
Python3 easy approach
shashank732001
0
27
orderly queue
899
0.665
Hard
14,618
https://leetcode.com/problems/orderly-queue/discuss/2782802/Python-3-Solution
class Solution: def calcS(self,s): res = 0 for x in s: res *= 26 res += (ord(x)-96) return res def orderlyQueue(self, s: str, k: int) -> str: if k == 1: least = inf indx = 0 ss = s*2 d = len(s) for l in range(d): if least>self.calcS(ss[l:l+d]): least = self.calcS(ss[l:l+d]) indx = l return ss[indx:indx+d] else: D = defaultdict(int) for x in s: D[x] += 1 abc = "abcdefghijklmnopqrstuvwxyz" res = "" for x in abc: res += x*D[x] return res
orderly-queue
Python 3 Solution
mati44
0
15
orderly queue
899
0.665
Hard
14,619
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1633530/Python3-NOT-BEGINNER-FRIENDLY-Explained
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: digits = set(int(d) for d in digits) dLen = len(digits) nStr = str(n) nLen = len(nStr) res = sum(dLen**i for i in range(1, nLen)) # lower dimensions def helper(firstDigit, slots): if slots == 1: return sum(d <= firstDigit for d in digits) return sum(d < firstDigit for d in digits) * dLen**(slots - 1) for i in range(nLen): curDigit = int(nStr[i]) res += helper(curDigit, nLen - i) if not curDigit in digits: # makes no sense to continue break return res
numbers-at-most-n-given-digit-set
✔️ [Python3] NOT BEGINNER FRIENDLY, Explained
artod
8
364
numbers at most n given digit set
902
0.414
Hard
14,620
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1547664/Python3-dp
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: s = str(n) prev = 1 for i, ch in enumerate(reversed(s)): k = bisect_left(digits, ch) ans = k*len(digits)**i if k < len(digits) and digits[k] == ch: ans += prev prev = ans return ans + sum(len(digits)**i for i in range(1, len(s)))
numbers-at-most-n-given-digit-set
[Python3] dp
ye15
3
80
numbers at most n given digit set
902
0.414
Hard
14,621
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1547664/Python3-dp
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: s = str(n) ans = sum(len(digits) ** i for i in range(1, len(s))) for i in range(len(s)): ans += sum(c < s[i] for c in digits) * (len(digits) ** (len(s) - i - 1)) if s[i] not in digits: return ans return ans + 1
numbers-at-most-n-given-digit-set
[Python3] dp
ye15
3
80
numbers at most n given digit set
902
0.414
Hard
14,622
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1393003/Python-3-or-O(logn)
class Solution: def less_digits_than_n (self, digits, n): cnt = 0 for i in range (1, len(str(n))): cnt += len(digits)** i return cnt def same_digits_than_n (self, digits, n): s = str(n) cnt = 0 for i in range (len(s)): valid_digits_counter = 0 for d in digits: if d < s[i]: valid_digits_counter+=1 cnt+= valid_digits_counter * (len(digits)**(len(s)-i-1)) if s[i] not in digits: break cnt+=1 if i==len(s)-1 else 0 return cnt def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: return self.less_digits_than_n(digits, n) + self.same_digits_than_n(digits,n)
numbers-at-most-n-given-digit-set
Python 3 | O(logn)
shirshrem
2
172
numbers at most n given digit set
902
0.414
Hard
14,623
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1634293/Python3-one-liner
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: return sum((len(digits)**p) for p in range(1,len(str(n)))) + sum(sum(1 for digit in set(digits) if digit < d )*(len(digits)**(len(str(n))-i-1)) for i,(d,_) in enumerate(itertools.takewhile(lambda a:a[1] in set(digits) ,zip(str(n),digits[0]+str(n))))) + (1 if all(d in digits for d in str(n)) else 0)
numbers-at-most-n-given-digit-set
Python3 one-liner
pknoe3lh
1
32
numbers at most n given digit set
902
0.414
Hard
14,624
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1635628/Python-Digit-DP-Solution-with-Explanation-28ms
class Solution(): def atMostNGivenDigitSet(self, digits, n): cache = {} target = str(n) def helper(idx, isBoundary, isZero): if idx == len(target): return 1 if (idx, isBoundary, isZero) in cache: return cache[(idx, isBoundary, isZero)] res = 0 if isZero and idx != len(target)-1: res+= helper(idx+1, False, True) for digit in digits: if isBoundary and int(digit) > int(target[idx]): continue res+= helper(idx+1, True if isBoundary and digit == target[idx] else False, False) cache[(idx, isBoundary, isZero)] = res return res return helper(0, True, True)
numbers-at-most-n-given-digit-set
[Python] Digit DP Solution with Explanation, 28ms
Saksham003
0
68
numbers at most n given digit set
902
0.414
Hard
14,625
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1634597/Python3-Beats-100-or-O(1)-Space-or-No-string-conversion
class Solution: def _len(self, n): length = 0 while n: n //= 10 length += 1 return length def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: for i, d in enumerate(digits): digits[i] = int(d) lenN = self._len(n) ans = 1 power = 1 powerSum = -1 for i in range(lenN - 1, -1, -1): curDigit = n % 10 n //= 10 sep = bisect_left(digits, curDigit) ans = sep * power + (ans if sep < len(digits) and digits[sep] == curDigit else 0) powerSum += power power *= len(digits) return ans + powerSum
numbers-at-most-n-given-digit-set
[Python3] Beats 100% | O(1) Space | No string conversion
PatrickOweijane
0
64
numbers at most n given digit set
902
0.414
Hard
14,626
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1634466/Python-Solution-oror-O(log(N))-Time-O(1)-Space-oror-greater-99-Solution
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: num = list(str(n)) N = len(num) #print(num) #print(digits) tsum = 0 if len(digits) > 1: tsum = len(digits)*(len(digits)**(N-1) - 1)//(len(digits)-1) else: tsum = N-1 #print(" numbers smaller than 10*(N-1)",tsum) i =0 while i < N: count = 0 equals = False for digit in digits: if digit > num[i]: break if digit == num[i]: equals = True if i == N-1: count+=1 break count += 1 tsum += count*(len(digits)**(N-1-i)) if equals: i+=1 continue break return tsum
numbers-at-most-n-given-digit-set
Python Solution || O(log(N)) Time ; O(1) Space || > 99 % Solution
henriducard
0
42
numbers at most n given digit set
902
0.414
Hard
14,627
https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1634331/Python3-Digit-DP-solution
class Solution: def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int: limit = str(n) limit_len = len(limit) digits_len = len(digits) res = 0 for idx in range(1, limit_len): res += pow(digits_len, idx) for idx in range(limit_len): is_start_eq_digit = False for digit in digits: if digit < limit[idx]: res += pow(digits_len, limit_len - idx - 1) elif digit == limit[idx]: is_start_eq_digit = True if not is_start_eq_digit: return res return res + 1
numbers-at-most-n-given-digit-set
[Python3] Digit DP solution
maosipov11
0
37
numbers at most n given digit set
902
0.414
Hard
14,628
https://leetcode.com/problems/valid-permutations-for-di-sequence/discuss/1261833/Python3-top-down-dp
class Solution: def numPermsDISequence(self, s: str) -> int: @cache def fn(i, x): """Return number of valid permutation given x numbers smaller than previous one.""" if i == len(s): return 1 if s[i] == "D": if x == 0: return 0 # cannot decrease return fn(i, x-1) + fn(i+1, x-1) else: if x == len(s)-i: return 0 # cannot increase return fn(i, x+1) + fn(i+1, x) return sum(fn(0, x) for x in range(len(s)+1)) % 1_000_000_007
valid-permutations-for-di-sequence
[Python3] top-down dp
ye15
1
350
valid permutations for di sequence
903
0.577
Hard
14,629
https://leetcode.com/problems/valid-permutations-for-di-sequence/discuss/2649709/DP-Solution
class Solution: def numPermsDISequence(self, s: str) -> int: mem=defaultdict(int) def dfs(i,val=0): if i==len(s): return 1 if (i,val) in mem: return mem[i,val] p=0 if s[i]=="D": for ind in range(0,val+1): p+=dfs(i+1,ind)%(10**9+7) else: for ind in range(val+1,i+2): p+=dfs(i+1,ind)%(10**9+7) mem[i,val]=p return p return dfs(0)
valid-permutations-for-di-sequence
DP Solution
Garima1501
0
19
valid permutations for di sequence
903
0.577
Hard
14,630
https://leetcode.com/problems/valid-permutations-for-di-sequence/discuss/2352796/python3-solution
class Solution: def numPermsDISequence(self, s: str) -> int: myStore = [1] for index, val in enumerate(s): if val == 0: continue temp = [] for i in range(index + 2): if val == "I": curr = sum(myStore[i:]) else: curr = sum(myStore[:i]) temp.append(curr) myStore = temp return sum(myStore) % (10**9+7)
valid-permutations-for-di-sequence
python3 solution
syji
0
94
valid permutations for di sequence
903
0.577
Hard
14,631
https://leetcode.com/problems/fruit-into-baskets/discuss/1414545/Python-clean-%2B-easy-to-understand-or-Sliding-Window-O(N)
class Solution: def totalFruit(self, fruits: List[int]) -> int: fruit_types = Counter() distinct = 0 max_fruits = 0 left = right = 0 while right < len(fruits): # check if it is a new fruit, and update the counter if fruit_types[fruits[right]] == 0: distinct += 1 fruit_types[fruits[right]] += 1 # too many different fruits, so start shrinking window while distinct > 2: fruit_types[fruits[left]] -= 1 if fruit_types[fruits[left]] == 0: distinct -= 1 left += 1 # set max_fruits to the max window size max_fruits = max(max_fruits, right-left+1) right += 1 return max_fruits
fruit-into-baskets
Python - clean + easy to understand | Sliding Window O(N)
afm2
26
1,900
fruit into baskets
904
0.426
Medium
14,632
https://leetcode.com/problems/fruit-into-baskets/discuss/1300605/Python3-easy-to-understand-On
class Solution: def totalFruit(self, fruits: List[int]) -> int: start =0 end = 0 d = {} max_val = 0 while end < len(fruits): d[fruits[end]] = end if len(d) >=3: min_val = min(d.values()) del d[fruits[min_val]] start = min_val +1 max_val = max(max_val,end -start +1) end += 1 return max_val
fruit-into-baskets
Python3 easy to understand , On
moonchild_1
10
545
fruit into baskets
904
0.426
Medium
14,633
https://leetcode.com/problems/fruit-into-baskets/discuss/484921/Python-Solution-O(n)
class Solution: def totalFruit(self, tree: List[int]) -> int: tracker = collections.defaultdict(int) start = result = 0 for end in range(len(tree)): tracker[tree[end]] += 1 while len(tracker) > 2: tracker[tree[start]] -= 1 if tracker[tree[start]] == 0: del tracker[tree[start]] start += 1 result = max(result, end - start + 1) return result
fruit-into-baskets
Python Solution - O(n)
mmbhatk
6
919
fruit into baskets
904
0.426
Medium
14,634
https://leetcode.com/problems/fruit-into-baskets/discuss/2779001/Python-keeping-track-of-left-pointer-(with-detailed-comments)
class Solution: def totalFruit(self, fr: list[int]) -> int: l = i = 0 # [1] left and intermediate indices m = 0 # [2] max interval length bs = [-1,-1] # [3] fruit counts in the basket for r in range(len(fr)): # [4] move right end if fr[r] != bs[1]: # [5] when encountered a different fruit if fr[r] != bs[0]: l = i # - update left end for the new earliest type i = r # - update index of the first entrance of this type bs[0], bs[1] = bs[1], fr[r] # - update earliest/latest pair in the basket m = max(m, r - l + 1) # [6] compute length of current interval return m
fruit-into-baskets
✅ [Python] keeping track of left pointer (with detailed comments)
stanislav-iablokov
4
138
fruit into baskets
904
0.426
Medium
14,635
https://leetcode.com/problems/fruit-into-baskets/discuss/2628455/Python-Clean-%2B-Drawing-or-Sliding-Window-O(N)
class Solution: def totalFruit(self, fruits: List[int]) -> int: if len(fruits) < 2: return 1 MAX = 0 basket = defaultdict(int) l = 0 for r in range(len(fruits)): basket[fruits[r]] += 1 while len(basket) > 2: basket[fruits[l]] -= 1 if basket[fruits[l]] == 0: basket.pop(fruits[l]) l += 1 MAX = max(MAX, r - l + 1) return MAX
fruit-into-baskets
[Python] Clean + Drawing | Sliding Window O(N)
codingCBC
4
287
fruit into baskets
904
0.426
Medium
14,636
https://leetcode.com/problems/fruit-into-baskets/discuss/2754161/Python-Solution-with-both-brute-force-and-optimized-solution-with-explanation
# class Solution: # # Time : O(n^2) | Space : O(1) # def totalFruit(self, fruits: List[int]) -> int: # max_trees = 0 # for i in range(len(fruits)): # num_fruits = {} # fruit_types = 0 # for j in range(i, len(fruits), 1): # if fruits[j] not in num_fruits: # fruit_types += 1 # if fruit_types > 2: # break # num_fruits[fruits[j]] = 1 # else: # num_fruits[fruits[j]] += 1 # count = 0 # for _, v in num_fruits.items(): # count += v # max_trees = max(count, max_trees) # return max_trees class Solution: # Time : O(n) | Space : O(1) def totalFruit(self, fruits: List[int]) -> int: start = 0 end = 0 max_len = 0 fruits_type = {} while end < len(fruits): fruits_type[fruits[end]] = end # storing the index of the fruit if len(fruits_type) >= 3: # need to pop the fruit with the minimum index min_idx = min(fruits_type.values()) del fruits_type[fruits[min_idx]] # update the new shart start = min_idx + 1 max_len = max(max_len, end - start + 1) end += 1 return max_len
fruit-into-baskets
Python Solution with both brute force and optimized solution with explanation
SuvroBaner
1
23
fruit into baskets
904
0.426
Medium
14,637
https://leetcode.com/problems/fruit-into-baskets/discuss/2342976/Python3-Sliding-window-with-Budget
class Solution: def totalFruit(self, nums: List[int]) -> int: """ This problem asks us to find the maximum length of a subarray, which has maximum 2 unique numbers. I changed the input "fruit -> nums" for easy typing. """ #Define the budget k we can spend k = 2 left = 0 hashmap = {} for right in range(len(nums)): # when we meet a new unique number, # add it to the hashmap and lower the budget if nums[right] not in hashmap: k -= 1 hashmap[nums[right]] = 1 # when we meet a number in our window elif nums[right] in hashmap: hashmap[nums[right]] += 1 # when we exceed our budget if k < 0: # when we meet a number that can help us to save the budget if hashmap[nums[left]] == 1: del hashmap[nums[left]] k += 1 # otherwise we just reduce the freq else: hashmap[nums[left]] -= 1 left += 1 """ We never shrink our window, we just expand the window when it satisfies the condition So, finally the window size is the maximum """ return right - left + 1
fruit-into-baskets
Python3 Sliding window with Budget
_Newbie_007
1
161
fruit into baskets
904
0.426
Medium
14,638
https://leetcode.com/problems/fruit-into-baskets/discuss/2191167/Sliding-Window-oror-Implementation-of-Approach-explained-by-Aditya-Verma
class Solution: def totalFruit(self, fruits: List[int]) -> int: i, j, n = 0, 0, len(fruits) maxFruitsLength = n + 1 frequencyDict = {} d = Counter(fruits) if len(d) == 1: return list(d.values())[0] mapSize = 0 maxSize = float('-inf') while j < n: frequencyDict[fruits[j]] = frequencyDict.get(fruits[j], 0) + 1 if len(frequencyDict) < 2: j += 1 elif len(frequencyDict) == 2: maxSize = max(maxSize, j - i + 1) j += 1 else: while len(frequencyDict) > 2: frequencyDict[fruits[i]] -= 1 if frequencyDict[fruits[i]] == 0: del frequencyDict[fruits[i]] i += 1 j += 1 return maxSize
fruit-into-baskets
Sliding Window || Implementation of Approach explained by Aditya Verma
Vaibhav7860
1
119
fruit into baskets
904
0.426
Medium
14,639
https://leetcode.com/problems/fruit-into-baskets/discuss/2178808/Python3-O(n)-oror-O(1)-Runtime%3A-1375ms-42.45-memory%3A-20.1mb-88.07
class Solution: # O(n) || O(1) # Runtime: 1375ms 42.45%; memory: 20.1mb 88.07% def totalFruit(self, fruits: List[int]) -> int: prevFruit, secondLastFruit = -1, -1 lastFruitCount = 0 currMax = 0 maxVal = 0 for fruit in fruits: if fruit == prevFruit or fruit == secondLastFruit: currMax += 1 else: currMax = lastFruitCount + 1 if fruit == prevFruit: lastFruitCount += 1 else: lastFruitCount = 1 if fruit != prevFruit: secondLastFruit = prevFruit prevFruit = fruit maxVal = max(maxVal, currMax) return maxVal
fruit-into-baskets
Python3 O(n) || O(1) # Runtime: 1375ms 42.45%; memory: 20.1mb 88.07%
arshergon
1
79
fruit into baskets
904
0.426
Medium
14,640
https://leetcode.com/problems/fruit-into-baskets/discuss/1708337/Python3-Simple-code-with-complete-explanation-(Faster-than-99.74-and-O(1)-space)
class Solution: def totalFruit(self, fruits: List[int]) -> int: num1 = fruits[0] num2 = 0 p1 = 0 p2 = -1 max_f = 0 c = 0 for i in range(len(fruits)): if fruits[i]==num1: c += 1 elif fruits[i]==num2: temp = num1 num1 = num2 num2 = temp p2 = p1 p1 = i c += 1 else: if c>max_f: max_f = c p2 = p1 p1 = i num2 = num1 num1 = fruits[i] c = i-p2+1 if c>max_f: max_f = c return max_f
fruit-into-baskets
[Python3] Simple code with complete explanation (Faster than 99.74% and O(1) space)
ruphan_s
1
131
fruit into baskets
904
0.426
Medium
14,641
https://leetcode.com/problems/fruit-into-baskets/discuss/2847532/Python3-Clean-and-Commented-Solution
class Solution: def totalFruit(self, fruits: List[int]) -> int: # go through the fruits and keep a set max_size = 0 baskets = collections.Counter() left_pointer = 0 for idx, fruit in enumerate(fruits): # add the current fruit to the set baskets[fruit] += 1 # reduce until the counter has no more while len(baskets) > 2: baskets[fruits[left_pointer]] -= 1 if baskets[fruits[left_pointer]] == 0: del baskets[fruits[left_pointer]] left_pointer += 1 # check the amount of fruits we found max_size = max(max_size, sum(baskets.values())) return max_size
fruit-into-baskets
[Python3] - Clean and Commented Solution
Lucew
0
1
fruit into baskets
904
0.426
Medium
14,642
https://leetcode.com/problems/fruit-into-baskets/discuss/2788723/Run-length-encoding
class Solution: def totalFruit(self, fruits: List[int]) -> int:different one, and start from there run_length_encoded = [[fruits[0], 1]] for fruit in fruits[1:]: if fruit == run_length_encoded[-1][0]: run_length_encoded[-1][1] += 1 else: run_length_encoded.append([fruit, 1]) max_fruit = run_length_encoded[0][1] len_length = len(run_length_encoded) i = 0 while i < len_length - 1: fruit_sum = run_length_encoded[i][1] + run_length_encoded[i+1][1] first_fruit = run_length_encoded[i][0] second_fruit = run_length_encoded[i+1][0] j = i + 2 while j < len_length: next_fruit = run_length_encoded[j][0] if next_fruit in [first_fruit, second_fruit]: fruit_sum += run_length_encoded[j][1] j += 1 i += 1 else: break i += 1 max_fruit = max(max_fruit, fruit_sum) return max_fruit
fruit-into-baskets
Run length encoding
chronologisch
0
1
fruit into baskets
904
0.426
Medium
14,643
https://leetcode.com/problems/fruit-into-baskets/discuss/2648506/python-solution-using-dictionary-and-sliding-window
class Solution: def totalFruit(self, fruits: List[int]) -> int: start, end = 0, 0 table = dict() longest = 0 for end in range(len(fruits)): newfruit = fruits[end] if newfruit in table.keys(): table[newfruit]+=1 else: table[newfruit]=1 while len(table)>2: startfruit = fruits[start] start += 1 table[startfruit]-=1 if table[startfruit] == 0: table.pop(startfruit) if end-start+1>longest: longest= end-start+1 return longest
fruit-into-baskets
python solution using dictionary and sliding window
123014041
0
4
fruit into baskets
904
0.426
Medium
14,644
https://leetcode.com/problems/fruit-into-baskets/discuss/2572779/Python-Sliding-Window-solution
class Solution: def totalFruit(self, fruits: List[int]) -> int: left = 0 ans = float('-inf') baskets = {} ''' Intuition behind this problem is to mantain a dict, dict has to have only two values i.e the no. of baskets we are provided, linearly scanning we can get fruit of different type, we check if at any time we have 2 type of fruits, if not we contract the sliding window till type of fruits is just 1, else we expand the window and find the maximum subarray ''' for right in range(len(fruits)): if len(baskets) < 2: if fruits[right] not in baskets: baskets[fruits[right]] = 1 else: baskets[fruits[right]] += 1 elif len(baskets) == 2: if fruits[right] in baskets: baskets[fruits[right]] += 1 else: while len(baskets) != 1: if baskets[fruits[left]] == 1: del baskets[fruits[left]] else: baskets[fruits[left]] -= 1 left += 1 baskets[fruits[right]] = 1 ans = max(right-left+1, ans) return ans
fruit-into-baskets
Python Sliding Window solution
DietCoke777
0
38
fruit into baskets
904
0.426
Medium
14,645
https://leetcode.com/problems/fruit-into-baskets/discuss/2551847/Python-or-Sliding-Window-or-Easy-to-Understand
class Solution: def totalFruit(self, fruits: List[int]) -> int: max_num = 0 left = 0 counter = Counter() for right in range(len(fruits)): counter[fruits[right]] += 1 while len(counter) > 2: counter[fruits[left]] -= 1 if counter[fruits[left]] == 0: del counter[fruits[left]] left += 1 max_num = max(max_num, right-left+1) return max_num
fruit-into-baskets
Python | Sliding Window | Easy to Understand
Mikey98
0
68
fruit into baskets
904
0.426
Medium
14,646
https://leetcode.com/problems/fruit-into-baskets/discuss/2402955/Python3-or-Sliding-Window-or-O(N)-Space-and-Time
class Solution: def totalFruit(self, fruits: List[int]) -> int: freq=defaultdict(int) dq=deque() types,l=0,0 for i in range(len(fruits)): if not freq[fruits[i]]: types+=1 freq[fruits[i]]+=1 dq.append(i) while dq and types>2: ind=dq.popleft() freq[fruits[ind]]-=1 if freq[fruits[ind]]==0: types-=1 break l=max(l,len(dq)) return l
fruit-into-baskets
[Python3] | Sliding Window | O(N) Space & Time
swapnilsingh421
0
87
fruit into baskets
904
0.426
Medium
14,647
https://leetcode.com/problems/fruit-into-baskets/discuss/2394764/Python-Solution-O(n)-with-explanations-99-TC-and-98-SC
class Solution: def totalFruit(self, fruits: List[int]) -> int: n = len(fruits) if n <= 2: return n # First we want to get the first two tree so we can start tracking # our local longest first_fruit = fruits[0] second_fruit = fruits[1] # next we want to be able to look back at the previous fruit tree to # track out streaks on an individual fruit, a streak will only every # apply to the most recently seen fruit tree, so we only need to know the last # assume indexes [0, 1, 2, 3, 4, 5] # and fruit trees [0, 1, 1, 1, 2, 3] if we are at index 3 and our second_fruit # is 1, prev will be 1 and our second_streak will be 2 before we process this fruit # after we process it prev will be set to the current fruit which is also 1 # and second_streak will now be 3 # However, once we reach index 4 our streak will be broken our, but since second_fruit # is the most recently seen fruit or equal to prev, its streak will become our current total # first_fruit will now be replaced with the newly seen fruit, since it was not the # most recent prev and its streak will be set to 1 prev = first_fruit first_streak = 1 second_streak = 0 if first_fruit == second_fruit: first_streak += 1 else: second_streak += 1 prev = second_fruit # Track the longest total we see longest = first_streak + second_streak total = first_streak + second_streak for i in range(2, n): fruit = fruits[i] if fruit == first_fruit: total += 1 # add 1 to total since fruits did not change # we only increment our streak if fruit is equal to prev # else we set it to 1 since we have a streak of 1 if prev == first_fruit: first_streak += 1 else: first_streak = 1 elif fruit == second_fruit: total += 1 # add 1 to total since fruits did not change # we only increment our streak if fruit is equal to prev # else we set it to 1 since we have a streak of 1 if prev == second_fruit: second_streak += 1 else: second_streak = 1 else: # we found a fruit so check if our current total > longest longest = max(longest, total) # So now we have to get the next total started # we check to see what the last fruit was because our current first # or second fruit will now overlap the new fruit type based on the previous seen # e.g. if you look at the 4th index in the array example above once we see 2 # we no longer care about one of the fruits, in this case its the first fruit # so we can replace it, however the second fruits streak will be added to our # new first fruits streak of 1 if prev == first_fruit: total = first_streak second_fruit = fruit second_streak = 1 else: # prev == second_fruit total = second_streak first_fruit = fruit first_streak = 1 total += 1 # capture prev in each loop iteration prev = fruit # finally just one more check against the final total and return return max(longest, total)
fruit-into-baskets
Python Solution O(n) with explanations 99% TC and 98% SC
valepos
0
47
fruit into baskets
904
0.426
Medium
14,648
https://leetcode.com/problems/fruit-into-baskets/discuss/2228882/Python3-Explanation-Easy-to-understand-O(N)-O(1)-Solution-or-Sliding-Window
class Solution: def totalFruit(self, fruits: List[int]) -> int: lptr = 0 basket1 = [None, 0] basket2 = [None, 0] size = 0 for i in range(len(fruits)): # Check if basket 1 or 2 contains the fruit type if basket1[0] == fruits[i]: basket1[1] += 1 elif basket2[0] == fruits[i]: basket2[1] += 1 # Check if basket 1 or 2 is empty elif basket1[0] is None: basket1[0], basket1[1] = fruits[i], 1 elif basket2[0] is None: basket2[0], basket2[1] = fruits[i], 1 # Otherwise we need to empty a basket before adding the new type else: while True: if basket1[0] == fruits[lptr]: basket1[1] -= 1 lptr += 1 # If the count is 0, then we can set the new type and initialize it's count with 1 if basket1[1] == 0: basket1[0], basket1[1] = fruits[i], 1 break # If the type doesn't exist in the first basket then it is guarnteed to exist in the second else: basket2[1] -= 1 lptr += 1 if basket2[1] == 0: basket2[0], basket2[1] = fruits[i], 1 break # Every iteration we must check to see if there is a new maximum size size = max(size, basket1[1] + basket2[1]) return size
fruit-into-baskets
[Python3] [Explanation] Easy to understand O(N) O(1) Solution | Sliding Window
shrined
0
129
fruit into baskets
904
0.426
Medium
14,649
https://leetcode.com/problems/fruit-into-baskets/discuss/2158156/easy-python-solution-beginners-friendly
class Solution: def totalFruit(self, fruits: List[int]) -> int: # same as bsic problem of , having unique character == k , here k is equal to 2. # here we handle case when no. of distinct fruits are already less than 2 or equal to 2 d=Counter(fruits) if len(d)<=2: return len(fruits) i,j,count=0,0,-float('inf') dict={} while j<len(fruits): dict[fruits[j]]=dict.get(fruits[j],0)+1 if len(dict)==2: count=max(count,j-i+1) else: while len(dict)>2: dict[fruits[i]]-=1 if dict[fruits[i]]==0: del dict[fruits[i]] i+=1 j+=1 return count
fruit-into-baskets
easy python solution , beginners friendly
Aniket_liar07
0
78
fruit into baskets
904
0.426
Medium
14,650
https://leetcode.com/problems/fruit-into-baskets/discuss/2061243/Python3-or-100-speed-%2B-Explanation
class Solution: def totalFruit(self, fruits: List[int]) -> int: dp = [1] s = [fruits[0]] for i in range(1, len(fruits)): if fruits[i] != fruits[i - 1]: dp.append(1) s.append(fruits[i]) else: dp[-1] += 1 if len(s) == 1: return dp[0] a, b = s[0], s[1] ans = 0 tmp_ans = dp[0] + dp[1] for i in range(2, len(s)): if s[i] != a and s[i] != b: ans = max(ans, tmp_ans) tmp_ans = dp[i] + dp[i - 1] a, b = s[i - 1], s[i] else: tmp_ans += dp[i] ans = max(ans, tmp_ans) return ans
fruit-into-baskets
Python3 | 100% speed + Explanation
manfrommoon
0
46
fruit into baskets
904
0.426
Medium
14,651
https://leetcode.com/problems/fruit-into-baskets/discuss/1720462/Python-Sliding-window-solution-explained
class Solution: # to rephrase the question, we need to find # the longest subarray consisting of only # two characters. def totalFruit(self, fruits: List[int]) -> int: basket = {} i, j = 0, 0 out = 0 while j < len(fruits): # if we have space in our basket # add the current fruit into it # and add the idx of the current # fruit as it's value in the map if len(basket) <= 2: basket[fruits[j]] = j # if the basket goes over # the allowed size (2), we need # to resize it. Here, we find # the min index from the basket # i.e the last occurrence of the first # fruit and then set i to the next index # of that occurrence which would be the # second fruit, j is on the third fruit # right now. We also remove the first # fruit from the basket if len(basket) > 2: _min = len(fruits) - 1 for _, idx in basket.items(): _min = min(_min, idx) i = _min + 1 del basket[fruits[_min]] # the range of [i..j] is # the result here j += 1 out = max(out, j - i) return out
fruit-into-baskets
[Python] Sliding window solution explained
buccatini
0
138
fruit into baskets
904
0.426
Medium
14,652
https://leetcode.com/problems/fruit-into-baskets/discuss/1708154/sliding-window-of-K-distinct-elements-or-easy-or-python
class Solution: def totalFruit(self, fruits: List[int]) -> int: lptr, rptr, freq, N, max_l = 0, 0, collections.defaultdict(int), len(fruits), -math.inf while rptr < N: fruit = fruits[rptr] freq[fruit]+=1 if len(freq) <= 2: max_l = max(max_l, rptr-lptr+1) while lptr <= rptr and len(freq) > 2: fruit = fruits[lptr] freq[fruit]-=1 if freq[fruit] == 0: del freq[fruit] lptr+=1 rptr+=1 return max_l
fruit-into-baskets
sliding window of K distinct elements | easy | python
SN009006
0
75
fruit into baskets
904
0.426
Medium
14,653
https://leetcode.com/problems/fruit-into-baskets/discuss/1312304/Python3-Sliding-window-solution
class Solution: def totalFruit(self, fruits: List[int]) -> int: picked = [] m = 0 curr_m = 0 i = 0 while (i < len(fruits)): if(fruits[i] not in picked and len(picked) < 2): picked.append(fruits[i]) curr_m += 1 i+=1 if(m < curr_m): m = curr_m continue if(fruits[i] in picked and len(picked) <= 2): curr_m += 1 i+=1 if(m < curr_m): m = curr_m continue if(fruits[i] not in picked and len(picked) == 2): k = fruits[i-1] while(i > 0): if(fruits[i-1] == k): i -= 1 else: break picked = [] curr_m = 0 continue return m
fruit-into-baskets
Python3 Sliding window solution
PranavBharadwaj1305
0
45
fruit into baskets
904
0.426
Medium
14,654
https://leetcode.com/problems/fruit-into-baskets/discuss/949027/Python3-deque-O(N)
class Solution: def totalFruit(self, tree: List[int]) -> int: ans = ii = -1 seen = {} queue = deque([None]*2) for i, x in enumerate(tree): seen[x] = i if x != queue[-1]: queue.append(x) x = queue.popleft() if x not in queue: ii = seen.get(x, -1) ans = max(ans, i - ii) return ans
fruit-into-baskets
[Python3] deque O(N)
ye15
0
69
fruit into baskets
904
0.426
Medium
14,655
https://leetcode.com/problems/fruit-into-baskets/discuss/949027/Python3-deque-O(N)
class Solution: def totalFruit(self, tree: List[int]) -> int: ans = ii = 0 freq = {} for i, x in enumerate(tree): freq[x] = 1 + freq.get(x, 0) while len(freq) > 2: freq[tree[ii]] -= 1 if freq[tree[ii]] == 0: freq.pop(tree[ii]) ii += 1 ans = max(ans, i - ii + 1) return ans
fruit-into-baskets
[Python3] deque O(N)
ye15
0
69
fruit into baskets
904
0.426
Medium
14,656
https://leetcode.com/problems/sort-array-by-parity/discuss/356271/Solution-in-Python-3-(beats-~96)-(short)-(-O(1)-space-)-(-O(n)-speed-)
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: i, j = 0, len(A) - 1 while i < j: if A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i] i, j = i + 1 - A[i] % 2, j - A[j] % 2 return A
sort-array-by-parity
Solution in Python 3 (beats ~96%) (short) ( O(1) space ) ( O(n) speed )
junaidmansuri
21
2,300
sort array by parity
905
0.757
Easy
14,657
https://leetcode.com/problems/sort-array-by-parity/discuss/356271/Solution-in-Python-3-(beats-~96)-(short)-(-O(1)-space-)-(-O(n)-speed-)
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: return sorted(A, key = lambda x : x % 2) class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: return [i for i in A if not i % 2] + [i for i in A if i % 2] - Junaid Mansuri (LeetCode ID)@hotmail.com
sort-array-by-parity
Solution in Python 3 (beats ~96%) (short) ( O(1) space ) ( O(n) speed )
junaidmansuri
21
2,300
sort array by parity
905
0.757
Easy
14,658
https://leetcode.com/problems/sort-array-by-parity/discuss/2166617/Python3-O(n)-oror-O(1)-Runtime%3A-74.80
class Solution: # O(n) || O(1) def sortArrayByParity(self, array: List[int]) -> List[int]: if not array: return array left, right = 0, len(array) - 1 while left < right: if array[left] % 2 == 0: left += 1 else: array[left], array[right] = array[right], array[left] right -= 1 return array
sort-array-by-parity
Python3 O(n) || O(1) Runtime: 74.80%
arshergon
2
69
sort array by parity
905
0.757
Easy
14,659
https://leetcode.com/problems/sort-array-by-parity/discuss/1999939/Python3-98.21-or-One-Pass-O(N)-or-Easy-Implementation
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: l = deque([]) for i in nums: if i % 2: l.append(i) else: l.appendleft(i) return l
sort-array-by-parity
Python3 98.21% | One Pass O(N) | Easy Implementation
doneowth
2
69
sort array by parity
905
0.757
Easy
14,660
https://leetcode.com/problems/sort-array-by-parity/discuss/2473908/Simple-Python3-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: list1=[] list2=[] for ele in nums: if ele%2==0: list1.append(ele) else: list2.append(ele) return list1+list2
sort-array-by-parity
Simple Python3 solution
anirudh422
1
39
sort array by parity
905
0.757
Easy
14,661
https://leetcode.com/problems/sort-array-by-parity/discuss/2182605/Easy-python-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: even = [] odd = [] for i in range(len(nums)): if nums[i] % 2 == 0: even.append(nums[i]) else: odd.append(nums[i]) return even + odd
sort-array-by-parity
Easy python solution
rohansardar
1
34
sort array by parity
905
0.757
Easy
14,662
https://leetcode.com/problems/sort-array-by-parity/discuss/2009084/Python-or-Two-Pointer-or-O(1)-Space
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: if len(nums) == 0: return [] j = 0 for i in range(len(nums)): if nums[i]%2 == 0: nums[i], nums[j] = nums[j], nums[i] j += 1 return nums
sort-array-by-parity
Python | Two Pointer | O(1) Space
PythonicLava
1
82
sort array by parity
905
0.757
Easy
14,663
https://leetcode.com/problems/sort-array-by-parity/discuss/2001285/Python3-or-Two-Pointer-or-Easy-Solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: i=0 j=0 while i!=len(nums): #Running loop till i reach to the lenght of nums array or list. if nums[i]%2==0: nums[i],nums[j]=nums[j],nums[i] #Swapping the odd no. with even no. j+=1 i+=1 return nums
sort-array-by-parity
Python3 | Two-Pointer | Easy Solution
arpit_yadav
1
19
sort array by parity
905
0.757
Easy
14,664
https://leetcode.com/problems/sort-array-by-parity/discuss/2000083/PYTHON-oror-SIMPLE-oror-EASY-UNDERSTAND-oror
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: x = set() for i in range(1,len(nums)+1): x.add(i) return x.difference(set(nums))
sort-array-by-parity
PYTHON || SIMPLE || EASY UNDERSTAND ||
Airodragon
1
12
sort array by parity
905
0.757
Easy
14,665
https://leetcode.com/problems/sort-array-by-parity/discuss/1999564/Python-Simple-In-Place-One-Pass
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: i,j = 0, len(nums)-1 while i < j: while i < j and nums[i]%2==0: i+=1 while i < j and nums[j]%2==1: j-=1 nums[j], nums[i]=nums[i], nums[j] return nums
sort-array-by-parity
✅ Python Simple In-Place One Pass
constantine786
1
48
sort array by parity
905
0.757
Easy
14,666
https://leetcode.com/problems/sort-array-by-parity/discuss/1854913/Python-easy-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: even = [] odd = [] for i in nums: if i % 2 == 0: even.append(i) else: odd.append(i) return even + odd
sort-array-by-parity
Python easy solution
alishak1999
1
37
sort array by parity
905
0.757
Easy
14,667
https://leetcode.com/problems/sort-array-by-parity/discuss/1159626/Python-pythonic-fast-1-line
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: return [x for x in A if not x % 2] + [x for x in A if x % 2]
sort-array-by-parity
[Python] pythonic, fast, 1 line
cruim
1
62
sort array by parity
905
0.757
Easy
14,668
https://leetcode.com/problems/sort-array-by-parity/discuss/1030330/Python3-easy-and-efficient-solution
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: even = [] odd = [] for i in A: if i%2 == 0: even.append(i) else: odd.append(i) return even+odd
sort-array-by-parity
Python3 easy and efficient solution
EklavyaJoshi
1
72
sort array by parity
905
0.757
Easy
14,669
https://leetcode.com/problems/sort-array-by-parity/discuss/1030330/Python3-easy-and-efficient-solution
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: return sorted(A, key = lambda x : x%2)
sort-array-by-parity
Python3 easy and efficient solution
EklavyaJoshi
1
72
sort array by parity
905
0.757
Easy
14,670
https://leetcode.com/problems/sort-array-by-parity/discuss/803860/Python-Simple-Solution-Explained
class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: l = 0 r = len(A) - 1 while l < r: while A[l] % 2 == 0 and l < r: l += 1 while A[r] % 2 == 1 and l < r: r -= 1 A[l], A[r] = A[r], A[l] return A
sort-array-by-parity
Python Simple Solution Explained
spec_he123
1
57
sort array by parity
905
0.757
Easy
14,671
https://leetcode.com/problems/sort-array-by-parity/discuss/2847500/Python3-Inplace-O(1)-Space-Solution-O(N)-Time
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: # try to do it in place left = 0 right = len(nums) - 1 while left < right: if nums[left] % 2: # switch elements nums[right], nums[left] = nums[left], nums[right] # decrease right pointer right -= 1 else: # go on with left pointer left += 1 return nums
sort-array-by-parity
[Python3] - Inplace O(1)-Space Solution - O(N) Time
Lucew
0
1
sort array by parity
905
0.757
Easy
14,672
https://leetcode.com/problems/sort-array-by-parity/discuss/2846674/Python-simple-solution-check-it-out.
class Solution(object): def sortArrayByParity(self, nums): i = 0 len_ = len(nums) - 1 while i != len_: if not nums[i] % 2 == 0: nums[i], nums[len_] = nums[len_], nums[i] len_ -= 1 else: i += 1 return nums
sort-array-by-parity
Python simple solution - check it out.
Nematulloh
0
2
sort array by parity
905
0.757
Easy
14,673
https://leetcode.com/problems/sort-array-by-parity/discuss/2841776/Two-Pointer-Simple-and-Efficient-O(n)-time-O(1)-space
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: e, o = 0, len(nums) - 1 while e < o: if nums[e] &amp; 1: nums[e], nums[o] = nums[o], nums[e] o -= 1 else: e += 1 return nums
sort-array-by-parity
Two-Pointer, Simple and Efficient - O(n) time, O(1) space
Aritram
0
1
sort array by parity
905
0.757
Easy
14,674
https://leetcode.com/problems/sort-array-by-parity/discuss/2828515/Sort-Array-By-Parity-(Python)-TC%3A-O(n)-SC%3A-O(1)
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: """ Input: nums = [3,1,2,4] Output: [2,4,3,1] """ w, n = 0, len(nums) for i in range(0, n): if nums[i] &amp; 1 == 0: nums[w], nums[i] = nums[i], nums[w] w += 1 return nums
sort-array-by-parity
Sort Array By Parity (Python) TC: O(n) SC: O(1)
WizardDev
0
1
sort array by parity
905
0.757
Easy
14,675
https://leetcode.com/problems/sort-array-by-parity/discuss/2801247/Python-O(N)O(1)-Simple-solution-(In-Place)
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: slow = 0 for i in range(len(nums)): if nums[i] % 2 == 0: nums[slow], nums[i] = nums[i], nums[slow] slow += 1 return nums
sort-array-by-parity
[Python] O(N)/O(1) Simple solution (In-Place)
urrusjm
0
1
sort array by parity
905
0.757
Easy
14,676
https://leetcode.com/problems/sort-array-by-parity/discuss/2793543/Python-Two-pointers-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: l, r = 0, len(nums) - 1 while l < r: if nums[r] % 2 == 0: nums[l], nums[r] = nums[r], nums[l] l += 1 else: r -= 1 return nums
sort-array-by-parity
[Python] Two pointers solution
shahbaz95ansari
0
1
sort array by parity
905
0.757
Easy
14,677
https://leetcode.com/problems/sort-array-by-parity/discuss/2793015/generator-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: tmp = [nums[x] for x in range(len(nums)) if nums[x] % 2 == 1] res = [nums[x] for x in range(len(nums)) if nums[x] % 2 == 0] + tmp return res
sort-array-by-parity
generator solution
ayanokoj1
0
1
sort array by parity
905
0.757
Easy
14,678
https://leetcode.com/problems/sort-array-by-parity/discuss/2784621/Divide-nd-Merge
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: even,odd=[],[] for i in nums: if i%2==0: even.append(i) else: odd.append(i) res=even+odd return res
sort-array-by-parity
Divide nd Merge
bhavya_vermaa
0
1
sort array by parity
905
0.757
Easy
14,679
https://leetcode.com/problems/sort-array-by-parity/discuss/2780250/Simple-Python-Solution-Both-Brute-ForceOptimized-Solution-and-one-linear-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: new_list = [] for i in nums: if i % 2 == 0: new_list.append(i) for i in nums: if i % 2 != 0: new_list.append(i) return new_list
sort-array-by-parity
Simple Python Solution - Both Brute Force,Optimized Solution and one linear solution
danishs
0
2
sort array by parity
905
0.757
Easy
14,680
https://leetcode.com/problems/sort-array-by-parity/discuss/2780250/Simple-Python-Solution-Both-Brute-ForceOptimized-Solution-and-one-linear-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: return sorted(nums, key = lambda x : x % 2)
sort-array-by-parity
Simple Python Solution - Both Brute Force,Optimized Solution and one linear solution
danishs
0
2
sort array by parity
905
0.757
Easy
14,681
https://leetcode.com/problems/sort-array-by-parity/discuss/2780250/Simple-Python-Solution-Both-Brute-ForceOptimized-Solution-and-one-linear-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: return [ i for i in nums if i % 2 == 0] + [i for i in nums if i % 2 != 0 ]
sort-array-by-parity
Simple Python Solution - Both Brute Force,Optimized Solution and one linear solution
danishs
0
2
sort array by parity
905
0.757
Easy
14,682
https://leetcode.com/problems/sort-array-by-parity/discuss/2757778/Very-Easy-to-understand-solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: count = 0 for i in range(len(nums)): if nums[i] % 2==0: temp = nums[count] nums[count] = nums[i] nums[i] = temp count+=1 return nums
sort-array-by-parity
Very Easy to understand solution
shashank00818
0
1
sort array by parity
905
0.757
Easy
14,683
https://leetcode.com/problems/sort-array-by-parity/discuss/2655343/Python-Easy-Solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: r = len(nums) - 1 l = 0 while l < r: while l < r and nums[l] % 2 == 0: l += 1 #increment while its even------------- while l < r and nums[r] % 2 != 0: r -= 1 #decrement while its odd-------------- nums[l], nums[r] = nums[r], nums[l] return nums
sort-array-by-parity
Python Easy Solution
user6770yv
0
4
sort array by parity
905
0.757
Easy
14,684
https://leetcode.com/problems/sort-array-by-parity/discuss/2653891/Simplest-and-easy-solution-or-Python
class Solution(object): def sortArrayByParity(self, nums): """ :type nums: List[int] :rtype: List[int] """ startPointer=0 temp=0 for i in range(len(nums)): if nums[i]%2==0: temp=nums[startPointer] nums[startPointer]=nums[i] nums[i]=temp startPointer+=1 return nums
sort-array-by-parity
Simplest and easy solution | Python
msherazedu
0
2
sort array by parity
905
0.757
Easy
14,685
https://leetcode.com/problems/sort-array-by-parity/discuss/2591576/optimized-solutiongreatergreaterusing-two-pointer-algo-(python3)
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: l = 0 h = len(nums)- 1 while l<h: if (nums[l]%2 != 0): if (nums[h]%2 == 0): nums[l] , nums[h] = nums[h] , nums[l] l += 1 h -= 1 else: h -=1 else: l += 1 return nums
sort-array-by-parity
optimized solution>>using two pointer algo (python3)
kingshukmaity60
0
19
sort array by parity
905
0.757
Easy
14,686
https://leetcode.com/problems/sort-array-by-parity/discuss/2570688/SIMPLE-PYTHON3-SOLUTION-95less-memory-usage
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: for i in range(len(nums)): if nums[i]%2==0: nums.insert(0,nums.pop(i)) return nums
sort-array-by-parity
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔95%less memory usage
rajukommula
0
15
sort array by parity
905
0.757
Easy
14,687
https://leetcode.com/problems/sort-array-by-parity/discuss/2530199/Python-linear-time-solution-with-constant-space.
class Solution(object): def sortArrayByParity(self, arr): l,r=0,len(arr)-1 while l<r: if arr[l]%2==1 and arr[r]%2==0: arr[l],arr[r]=arr[r],arr[l] l+=1 r-=1 elif arr[l]%2==0 and arr[r]%2==0: l+=1 elif arr[l]%2==1 and arr[r]%2==1: r-=1 else: l+=1 r-=1 return arr
sort-array-by-parity
Python linear time solution with constant space.
babashankarsn
0
14
sort array by parity
905
0.757
Easy
14,688
https://leetcode.com/problems/sort-array-by-parity/discuss/2483906/Clean-and-well-structured-Python3-implementation-(Top-97.1)
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: # transverse nums # if nums[i] is even # put it in first index(l) and increase l+=1 #if nums[i] is not even keep increasing second pointer l =0 r = 0 for i in range(len(nums)): if nums[i] % 2 == 0: nums[l], nums[r] = nums[i], nums[l] l+=1 r+=1 return nums
sort-array-by-parity
✔️ Clean and well structured Python3 implementation (Top 97.1%)
explusar
0
10
sort array by parity
905
0.757
Easy
14,689
https://leetcode.com/problems/sort-array-by-parity/discuss/2461482/Fast-solution-using-lambda-function-in-python
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: evens = list(filter(lambda x: x % 2 == 0, nums)) odds = list(filter(lambda x: x % 2 != 0, nums)) return evens + odds
sort-array-by-parity
Fast solution using lambda function in python
samanehghafouri
0
8
sort array by parity
905
0.757
Easy
14,690
https://leetcode.com/problems/sort-array-by-parity/discuss/2461450/solution-using-List-comprehension-fast-less-memory
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: evens = [e for e in nums if e % 2 == 0] odds = [o for o in nums if o % 2 != 0] return evens + odds
sort-array-by-parity
solution using List comprehension; fast, less memory
samanehghafouri
0
6
sort array by parity
905
0.757
Easy
14,691
https://leetcode.com/problems/sort-array-by-parity/discuss/2418705/Python3-Two-Pointer-Solution
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: l= 0 r= len(nums)-1 while(l<r): if nums[l]%2 ==0 and nums[r]%2 ==0: print(f'{nums[l]} and {nums[r]} Both Even so increment L') l+=1 elif nums[l]%2 !=0 and nums[r]%2 == 0: print(f'L:{nums[l]} is Odd and {nums[r]} is Even so swap both and increment l and decrement r') nums[l],nums[r] = nums[r],nums[l] l+=1 r-=1 elif nums[l]%2 ==0 and nums[r]%2!=0: print(f"l: {nums[l]} is Even and r: {nums[r]} is Odd so just increment l and decrement r ") l+=1 r-=1 elif nums[l]%2 !=0 and nums[r]%2 !=0: print(f'{nums[l]} and {nums[r]} Both are Odd so just decrement r') r-=1 return nums
sort-array-by-parity
Python3 Two Pointer Solution
aditya_maskar
0
9
sort array by parity
905
0.757
Easy
14,692
https://leetcode.com/problems/sort-array-by-parity/discuss/2401777/Python-one-line-O(N)
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: return [i for i in nums if i % 2 == 0] + [i for i in nums if not i % 2 == 0]
sort-array-by-parity
Python one line O(N)
YangJenHao
0
26
sort array by parity
905
0.757
Easy
14,693
https://leetcode.com/problems/sort-array-by-parity/discuss/2399438/SImple-Swap-Mehod-Using-Python-Space-O(1)
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: count = 0 for i in range(len(nums)): if nums[i]%2 == 0: nums[count], nums[i] = nums[i], nums[count] count += 1 return nums
sort-array-by-parity
SImple Swap Mehod Using Python Space = O(1)
Abhi_-_-
0
15
sort array by parity
905
0.757
Easy
14,694
https://leetcode.com/problems/sort-array-by-parity/discuss/2372312/Sort-Array-By-Parity
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: lisp1=[] lisp2=[] for i in range(len(nums)): if nums[i]%2==0: lisp1.append(nums[i]) else: lisp2.append(nums[i]) fin_lisp=lisp1+lisp2 return fin_lisp
sort-array-by-parity
Sort Array By Parity
Faraz369
0
7
sort array by parity
905
0.757
Easy
14,695
https://leetcode.com/problems/sort-array-by-parity/discuss/2309479/Sort-Array-By-Parity-with-python3
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: arr = [] newarr = [] for element in nums: if element % 2 == 1: arr.append(element) else: newarr.append(element) newarr.extend(arr) return newarr
sort-array-by-parity
Sort Array By Parity with python3 🤩
ibrahimbayburtlu5
0
9
sort array by parity
905
0.757
Easy
14,696
https://leetcode.com/problems/sort-array-by-parity/discuss/2298912/Python-simplest-1-Liner
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: return sorted(nums, key=lambda t: t % 2)
sort-array-by-parity
Python simplest 1-Liner
amaargiru
0
17
sort array by parity
905
0.757
Easy
14,697
https://leetcode.com/problems/sort-array-by-parity/discuss/2211271/SIMPLE-Python-solution-using-iteration
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: even = [] odds = [] for i in nums: if i % 2 == 0: even.append(i) elif i % 2 == 1: odds.append(i) return even + odds
sort-array-by-parity
SIMPLE Python solution using iteration
lyubol
0
27
sort array by parity
905
0.757
Easy
14,698
https://leetcode.com/problems/sort-array-by-parity/discuss/2204692/faster-than-75.98-of-Python3
class Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: even = [] odd = [] for i in nums: if i%2 ==0: even.append(i) else: odd.append(i) return even+odd
sort-array-by-parity
faster than 75.98% of Python3
EbrahimMG
0
20
sort array by parity
905
0.757
Easy
14,699