problem_title stringlengths 3 77 | python_solutions stringlengths 81 8.45k | post_href stringlengths 64 213 | upvotes int64 0 1.2k | question stringlengths 0 3.6k | post_title stringlengths 2 100 | views int64 1 60.9k | slug stringlengths 3 77 | acceptance float64 0.14 0.91 | user stringlengths 3 26 | difficulty stringclasses 3
values | __index_level_0__ int64 0 34k | number int64 1 2.48k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
largest sum of averages | class Solution:
def largestSumOfAverages(self, nums: List[int], k: int) -> float:
@lru_cache(maxsize=None)
def maxAvgSum(index: int, partitions_left: int) -> int:
if partitions_left == 1:
return sum(nums[index:]) / (len(nums) - index)
max_sum: float ... | https://leetcode.com/problems/largest-sum-of-averages/discuss/1633894/Python-3-Solution-Using-Memoization | 1 | You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximu... | Python 3 Solution Using Memoization | 100 | largest-sum-of-averages | 0.529 | mlalma | Medium | 13,178 | 813 |
binary tree pruning | class Solution(object):
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root==None:
return None
_l = self.pruneTree(root.left)
_r = self.pruneTree(root.right)
if root.val == 0 and _l == None and _r == None:
... | https://leetcode.com/problems/binary-tree-pruning/discuss/298312/Python-faster-than-98-16-ms | 8 | Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
A subtree of a node node is node plus every node that is a descendant of node.
Example 1:
Input: root = [1,null,0,0,1]
Output: [1,null,0,null,1]
Explanation:
Only the red nodes satisfy t... | Python - faster than 98%, 16 ms | 826 | binary-tree-pruning | 0.726 | il_buono | Medium | 13,183 | 814 |
bus routes | class Solution:
def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
m = defaultdict(set)
for i, route in enumerate(routes):
for node in route:
m[node].add(i)
ans = -1
vis = set()
queue = deque()
queue.... | https://leetcode.com/problems/bus-routes/discuss/2275016/Python3-BFS-Approach | 1 | You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.
For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.
You will start at the bus stop source (You are not on any bus ... | [Python3] BFS Approach | 127 | bus-routes | 0.457 | van_fantasy | Hard | 13,218 | 815 |
ambiguous coordinates | class Solution:
def ambiguousCoordinates(self, s: str) -> List[str]:
s = s.strip("(").strip(")")
def fn(s):
"""Return valid numbers from s."""
if len(s) == 1: return [s]
if s.startswith("0") and s.endswith("0"): return []
if s.startswith("0")... | https://leetcode.com/problems/ambiguous-coordinates/discuss/934654/Python3-valid-numbers | 7 | We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, decimal points, and spaces and ended up with the string s.
For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)".
Return a list of strings representing all possibilities for what our original coordinat... | [Python3] valid numbers | 302 | ambiguous-coordinates | 0.561 | ye15 | Medium | 13,225 | 816 |
linked list components | class Solution:
def numComponents(self, head: ListNode, G: List[int]) -> int:
Gs = set(G)
ans = 0
while head:
if head.val in Gs and (head.next is None or head.next.val not in Gs): ans += 1
head = head.next
return ans | https://leetcode.com/problems/linked-list-components/discuss/933679/Python3-counting-end-of-component | 3 | You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.
Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.
Example 1:
Input: head = [0,1,2,3], nums = [0... | [Python3] counting end of component | 180 | linked-list-components | 0.581 | ye15 | Medium | 13,231 | 817 |
race car | class Solution:
def racecar(self, target: int) -> int:
q = deque()
q.append((0,0,1))
while q:
m,p,s = q.popleft()
if p==target:
return m
rev = -1 if s>0 else 1
q.append((m+1,p+s,s*2))
if (p+s<target and s<0) or (p+s>target and s>0): ... | https://leetcode.com/problems/race-car/discuss/1512080/Greedy-Approach-oror-Normal-conditions-oror-94-faster-oror-Well-Coded | 9 | Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):
When you get an instruction 'A', your car does the following:
position += speed
speed *= 2
When you ge... | 📌📌 Greedy Approach || Normal conditions || 94% faster || Well-Coded 🐍 | 764 | race-car | 0.435 | abhi9Rai | Hard | 13,240 | 818 |
most common word | class Solution:
def getSplit(self, s):
result = []
strS = ''
for i in s.lower():
if i not in "!?',;. ": strS += i
else:
if len(strS) > 0: result.append(strS)
strS = ''
if len(strS) > 0: result.append(strS)
return result
... | https://leetcode.com/problems/most-common-word/discuss/2830994/Python-oror-Long-but-FAST-oror-Memory-beats-82.67! | 1 | Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph are case-insensitive and the answer should be returned in lowercase.
Example 1... | Python || Long but FAST || Memory beats 82.67%! | 27 | most-common-word | 0.449 | qiy2019 | Easy | 13,243 | 819 |
short encoding of words | class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
words.sort(key=len, reverse=True)
res = []
for suffix in words:
if not any(word.endswith(suffix) for word in res): # check that this word is not actually a suffix
res.append(suffix)
... | https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation | 23 | A valid encoding of an array of words is any reference string s and array of indices indices such that:
words.length == indices.length
The reference string s ends with the '#' character.
For each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal ... | [Python] Concise Brute Force & Trie Solutions with Explanation | 1,100 | short-encoding-of-words | 0.607 | zayne-siew | Medium | 13,271 | 820 |
shortest distance to a character | class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
L = []
for idx, value in enumerate(s):
if value == c:
L.append(idx)
distance = []
i = 0
for idx, value in enumerate(s):
if value == c:
dista... | https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1226696/Python3Any-improvement | 5 | Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
Example 1:... | 【Python3】Any improvement ? | 293 | shortest-distance-to-a-character | 0.714 | qiaochow | Easy | 13,295 | 821 |
card flipping game | class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
"""
O(n) time complexity: n is length of fronts
O(n) space complexity
"""
same = {x for i, x in enumerate(fronts) if x == backs[i]}
res = 9999
for i in range(len(fronts)):
... | https://leetcode.com/problems/card-flipping-game/discuss/530999/Python3-simple-solution-using-a-for()-loop | 2 | You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any numb... | Python3 simple solution using a for() loop | 254 | card-flipping-game | 0.456 | jb07 | Medium | 13,330 | 822 |
binary trees with factors | class Solution:
def numFactoredBinaryTrees(self, arr: List[int]) -> int:
total_nums = len(arr)
moduler = 1000000007
count_product_dict = {num: 1 for num in arr}
arr.sort()
for i in range(1, total_nums):
for j in range(i):
quotient = arr[i] // arr[... | https://leetcode.com/problems/binary-trees-with-factors/discuss/2402569/Python-oror-Detailed-Explanation-oror-Easily-Understood-oror-DP-oror-O(n-*-sqrt(n)) | 35 | Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return the number of binary trees we can... | 🔥 Python || Detailed Explanation ✅ || Easily Understood || DP || O(n * sqrt(n)) | 1,100 | binary-trees-with-factors | 0.5 | wingskh | Medium | 13,333 | 823 |
goat latin | class Solution:
def toGoatLatin(self, sentence: str) -> str:
new = sentence.split() # Breaks up the input into individual sentences
count = 1 # Starting at 1 since we only have one "a" to begin with.
for x in range(len(new)):
if new[x][0].casefold() in 'aeiou': # Checks ... | https://leetcode.com/problems/goat-latin/discuss/1877272/Python-3-Simple-Solution-w-Explanation | 4 | You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
If a word begins with a vowel ('a', 'e', 'i', 'o... | [Python 3] - Simple Solution w Explanation | 110 | goat-latin | 0.678 | IvanTsukei | Easy | 13,358 | 824 |
friends of appropriate ages | class Solution:
def numFriendRequests(self, ages: List[int]) -> int:
ages.sort() # sort the `ages`
ans = 0
n = len(ages)
for idx, age in enumerate(ages): # for each age
lb = age # lower bound
... | https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2074946/Python-3-or-Three-Methods-(Binary-Search-CounterHashmap-Math)-or-Explanation | 5 | There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.
A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && age[x] < 100
Otherwise, x... | Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation | 416 | friends-of-appropriate-ages | 0.464 | idontknoooo | Medium | 13,401 | 825 |
most profit assigning work | class Solution:
#Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn)
#Space-Complexity: O(n)
def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:
#Approach: First of all, linearly traverse each and every corresponding index
#position of... | https://leetcode.com/problems/most-profit-assigning-work/discuss/2603913/Python3-or-Solved-Using-Binary-Search-W-Sorting-O((n%2Bm)*logn)-Runtime-Solution! | 2 | You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:
difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and
worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).
Every worker can be ... | Python3 | Solved Using Binary Search W/ Sorting O((n+m)*logn) Runtime Solution! | 134 | most-profit-assigning-work | 0.446 | JOON1234 | Medium | 13,412 | 826 |
making a large island | class Solution:
def largestIsland(self, grid: List[List[int]]) -> int:
N = len(grid)
DIRECTIONS = [(-1, 0), (0, -1), (0, 1), (1, 0)]
address = {}
def dfs(row, column, island_id):
queue = deque([(row, column, island_id)])
visited.add((row, column))
... | https://leetcode.com/problems/making-a-large-island/discuss/1340782/Python-Clean-DFS | 4 | You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.
Return the size of the largest island in grid after applying this operation.
An island is a 4-directionally connected group of 1s.
Example 1:
Input: grid = [[1,0],[0,1]]
Output: 3
Explanation: Change one 0 to 1 and connect two... | [Python] Clean DFS | 1,000 | making-a-large-island | 0.447 | soma28 | Hard | 13,422 | 827 |
count unique characters of all substrings of a given string | class Solution:
def uniqueLetterString(self, s: str) -> int:
r=0
for i in range(len(s)):
for j in range(i, len(s)):
ss=s[i:j+1]
unique=sum([ 1 for (i,v) in Counter(ss).items() if v == 1 ])
r+=unique
return r | https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process | 6 | Let's define a function countUniqueChars(s) that returns the number of unique characters in s.
For example, calling countUniqueChars(s) if s = "LEETCODE" then "L", "T", "C", "O", "D" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.
Given a string s, return the sum of countU... | Python O(n) with intuition / step-by-step thought process | 354 | count-unique-characters-of-all-substrings-of-a-given-string | 0.517 | alskdjfhg123 | Hard | 13,442 | 828 |
consecutive numbers sum | class Solution:
def consecutiveNumbersSum(self, n: int) -> int:
csum=0
result=0
for i in range(1,n+1):
csum+=i-1
if csum>=n:
break
if (n-csum)%i==0:
result+=1
return result | https://leetcode.com/problems/consecutive-numbers-sum/discuss/1466133/8-lines-Python3-code | 6 | Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.
Example 1:
Input: n = 5
Output: 2
Explanation: 5 = 2 + 3
Example 2:
Input: n = 9
Output: 3
Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: n = 15
Output: 4
Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + ... | 8 lines Python3 code | 705 | consecutive-numbers-sum | 0.415 | tongho | Hard | 13,456 | 829 |
positions of large groups | class Solution(object):
def largeGroupPositions(self, s):
s += " "
streak, char, out = 0, s[0], []
for i,c in enumerate(s):
if c != char:
if streak >= 3:
out.append([i-streak, i-1])
streak, cha... | https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22 | 1 | In a string s of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and "yy".
A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. ... | Python - simple and elegant - multiple solutions - "Streak" | 83 | positions-of-large-groups | 0.518 | domthedeveloper | Easy | 13,465 | 830 |
masking personal information | class Solution:
def maskPII(self, s: str) -> str:
if '@' in s: return f'{s[0].lower()}*****{s[s.index("@")-1].lower()+"".join([x.lower() for x in s[s.index("@"):]])}'
s=''.join([x for x in s if x not in '()- +'])
return ('' if len(s)<=10 else '+'+'*'*(len(s)-10)+'-')+f'***-***-{s[-4:]}' | https://leetcode.com/problems/masking-personal-information/discuss/1868652/3-Lines-Python-Solution-oror-98-Faster-oror-Memory-less-than-87 | 1 | You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.
Email address:
An email address is:
A name consisting of uppercase and lowercase English letters, followed by
The '@' symbol, followed by
The domain consis... | 3-Lines Python Solution || 98% Faster || Memory less than 87% | 94 | masking-personal-information | 0.47 | Taha-C | Medium | 13,484 | 831 |
flipping an image | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
"""
Simple & striaghtforward without using inbuilt functions.
In actual the run time is very less as we are iterating only n/2 time
for each image list.
Time complexity : O(n * ... | https://leetcode.com/problems/flipping-an-image/discuss/1363051/PYTHON-VERY-VERY-EASY-SOLN.-3-solutions-explained-O(n).-With-or-without-inbuilt-functions. | 10 | Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
For example, flipping [1,1,0] horizontally results in [0,1,1].
To invert an image means that each 0 is replaced by 1, and each 1 is... | [PYTHON] VERY VERY EASY SOLN. 3 solutions explained O(n). With or without inbuilt functions. | 663 | flipping-an-image | 0.805 | er1shivam | Easy | 13,489 | 832 |
find and replace in string | class Solution:
def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
# iterate from the greater index to the smallest
for i, src, tg in sorted(list(zip(indices, sources, targets)), reverse=True):
# if found the pattern matches with t... | https://leetcode.com/problems/find-and-replace-in-string/discuss/1920198/Python-3-or-simple-or-3-lines-of-code-w-explanation | 3 | You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.
To complete the ith replacement operation:
Check if the substring sources[i] occurs at index indices[i] in the or... | Python 3 | simple | 3 lines of code w/ explanation | 327 | find-and-replace-in-string | 0.541 | Ploypaphat | Medium | 13,539 | 833 |
sum of distances in tree | class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
size = [0]*n
def fn(x, par):
"""Retur... | https://leetcode.com/problems/sum-of-distances-in-tree/discuss/1311639/Python3-post-order-and-pre-order-dfs | 2 | There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.
You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Return an array answer of length n where answer[i] is the sum of the distances betwee... | [Python3] post-order & pre-order dfs | 195 | sum-of-distances-in-tree | 0.542 | ye15 | Hard | 13,550 | 834 |
image overlap | class Solution:
def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:
n = len(img1)
bestOverlap = 0
def helper(dr, dc):
overlap = 0
for r in range(n):
for c in range(n):
nr, nc = r + dr, c + dc
... | https://leetcode.com/problems/image-overlap/discuss/2748733/Python-(Faster-than-82)-or-Brute-force-(Recursive)-and-optimized-using-HashMap | 1 | You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.
We translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calcul... | Python (Faster than 82%) | Brute force (Recursive) and optimized using HashMap | 18 | image-overlap | 0.64 | KevinJM17 | Medium | 13,556 | 835 |
rectangle overlap | class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
[A,B,C,D], [E,F,G,H] = rec1, rec2
return F<D and E<C and B<H and A<G
- Python 3
- Junaid Mansuri | https://leetcode.com/problems/rectangle-overlap/discuss/342095/Solution-in-Python-3-(beats-100)-(-2-lines-) | 2 | An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if... | Solution in Python 3 (beats 100%) ( 2 lines ) | 581 | rectangle-overlap | 0.436 | junaidmansuri | Easy | 13,572 | 836 |
new 21 game | class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
@lru_cache(None)
def fn(n):
"""Return prob of of points between K and N given current point n."""
if N < n: return 0
if K <= n: return 1
if n+1 < K: return (1+W)/W*fn(n+1) ... | https://leetcode.com/problems/new-21-game/discuss/938221/Python3-top-down-and-bottom-up-dp | 4 | Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equa... | [Python3] top-down & bottom-up dp | 558 | new-21-game | 0.361 | ye15 | Medium | 13,589 | 837 |
push dominoes | class Solution:
def pushDominoes(self, dominoes: str) -> str:
dominoes = 'L' + dominoes + 'R'
res = []
left = 0
for right in range(1, len(dominoes)):
if dominoes[right] == '.':
continue
middle = right - left - 1
... | https://leetcode.com/problems/push-dominoes/discuss/2629832/Easy-Python-O(n)-solution | 3 | There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right p... | Easy Python O(n) solution | 225 | push-dominoes | 0.57 | namanxk | Medium | 13,594 | 838 |
similar string groups | class Solution:
def numSimilarGroups(self, strs: List[str]) -> int:
N = len(strs)
parent = [i for i in range(N)]
depth = [1 for _ in range(N)]
def find(idx):
if idx != parent[idx]:
return find(parent[idx])
return idx
def union... | https://leetcode.com/problems/similar-string-groups/discuss/2698654/My-Python-Union-Find-Solution | 1 | Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X.
For example, "tars" and "rats" are similar (swapping at positions 0 and 2), and "rats" and "arts" are similar, but "star" is not similar t... | My Python Union Find Solution | 99 | similar-string-groups | 0.478 | MonQiQi | Hard | 13,626 | 839 |
magic squares in grid | class Solution:
def numMagicSquaresInside(self, G: List[List[int]]) -> int:
M, N, S, t = len(G)-2, len(G[0])-2, {(8,1,6,3,5,7,4,9,2),(6,1,8,7,5,3,2,9,4),(2,7,6,9,5,1,4,3,8),(6,7,2,1,5,9,8,3,4)}, range(3)
return sum((lambda x: x in S or x[::-1] in S)(tuple(sum([G[i+k][j:j+3] for k in t],[]))) for i,j in it... | https://leetcode.com/problems/magic-squares-in-grid/discuss/381223/Two-Solutions-in-Python-3-(beats-~99)-(two-lines) | 1 | A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col grid of integers, how many 3 x 3 "magic square" subgrids are there? (Each subgrid is contiguous).
Example 1:
Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,... | Two Solutions in Python 3 (beats ~99%) (two lines) | 624 | magic-squares-in-grid | 0.385 | junaidmansuri | Medium | 13,631 | 840 |
keys and rooms | class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
visited_rooms = set()
stack = [0] # for rooms that we need to visit and we start from room [0]
while stack:
room = stack.pop()
visited_rooms.add(room)
for key in rooms[r... | https://leetcode.com/problems/keys-and-rooms/discuss/1116836/Python3-Soln-greater-Keys-and-Rooms-stack-implementation | 12 | There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, an... | [Python3] Soln -> Keys and Rooms [stack implementation] | 620 | keys-and-rooms | 0.702 | avEraGeC0der | Medium | 13,635 | 841 |
split array into fibonacci sequence | class Solution:
def splitIntoFibonacci(self, num: str) -> List[int]:
def dfs(i):
if i>=len(num):
return len(ans)>2
n = 0
for j in range(i, len(num)):
n = n*10 + int(num[j])
if n>2**31: # if number exceeds the ran... | https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1579510/PYTHON-BACKTRACKING-or-THREE-PROBLEMS-ONE-SOLUTION | 1 | You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:
0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),
f.length >= 3, and
f[i] + f[i + 1]... | PYTHON BACKTRACKING | THREE PROBLEMS ONE SOLUTION | 150 | split-array-into-fibonacci-sequence | 0.383 | hX_ | Medium | 13,680 | 842 |
guess the word | class Solution:
def findSecretWord(self, words: List[str], master: 'Master') -> None:
k = 1 # for tracing the number of loops
matches = 0
blacklists = [[] for i in range(6)]
while matches != 6:
n = len(words)
r = random.randint(0, n - 1)
... | https://leetcode.com/problems/guess-the-word/discuss/2385099/Python-Solution-with-narrowed-candidates-and-blacklist | 2 | You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word.
You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns:
-1 if word is not ... | [Python] Solution with narrowed candidates and blacklist | 203 | guess-the-word | 0.418 | bbshark | Hard | 13,687 | 843 |
backspace string compare | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
a, A = [collections.deque(), collections.deque()], [S,T]
for i in range(2):
for j in A[i]:
if j != '#': a[i].append(j)
elif a[i]: a[i].pop()
return a[0] == a[1] | https://leetcode.com/problems/backspace-string-compare/discuss/381659/Three-Solutions-in-Python-3-(With-and-Without-Deque-and-Two-Pointer) | 16 | Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".
Example 2:
Input:... | Three Solutions in Python 3 (With and Without Deque and Two-Pointer) | 2,600 | backspace-string-compare | 0.48 | junaidmansuri | Easy | 13,692 | 844 |
longest mountain in array | class Solution:
def longestMountain(self, arr: List[int]) -> int:
increasing = False
increased = False
mx = -math.inf
curr = -math.inf
for i in range(1, len(arr)):
if arr[i] > arr[i-1]:
if increasing:
curr += 1
... | https://leetcode.com/problems/longest-mountain-in-array/discuss/1837098/Python3%3A-One-pass-O(1)-Auxiliary-Space | 2 | You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr, return the length of the longest subar... | Python3: One pass, O(1) Auxiliary Space | 51 | longest-mountain-in-array | 0.402 | DheerajGadwala | Medium | 13,750 | 845 |
hand of straights | class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
counter = Counter(hand)
while counter:
n = groupSize
start = min(counter.keys())
while n:
if start not in counter:
return False
... | https://leetcode.com/problems/hand-of-straights/discuss/1938042/Python3-oror-Hashmap-oror-15-line-easy-to-understand | 3 | Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.
Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or fa... | Python3 || Hashmap || 15-line easy to understand | 227 | hand-of-straights | 0.564 | gulugulugulugulu | Medium | 13,763 | 846 |
shortest path visiting all nodes | class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
length = len(graph)
result = 0
visited_node = []
queue = []
for i in range(length):
visited_node.append(set([1<<i]))
queue.append([i,1<<i])
while queue:
result = result + 1
new_queue = []
for node, value ... | https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/1800062/Python-Simple-Python-Solution-Using-Breadth-First-Search | 6 | You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, an... | [ Python ] ✔✔ Simple Python Solution Using Breadth-First-Search 🔥✌ | 914 | shortest-path-visiting-all-nodes | 0.613 | ASHOK_KUMAR_MEGHVANSHI | Hard | 13,778 | 847 |
shifting letters | class Solution:
def shiftingLetters(self, S: str, shifts: List[int]) -> str:
final_shift = list(accumulate(shifts[::-1]))[::-1]
s_list = list(S)
for x in range(len(s_list)):
midval = ord(s_list[x]) + final_shift[x]%26
if midval > 122:
... | https://leetcode.com/problems/shifting-letters/discuss/1088920/PythonPython3-Shifting-Letter-or-2-Solutions-or-One-liner | 4 | You are given a string s of lowercase English letters and an integer array shifts of the same length.
Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').
For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.
Now for each shifts[i] = x, we want to sh... | [Python/Python3] Shifting Letter | 2 Solutions | One-liner | 761 | shifting-letters | 0.454 | newborncoder | Medium | 13,782 | 848 |
maximize distance to closest person | class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
#initialization, starting index is 0, result is res
left,res,index = -1,0,0
while index != len(seats):
# only right is 1
if left == -1 and seats[index] == 1:
res = max(res,index)
... | https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2706156/python%3A-easy-to-understand-3-situations | 2 | You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and t... | python: easy to understand, 3 situations | 95 | maximize-distance-to-closest-person | 0.476 | zoey513 | Medium | 13,804 | 849 |
rectangle area ii | class Solution:
def rectangleArea(self, rectangles: List[List[int]]) -> int:
line = []
for x1, y1, x2, y2 in rectangles:
line.append((y1, x1, x2, 1))
line.append((y2, x1, x2, 0))
ans = yy = val = 0
seg = []
for y, x1, x2, tf in sorted(line): ... | https://leetcode.com/problems/rectangle-area-ii/discuss/1398210/Python3-sweeping | 1 | You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.
Calculate the total area covered by all rectangles in the plane. Any area co... | [Python3] sweeping | 212 | rectangle-area-ii | 0.537 | ye15 | Hard | 13,840 | 850 |
loud and rich | class Solution:
def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
richer_count = [0 for _ in range(len(quiet))]
graph = defaultdict(list)
answer = [idx for idx in range(len(quiet))]
## create the graph so that we go from the richer to the poorer
... | https://leetcode.com/problems/loud-and-rich/discuss/2714041/Python-Pure-topological-sort | 1 | There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.
You are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All t... | Python Pure topological sort | 77 | loud-and-rich | 0.582 | Henok2011 | Medium | 13,841 | 851 |
peak index in a mountain array | class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
return (arr.index(max(arr))) | https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2068528/Simple-Python-one-liner | 3 | An array arr is a mountain if the following properties hold:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1]... | Simple Python one-liner | 144 | peak-index-in-a-mountain-array | 0.694 | tusharkhanna575 | Medium | 13,845 | 852 |
car fleet | class Solution:
def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:
ans = prev = 0
for pp, ss in sorted(zip(position, speed), reverse=True):
tt = (target - pp)/ss # time to arrive at target
if prev < tt:
ans += 1
p... | https://leetcode.com/problems/car-fleet/discuss/939525/Python3-greedy-O(NlogN) | 17 | There are n cars going to the same destination along a one-lane road. The destination is target miles away.
You are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).
A car can never pass another ca... | [Python3] greedy O(NlogN) | 1,200 | car-fleet | 0.501 | ye15 | Medium | 13,892 | 853 |
k similar strings | class Solution:
# DFS
def kSimilarity(self, A: str, B: str) -> int:
N = len(A)
def dfs(A, B, pos):
if A == B:
return 0
while A[pos] == B[pos]:
pos += 1
minCnt = float('inf')
for i in ran... | https://leetcode.com/problems/k-similar-strings/discuss/321201/three-solutions-of-this-problem-good-for-understanding-DFS-DFS-with-memo-and-BFS | 21 | Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.
Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.
Example 1:
Input: s1 = "ab", s2 = "ba"
Output: 1
Explanatio... | three solutions of this problem, good for understanding DFS, DFS with memo and BFS | 2,900 | k-similar-strings | 0.401 | shchshhappy | Hard | 13,909 | 854 |
score of parentheses | class Solution:
def scoreOfParentheses(self, s: str) -> int:
stk = [0] # temp value to help us
for char in s:
if char == '(':
stk.append(0) # new parent: current sum = 0
else:
# An expression will be closed
# Find its value... | https://leetcode.com/problems/score-of-parentheses/discuss/2299821/Python-or-faster-than-83-or-easy-understanding-or-explaining-with-comments | 3 | Given a balanced parentheses string s, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()" has score 1.
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:
Input: s = "... | Python | faster than 83% | easy-understanding | explaining with comments | 130 | score-of-parentheses | 0.65 | Saiko15 | Medium | 13,915 | 856 |
minimum cost to hire k workers | class Solution:
def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:
ans, rsm = inf, 0
pq = [] # max-heap
for q, w in sorted(zip(quality, wage), key=lambda x: x[1]/x[0]):
rsm += q
heappush(pq, -q)
if len(pq) > k: rsm += ... | https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/1265778/Python3-greedy-(priority-queue) | 1 | There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.
We want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules... | [Python3] greedy (priority queue) | 83 | minimum-cost-to-hire-k-workers | 0.521 | ye15 | Hard | 13,939 | 857 |
mirror reflection | class Solution:
def mirrorReflection(self, p: int, q: int) -> int:
L = lcm(p,q)
if (L//q)%2 == 0:
return 2
return (L//p)%2 | https://leetcode.com/problems/mirror-reflection/discuss/2376355/Python3-oror-4-lines-geometry-w-explanation-oror-TM%3A-9281 | 73 | There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.
The square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th recep... | Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81% | 3,400 | mirror-reflection | 0.633 | warrenruud | Medium | 13,943 | 858 |
buddy strings | class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
freq1=[0]*26
freq2=[0]*26
diff =0
if(len(s)!=len(goal)):
return False
for i in range(len(s)):
if(s[i]!=goal[i]):
diff+=1
freq1[ord(s[i])-ord('a')]+=1
... | https://leetcode.com/problems/buddy-strings/discuss/2790774/Python-oror-Beginner-Friendly-oror-98-faster-oror-O(n) | 1 | Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.
Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].
For example, swapping at indices 0 and 2 in "abcd" resu... | Python || Beginner Friendly || 98% faster || O(n) | 176 | buddy-strings | 0.291 | hasan2599 | Easy | 13,964 | 859 |
lemonade change | class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
change5=0
change10=0
change20=0
for i in range(len(bills)):
if bills[i]==5:
change5+=1
elif bills[i]==10:
change10+=1
change5-=1
eli... | https://leetcode.com/problems/lemonade-change/discuss/1260496/Python-3-Easy-to-understand-Better-than-95 | 4 | At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction ... | Python 3 Easy-to-understand Better than 95% | 447 | lemonade-change | 0.528 | mk_mohtashim | Easy | 13,985 | 860 |
score after flipping matrix | class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
for i in range(m):
if A[i][0] == 0:
for j in range(n): A[i][j] ^= 1
for j in range(n):
cnt = sum(A[i][j] for i in range(m))
if cnt < m - ... | https://leetcode.com/problems/score-after-flipping-matrix/discuss/940701/Python3-Greedy-O(MN) | 14 | You are given an m x n binary matrix grid.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
Return the highe... | [Python3] Greedy O(MN) | 385 | score-after-flipping-matrix | 0.751 | ye15 | Medium | 14,001 | 861 |
shortest subarray with sum at least k | class Solution:
def shortestSubarray(self, nums: List[int], k: int) -> int:
loc = {0: -1}
stack = [0] # increasing stack
ans, prefix = inf, 0
for i, x in enumerate(nums):
prefix += x
ii = bisect_right(stack, prefix - k)
if ii: ans = min(ans, i - l... | https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/1515369/Python3-binary-search | 4 | Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1], k = 1
Output: 1
Example 2:
Input: nums = [1,2], k = 4
Output: -1
Exam... | [Python3] binary search | 350 | shortest-subarray-with-sum-at-least-k | 0.261 | ye15 | Hard | 14,015 | 862 |
all nodes distance k in binary tree | class Solution:
def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
graph=defaultdict(list)
#create undirected graph
stack=[root]
while stack:
node=stack.pop()
if node==target:
targetVal=node.val
if node... | https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1606006/Easy-to-understand-Python-graph-solution | 6 | Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.
You can return the answer in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: T... | Easy to understand Python 🐍 graph solution | 439 | all-nodes-distance-k-in-binary-tree | 0.621 | InjySarhan | Medium | 14,020 | 863 |
shortest path to get all keys | class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
m, n = len(grid), len(grid[0])
ii = jj = total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == "@": ii, jj = i, j
elif grid[i][j].islower(): total += 1
... | https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/1516812/Python3-bfs | 4 | You are given an m x n grid grid where:
'.' is an empty cell.
'#' is a wall.
'@' is the starting point.
Lowercase letters represent keys.
Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid... | [Python3] bfs | 222 | shortest-path-to-get-all-keys | 0.455 | ye15 | Hard | 14,034 | 864 |
smallest subtree with all the deepest nodes | class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
@lru_cache(None)
def fn(node):
"""Return height of tree rooted at node."""
if not node: return 0
return 1 + max(fn(node.left), fn(node.right))
node = root
... | https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/940618/Python3-dfs-O(N) | 5 | Given the root of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
A node is called the deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is a tree... | [Python3] dfs O(N) | 140 | smallest-subtree-with-all-the-deepest-nodes | 0.686 | ye15 | Medium | 14,037 | 865 |
prime palindrome | class Solution:
def primePalindrome(self, N: int) -> int:
def isPrime(N):
return N > 1 and all(N % d for d in range(2, int(N**0.5)+1))
# N must be a palindrome with odd number of digits.
# The return value will have odd number of digits too.
def nextPalindrome(N)... | https://leetcode.com/problems/prime-palindrome/discuss/707393/Python3-check-next-palindrome-Prime-Palindrome | 1 | Given an integer n, return the smallest prime palindrome greater than or equal to n.
An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.
For example, 2, 3, 5, 7, 11, and 13 are all primes.
An integer is a palindrome if it reads the same from left to right as it does from... | Python3 check next palindrome - Prime Palindrome | 484 | prime-palindrome | 0.258 | r0bertz | Medium | 14,053 | 866 |
transpose matrix | class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
m,n=len(matrix),len(matrix[0])
ans = [[None] * m for _ in range(n)]
for i in range(m):
for j in range(n):
ans[j][i]=matrix[i][j]
return ans | https://leetcode.com/problems/transpose-matrix/discuss/2100098/Python-Easy-2-Approaches-one-liner | 18 | Given a 2D integer array matrix, return the transpose of matrix.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: matrix = [[1,2,3],[4,5,6]]
Ou... | Python Easy - 2 Approaches - one liner | 2,600 | transpose-matrix | 0.635 | constantine786 | Easy | 14,060 | 867 |
binary gap | class Solution:
def binaryGap(self, n: int) -> int:
if(bin(n).count('1'))==1:
return 0
c=0
x=bin(n)[2:]
for i in range(len(x)):
if(x[i]=='1'):
j=i+1
while j<len(x):
if(x[j]=='1'):
c=ma... | https://leetcode.com/problems/binary-gap/discuss/1306246/Easy-Python-Solution(100) | 2 | Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their... | Easy Python Solution(100%) | 204 | binary-gap | 0.619 | Sneh17029 | Easy | 14,111 | 868 |
reordered power of 2 | class Solution:
def reorderedPowerOf2(self, n: int) -> bool:
for i in range(32):
if Counter(str(n))==Counter(str(2**i)):
return True
return False | https://leetcode.com/problems/reordered-power-of-2/discuss/2485025/python-short-and-precise-answer | 3 | You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this so that the resulting number is a power of two.
Example 1:
Input: n = 1
Output: true
Example 2:
Input: n = 10
Output: false
Constraints:
1 ... | python short and precise answer | 90 | reordered-power-of-2 | 0.639 | benon | Medium | 14,131 | 869 |
advantage shuffle | class Solution:
def advantageCount(self, A: List[int], B: List[int]) -> List[int]:
sorted_a = sorted(A, reverse=True) # descending order
sorted_b = sorted(enumerate(B), key=lambda x: (x[1], x[0]), reverse=True) # descending order with original index
n... | https://leetcode.com/problems/advantage-shuffle/discuss/843628/Python-3-or-Greedy-Two-Pointers-or-Explanations | 3 | You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].
Return any permutation of nums1 that maximizes its advantage with respect to nums2.
Example 1:
Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11... | Python 3 | Greedy, Two Pointers | Explanations | 322 | advantage-shuffle | 0.517 | idontknoooo | Medium | 14,165 | 870 |
minimum number of refueling stops | class Solution: # Here's the plan:
#
# 1) We only need to be concerned with two quantities: the dist traveled (pos)
# and the fuel acquired (fuel). We have to refuel before pos > fuel.
#
... | https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2454099/Python3-oror-10-lines-heap-wexplanation-oror-TM%3A-90-98 | 3 | A car travels from a starting position to a destination which is target miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting posit... | Python3 || 10 lines, heap, w/explanation || T/M: 90%/ 98% | 140 | minimum-number-of-refueling-stops | 0.398 | warrenruud | Hard | 14,170 | 871 |
leaf similar trees | class Solution:
def __init__(self):
self.n = []
def dfs(self, root):
if root:
# checking if the node is leaf
if not root.left and not root.right:
# appends the leaf nodes to the list - self.n
self.n.append(root.val)
self.dfs(root.... | https://leetcode.com/problems/leaf-similar-trees/discuss/1564699/Easy-Python-Solution-or-Faster-than-98-(24ms) | 4 | Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if t... | Easy Python Solution | Faster than 98% (24ms) | 174 | leaf-similar-trees | 0.652 | the_sky_high | Easy | 14,183 | 872 |
length of longest fibonacci subsequence | class Solution:
def lenLongestFibSubseq(self, arr: List[int]) -> int:
arrset=set(arr)
res=0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
a,b,l=arr[i],arr[j],2
while(a+b in arrset):
a,b,l=b,a+b,l+1
res=... | https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/2732493/python-simple-solution-faster | 0 | A sequence x1, x2, ..., xn is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2 for all i + 2 <= n
Given a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
A subsequence is derived from another sequence ... | python simple solution faster | 8 | length-of-longest-fibonacci-subsequence | 0.486 | Raghunath_Reddy | Medium | 14,195 | 873 |
walking robot simulation | class Solution:
def robotSim(self, c: List[int], b: List[List[int]]) -> int:
x, y, d, b, M = 0, 0, 0, set([tuple(i) for i in b]), 0
for i in c:
if i < 0: d = (d + 2*i + 3)%4
else:
if d in [1,3]:
for x in range(x, x+(i+1)*(2-d), 2-d):
... | https://leetcode.com/problems/walking-robot-simulation/discuss/381840/Solution-in-Python-3 | 3 | A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:
-2: Turn left 90 degrees.
-1: Turn right 90 degrees.
1 <= k <= 9: Move forward k units, one unit at a time.
Some of the grid squares are obstacles. The ith obstacle is at grid... | Solution in Python 3 | 513 | walking-robot-simulation | 0.384 | junaidmansuri | Medium | 14,202 | 874 |
koko eating bananas | class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
k = 1
while True:
total_time = 0
for i in piles:
total_time += ceil(i / k)
if total_time > h:
k += 1
else:
return k | https://leetcode.com/problems/koko-eating-bananas/discuss/1705145/Python-BinarySearch-%2B-Optimizations-or-Explained | 20 | Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she ... | [Python] BinarySearch + Optimizations | Explained | 814 | koko-eating-bananas | 0.521 | anCoderr | Medium | 14,210 | 875 |
middle of the linked list | class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow, fast = head, head
while fast:
fast = fast.next
if fast:
fast = fast.next
else:
# fast has reached the end of linked list
... | https://leetcode.com/problems/middle-of-the-linked-list/discuss/526372/PythonJSJavaGoC%2B%2B-O(n)-by-two-pointers-90%2B-w-Diagram | 45 | Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: ... | Python/JS/Java/Go/C++ O(n) by two-pointers 90%+ [w/ Diagram] | 2,800 | middle-of-the-linked-list | 0.739 | brianchiang_tw | Easy | 14,233 | 876 |
stone game | class Solution:
def stoneGame(self, piles: List[int]) -> bool:
# Alex always win finally, no matter which step he takes first.
return True | https://leetcode.com/problems/stone-game/discuss/643412/Python-O(-n2-)-by-top-down-DP-w-Comment | 4 | Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.
Alice and Bob take ... | Python O( n^2 ) by top-down DP [w/ Comment] | 642 | stone-game | 0.697 | brianchiang_tw | Medium | 14,263 | 877 |
nth magical number | class Solution:
def nthMagicalNumber(self, n: int, a: int, b: int) -> int:
# inclusion-exclusion principle
ab = lcm(a,b)
lo, hi = 0, n*min(a, b)
while lo < hi:
mid = lo + hi >> 1
if mid//a + mid//b - mid//ab < n: lo = mid + 1
else: hi = mid
... | https://leetcode.com/problems/nth-magical-number/discuss/1545825/Python3-binary-search | 1 | A positive integer is magical if it is divisible by either a or b.
Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 1, a = 2, b = 3
Output: 2
Example 2:
Input: n = 4, a = 2, b = 3
Output: 6
Constraints:
1 <= n <=... | [Python3] binary search | 106 | nth-magical-number | 0.357 | ye15 | Hard | 14,280 | 878 |
profitable schemes | class Solution:
def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:
# A[i][j][k] = # schemes using subset of first i crimes, using <= j people, with total profit >= k
A = [[[0 for k in range(minProfit + 1)] for j in range(n + 1)] for i in range(len(profi... | https://leetcode.com/problems/profitable-schemes/discuss/2661178/Python3-DP | 0 | There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a profitable scheme any subset of these crimes that gen... | Python3 DP | 11 | profitable-schemes | 0.404 | jbradleyglenn | Hard | 14,282 | 879 |
decoded string at index | class Solution:
def decodeAtIndex(self, s: str, k: int) -> str:
lens = [0]
for c in s:
if c.isalpha():
lens.append(lens[-1] + 1)
else:
lens.append(lens[-1] * int(c))
for idx in range(len(s), 0, -1):
... | https://leetcode.com/problems/decoded-string-at-index/discuss/1585059/Python3-Solution-with-using-stack | 2 | You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
If the character read is a letter, that letter is written onto the tape.
If the character read is a digit d, the entire current tape is repeatedly written d - 1 more t... | [Python3] Solution with using stack | 217 | decoded-string-at-index | 0.283 | maosipov11 | Medium | 14,286 | 880 |
boats to save people | class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
lo = 0
hi = len(people)-1
boats = 0
while lo <= hi:
if people[lo] + people[hi] <= limit:
lo += 1
hi -= 1
else:
... | https://leetcode.com/problems/boats-to-save-people/discuss/1878155/Explained-Python-2-Pointers-Solution | 26 | You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.
Return the minimum number of boats t... | ⭐Explained Python 2 Pointers Solution | 3,400 | boats-to-save-people | 0.527 | anCoderr | Medium | 14,290 | 881 |
reachable nodes in subdivided graph | class Solution:
def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:
graph = collections.defaultdict(dict)
for s, e, n in edges: # n: subnodes in edge
graph[s][e] = n
graph[e][s] = n
seen = set() # (start, end, step)
q = col... | https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/2568608/BFS-intuitive | 0 | You are given an undirected graph (the "original graph") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is a... | BFS intuitive | 15 | reachable-nodes-in-subdivided-graph | 0.503 | scr112 | Hard | 14,319 | 882 |
projection area of 3d shapes | class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
p = len(grid)
x, y, c = [], [0]*p, 0
for i in range(p):
x.append(0)
for j in range(p):
n = grid[i][j]
if n > 0:
c += 1
if x[i] <... | https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1357263/Python3-dollarolution | 1 | You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).
We view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3-... | Python3 $olution | 105 | projection-area-of-3d-shapes | 0.708 | AakRay | Easy | 14,322 | 883 |
uncommon words from two sentences | class Solution:
def uncommonFromSentences(self, A: str, B: str) -> List[str]:
uncommon = []
def find_uncommon(s , t):
ans = []
for i in s:
if(s.count(i) == 1 and i not in t):
ans.append(i)
return ans
... | https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1219754/Python3-99-Faster-Solution | 3 | A sentence is a string of single-space separated words where each word consists only of lowercase letters.
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer i... | [Python3] 99% Faster Solution | 188 | uncommon-words-from-two-sentences | 0.66 | VoidCupboard | Easy | 14,333 | 884 |
spiral matrix iii | class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
ans = []
left, right = cStart, cStart+1
top, bottom = rStart, rStart+1
current = 1
move = 0
while current <= rows*cols:
# fill top
for... | https://leetcode.com/problems/spiral-matrix-iii/discuss/2718364/Easy-Python-Solution-Based-on-Spiral-Matrix-I-and-II | 3 | You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundar... | Easy Python Solution Based on Spiral Matrix I and II | 77 | spiral-matrix-iii | 0.732 | Naboni | Medium | 14,360 | 885 |
possible bipartition | class Solution:
def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:
dislike = [[] for _ in range(n)]
for a, b in dislikes:
dislike[a-1].append(b-1)
dislike[b-1].append(a-1)
groups = [0] * n
for p in range(n):
if groups[p] == ... | https://leetcode.com/problems/possible-bipartition/discuss/2593419/Clean-Python3-or-Bipartite-Graph-w-BFS-or-Faster-Than-99 | 2 | We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Given the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi,... | Clean Python3 | Bipartite Graph w/ BFS | Faster Than 99% | 148 | possible-bipartition | 0.485 | ryangrayson | Medium | 14,370 | 886 |
super egg drop | class Solution:
def superEggDrop(self, k: int, n: int) -> int:
@cache
def fn(n, k):
"""Return min moves given n floors and k eggs."""
if k == 1: return n
if n == 0: return 0
lo, hi = 1, n + 1
while lo < hi:
mid = ... | https://leetcode.com/problems/super-egg-drop/discuss/1468875/Python3-a-few-solutions | 4 | You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.
You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.
Each move, you may take an unbroken egg and dr... | [Python3] a few solutions | 210 | super-egg-drop | 0.272 | ye15 | Hard | 14,384 | 887 |
fair candy swap | class Solution:
def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
difference = (sum(A) - sum(B)) / 2
A = set(A)
for candy in set(B):
if difference + candy in A:
return [difference + candy, candy] | https://leetcode.com/problems/fair-candy-swap/discuss/1088075/Python.-Super-simple-solution. | 9 | Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since they are friends, they would like to e... | Python. Super simple solution. | 1,000 | fair-candy-swap | 0.605 | m-d-f | Easy | 14,388 | 888 |
construct binary tree from preorder and postorder traversal | class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
mp = {x: i for i, x in enumerate(inorder)} # relative position
root = None
stack = []
for x in preorder:
if not root: root = node = TreeNode(x)
elif mp[x] < mp[stack[-1].val]: s... | https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946726/Python3-consistent-soln-for-105-106-and-889 | 3 | Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.
If there exist multiple answers, you can return any of them.
Example 1:
Input: preorder = [1,... | [Python3] consistent soln for 105, 106 and 889 | 128 | construct-binary-tree-from-preorder-and-postorder-traversal | 0.708 | ye15 | Medium | 14,402 | 889 |
find and replace pattern | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
def helper( s ):
# dictionary
# key : character
# value : serial number in string type
char_index_dict = dict()
# giv... | https://leetcode.com/problems/find-and-replace-pattern/discuss/500786/Python-O(-nk-)-sol.-by-pattern-matching.-80%2B-With-explanation | 9 | Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.
Recall that a permutat... | Python O( nk ) sol. by pattern matching. 80%+ [ With explanation ] | 835 | find-and-replace-pattern | 0.779 | brianchiang_tw | Medium | 14,412 | 890 |
sum of subsequence widths | class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
MOD = 10**9 + 7
n = len(nums)
nums.sort()
dp = [0] * n
p = 2
temp = nums[0]
for i in range(1, n):
dp[i] = ((dp[i-1] + ((p-1)*nums[i])%MOD)%MOD - temp)%MOD
p = (2*p)%M... | https://leetcode.com/problems/sum-of-subsequence-widths/discuss/2839381/MATH-%2B-DP | 0 | The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.
A subsequence is a sequence that can be derived from ... | MATH + DP | 2 | sum-of-subsequence-widths | 0.365 | roboto7o32oo3 | Hard | 14,458 | 891 |
surface area of 3d shapes | class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
l = len(grid)
area=0
for row in range(l):
for col in range(l):
if grid[row][col]:
area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected... | https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/2329304/Simple-Python-explained | 3 | You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).
After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.
Return the total surface area ... | Simple Python explained | 153 | surface-area-of-3d-shapes | 0.633 | sunakshi132 | Easy | 14,462 | 892 |
groups of special equivalent strings | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
signature = set()
# Use pair of sorted even substring and odd substring as unique key
for idx, s in enumerate(A):
signature.add( ''.join( sorted( s[::2] ) ) + ''.join( sorted( s[1::2]... | https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/536199/Python-O(n-*-k-lg-k)-sol.-by-signature.-90%2B-w-Hint | 8 | You are given an array of strings of the same length words.
In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].
Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].
For example, words[i] = "zzxy" and wo... | Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint] | 512 | groups-of-special-equivalent-strings | 0.709 | brianchiang_tw | Medium | 14,470 | 893 |
all possible full binary trees | class Solution:
def allPossibleFBT(self, N: int) -> List[TreeNode]:
# Any full binary trees should contain odd number of nodes
# therefore, if N is even, return 0
if N % 2 == 0:
return []
# for all odd n that are less than N, store all FBTs
trees_all = collections.defaultdict(list)
#when the... | https://leetcode.com/problems/all-possible-full-binary-trees/discuss/339611/Python-solution-without-recursion-beets-100-speed | 8 | Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.
A full binary tree is a binary tree where each node has e... | Python solution without recursion, beets 100% speed | 825 | all-possible-full-binary-trees | 0.8 | KateMelnykova | Medium | 14,479 | 894 |
monotonic array | class Solution:
def isMonotonic(self, A: List[int]) -> bool:
if A[-1] < A[0]:
A = A[::-1]
for i in range(1, len(A)):
if A[i] < A[i-1]:
return False
return True | https://leetcode.com/problems/monotonic-array/discuss/501946/Python-and-Java-Solution-beat-96-and-100 | 17 | An array is monotonic if it is either monotone increasing or monotone decreasing.
An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array nums, return true if the given array is monotonic, or false oth... | Python and Java Solution beat 96% and 100% | 1,800 | monotonic-array | 0.583 | justin801514 | Easy | 14,494 | 896 |
increasing order search tree | class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
prev_node = None
def helper( node: TreeNode):
if node.right:
helper( node.right )
# prev_novde always points to next larger element for current ... | https://leetcode.com/problems/increasing-order-search-tree/discuss/526258/Python-O(n)-sol-by-DFS-90%2B-w-Diagram | 4 | Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Example 1:
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,nul... | Python O(n) sol by DFS 90%+ [w/ Diagram ] | 690 | increasing-order-search-tree | 0.785 | brianchiang_tw | Easy | 14,537 | 897 |
bitwise ors of subarrays | class Solution:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
ans=set(arr)
# each element is a subarry
one = set()
# to get the ans for the subarray of size >1
# starting from 0th element to the ending element
... | https://leetcode.com/problems/bitwise-ors-of-subarrays/discuss/1240982/python-code-with-comment-might-help-to-understand-or | 3 | Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
A subarray is a contiguous non-empty sequence of elements within an ar... | python code with comment , might help to understand | | 423 | bitwise-ors-of-subarrays | 0.369 | chikushen99 | Medium | 14,572 | 898 |
orderly queue | class Solution:
def orderlyQueue(self, s: str, k: int) -> str:
if k > 1:
return "".join(sorted(s))
res = s
for i in range(0,len(s)):
s = s[1:] + s[0]
res = min(res,s)
return res | https://leetcode.com/problems/orderly-queue/discuss/2783233/Python-Simple-and-Easy-Way-to-Solve-with-Explanation-or-99-Faster | 12 | You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
Example 1:
Input: s = "cba", k = 1
Output: "acb"
Explanation:
In the fir... | ✔️ Python Simple and Easy Way to Solve with Explanation | 99% Faster 🔥 | 577 | orderly-queue | 0.665 | pniraj657 | Hard | 14,574 | 899 |
numbers at most n given digit set | 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(firstDig... | https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1633530/Python3-NOT-BEGINNER-FRIENDLY-Explained | 8 | Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.
Return the number of positive integers that can be generated that are less than or equal... | ✔️ [Python3] NOT BEGINNER FRIENDLY, Explained | 364 | numbers-at-most-n-given-digit-set | 0.414 | artod | Hard | 14,620 | 902 |
valid permutations for di sequence | 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... | https://leetcode.com/problems/valid-permutations-for-di-sequence/discuss/1261833/Python3-top-down-dp | 1 | You are given a string s of length n where s[i] is either:
'D' means decreasing, or
'I' means increasing.
A permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i:
If s[i] == 'D', then perm[i] > perm[i + 1], and
If s[i] == 'I', then perm[i] < perm[i +... | [Python3] top-down dp | 350 | valid-permutations-for-di-sequence | 0.577 | ye15 | Hard | 14,629 | 903 |
fruit into baskets | 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]] ... | https://leetcode.com/problems/fruit-into-baskets/discuss/1414545/Python-clean-%2B-easy-to-understand-or-Sliding-Window-O(N) | 26 | You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
You onl... | Python - clean + easy to understand | Sliding Window O(N) | 1,900 | fruit-into-baskets | 0.426 | afm2 | Medium | 14,632 | 904 |
sort array by parity | 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 | https://leetcode.com/problems/sort-array-by-parity/discuss/356271/Solution-in-Python-3-(beats-~96)-(short)-(-O(1)-space-)-(-O(n)-speed-) | 21 | Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
I... | Solution in Python 3 (beats ~96%) (short) ( O(1) space ) ( O(n) speed ) | 2,300 | sort-array-by-parity | 0.757 | junaidmansuri | Easy | 14,657 | 905 |
super palindromes | class Solution:
nums = []
for i in range(1, 10**5):
odd = int(str(i)+str(i)[:-1][::-1])**2
even = int(str(i)+str(i)[::-1])**2
if str(odd) == str(odd)[::-1]:
nums.append(odd)
if str(even) == str(even)[::-1]:
... | https://leetcode.com/problems/super-palindromes/discuss/1198991/Runtime%3A-Faster-than-94.87-of-Python3-Memory-Usage-less-than-100 | 1 | Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].
Example 1:
Input: left = "4", right = "1000"
Out... | Runtime: Faster than 94.87% of Python3 Memory Usage less than 100% | 102 | super-palindromes | 0.392 | pranshusharma712 | Hard | 14,705 | 906 |
sum of subarray minimums | class Solution:
def sumSubarrayMins(self, arr: List[int]) -> int:
M = 10 ** 9 + 7
# right bound for current number as minimum
q = []
n = len(arr)
right = [n-1] * n
for i in range(n):
# must put the equal sign to one of the bound (left or right)... | https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846444/Python-3Monotonic-stack-boundry | 10 | Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.
Example 1:
Input: arr = [3,1,2,4]
Output: 17
Explanation:
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]... | [Python 3]Monotonic stack boundry | 475 | sum-of-subarray-minimums | 0.346 | chestnut890123 | Medium | 14,712 | 907 |
smallest range i | class Solution:
def smallestRangeI(self, A: List[int], K: int) -> int:
M, m = max(A), min(A)
diff, extension = M - m, 2*K
if diff <= extension:
return 0
else:
return diff - extension | https://leetcode.com/problems/smallest-range-i/discuss/535164/Python-O(n)-by-min-and-Max.-85%2B-w-Visualization | 17 | You are given an integer array nums and an integer k.
In one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.
The score of nums is the difference between the maximu... | Python O(n) by min & Max. 85%+ [w/ Visualization ] | 872 | smallest-range-i | 0.678 | brianchiang_tw | Easy | 14,741 | 908 |
snakes and ladders | class Solution:
def snakesAndLadders(self, board: List[List[int]]) -> int:
# creating a borad map to loop-up the square value
board_map = {}
i = 1
b_rev = board[::-1]
for d, r in enumerate(b_rev):
# reverse for even rows - here d is taken as direction
... | https://leetcode.com/problems/snakes-and-ladders/discuss/2491448/Python-3-oror-BFS-Solution-Using-board-mapping | 1 | You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.
You start on square 1 of the board. In each move, starting from square curr, do the following:
Choose a dest... | Python 3 || BFS Solution - Using board mapping | 161 | snakes-and-ladders | 0.409 | kevintoms | Medium | 14,756 | 909 |
smallest range ii | class Solution:
def smallestRangeII(self, A: List[int], K: int) -> int:
A.sort()
res = A[-1] - A[0]
for indx in range(0, len(A) - 1):
# assuming that A[indx] is the max val
min_val = min(A[0] + K, A[indx + 1] - K)
max_val = max(A[indx] + K, A[-1] ... | https://leetcode.com/problems/smallest-range-ii/discuss/980784/Python-3-Solution-Explained-(video-%2B-code) | 3 | You are given an integer array nums and an integer k.
For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimum score of nums after changing the values at each index.
Exa... | [Python 3] Solution Explained (video + code) | 361 | smallest-range-ii | 0.346 | spec_he123 | Medium | 14,760 | 910 |
sort an array | class Solution:
def sortArray(self, N: List[int]) -> List[int]:
L = len(N)
return [N.pop(min(range(L-i), key = lambda x: N[x])) for i in range(L)] | https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation) | 125 | Given an array of integers nums, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Explanation: After sorting the array, th... | Python 3 (Eight Sorting Algorithms) (With Explanation) | 9,200 | sort-an-array | 0.594 | junaidmansuri | Medium | 14,763 | 912 |
cat and mouse | class Solution:
def catMouseGame(self, graph: List[List[int]]) -> int:
n = len(graph)
@cache
def fn(i, m, c):
"""Return """
if i == 2*n: return 0 # tie
if m == 0: return 1 # mouse wins
if m == c: return 2 # cat wins
if i... | https://leetcode.com/problems/cat-and-mouse/discuss/1563154/Python3-dp-minimax | 0 | A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.
The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.
During ea... | [Python3] dp - minimax | 212 | cat-and-mouse | 0.351 | ye15 | Hard | 14,803 | 913 |
x of a kind in a deck of cards | class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
x = Counter(deck).values()
return reduce(gcd, x) > 1 | https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2821961/Did-you-known-about-'gcd'-function-%3AD | 0 | You are given an integer array deck where deck[i] represents the number written on the ith card.
Partition the cards into one or more groups such that:
Each group has exactly x cards where x > 1, and
All the cards in one group have the same integer written on them.
Return true if such partition is possible, or false ot... | Did you known about 'gcd' function? :D | 3 | x-of-a-kind-in-a-deck-of-cards | 0.32 | almazgimaev | Easy | 14,804 | 914 |
partition array into disjoint intervals | class Solution:
def partitionDisjoint(self, nums: List[int]) -> int:
"""
Intuition(logic) is to find two maximums.
One maximum is for left array and other maximum is for right array.
But the condition is that, the right maximum should be such that,
no element after ... | https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1359686/PYTHON-Best-solution-yet!-EXPLAINED-with-comments-to-make-life-easier.-O(n)-and-O(1) | 7 | Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:
Every element in left is less than or equal to every element in right.
left and right are non-empty.
left has the smallest possible size.
Return the length of left after such a partitioning.
Test cases are generated such t... | [PYTHON] Best solution yet! EXPLAINED with comments to make life easier. O(n) & O(1) | 352 | partition-array-into-disjoint-intervals | 0.486 | er1shivam | Medium | 14,812 | 915 |
word subsets | class Solution:
def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:
result = []
tempDict = Counter()
for w in words2:
tempDict |= Counter(w)
print(tempDict)
for w in words1:
if not tempDict - Counter(w):
r... | https://leetcode.com/problems/word-subsets/discuss/2353565/Solution-Using-Counter-in-Python | 26 | You are given two string arrays words1 and words2.
A string b is a subset of string a if every letter in b occurs in a including multiplicity.
For example, "wrr" is a subset of "warrior" but is not a subset of "world".
A string a from words1 is universal if for every string b in words2, b is a subset of a.
Return an ar... | Solution Using Counter in Python | 1,200 | word-subsets | 0.54 | AY_ | Medium | 14,831 | 916 |
reverse only letters | class Solution:
def reverseOnlyLetters(self, S: str) -> str:
S = list(S)
c = [c for c in S if c.isalpha()]
for i in range(-1,-len(S)-1,-1):
if S[i].isalpha(): S[i] = c.pop(0)
return "".join(S)
- Python 3
- Junaid Mansuri | https://leetcode.com/problems/reverse-only-letters/discuss/337853/Solution-in-Python-3 | 9 | Given a string s, reverse the string according to the following rules:
All the characters that are not English letters remain in the same position.
All the English letters (lowercase or uppercase) should be reversed.
Return s after reversing it.
Example 1:
Input: s = "ab-cd"
Output: "dc-ba"
Example 2:
Input: s = "a-b... | Solution in Python 3 | 1,100 | reverse-only-letters | 0.615 | junaidmansuri | Easy | 14,860 | 917 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.