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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
number of days between two dates | class Solution:
def daysBetweenDates(self, date1: str, date2: str) -> int:
def f_date(date): # calculates days passed since '1900-01-01'
year0 = '1900'
year1, month1, day1 = date.split('-')
days = 0
for y in range(int(year0), ... | https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1814530/Python3-Solution-from-Scratch-NOT-USING-DATETIME | 3 | Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Example 1:
Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1
Example 2:
Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15
Constraints:
The give... | Python3 Solution from Scratch - NOT USING DATETIME | 617 | number-of-days-between-two-dates | 0.476 | rmateusc | Easy | 20,467 | 1,360 |
validate binary tree nodes | class Solution:
def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
n = len(leftChild)
# tree has 2 requirements
# 1. every node has a single parent
# 2. single root (only one node has NO parent)
# 3. no cycle
# 4. ... | https://leetcode.com/problems/validate-binary-tree-nodes/discuss/1393392/Diagram-Explained-Clean-4-checks-single-parents-single-root-no-cycle-all-connected | 6 | You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.
If node i has no left child then leftChild[i] will equal -1, similarly for the right child.
Note that the nodes have no v... | Diagram Explained Clean 4 checks [single parents, single root, no cycle, all connected] | 232 | validate-binary-tree-nodes | 0.403 | yozaam | Medium | 20,474 | 1,361 |
closest divisors | class Solution:
def closestDivisors(self, num: int) -> List[int]:
for i in range(int((num+2)**0.5), 0, -1):
if not (num+1)%i: return (i, (num+1)//i)
if not (num+2)%i: return (i, (num+2)//i) | https://leetcode.com/problems/closest-divisors/discuss/517720/Python3-A-concise-solution | 1 | Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.
Return the two integers in any order.
Example 1:
Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 ... | [Python3] A concise solution | 50 | closest-divisors | 0.599 | ye15 | Medium | 20,490 | 1,362 |
largest multiple of three | class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
def dump(r: int) -> str:
if r:
for i in range(3):
idx = 3 * i + r
if counts[idx]:
counts[idx] -= 1
break
... | https://leetcode.com/problems/largest-multiple-of-three/discuss/519005/Clean-Python-3-counting-sort-O(N)O(1)-timespace-100 | 2 | Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not cont... | Clean Python 3, counting sort O(N)/O(1) time/space, 100% | 268 | largest-multiple-of-three | 0.333 | lenchen1112 | Hard | 20,499 | 1,363 |
how many numbers are smaller than the current number | class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
a=[]
numi = sorted(nums)
for i in range(0,len(nums)):
a.append(numi.index(nums[i]))
return a | https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/613343/Simple-Python-Solution-72ms-and-13.8-MB-EXPLAINED | 10 | Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[... | Simple Python Solution [72ms and 13.8 MB] EXPLAINED | 849 | how-many-numbers-are-smaller-than-the-current-number | 0.867 | code_zero | Easy | 20,506 | 1,365 |
rank teams by votes | class Solution:
def rankTeams(self, votes: List[str]) -> str:
teamVotes = collections.defaultdict(lambda: [0] * 26)
for vote in votes:
for pos, team in enumerate(vote):
teamVotes[team][pos] += 1
return ''.join(sorted(teamVotes.keys(), reverse=True,
... | https://leetcode.com/problems/rank-teams-by-votes/discuss/2129031/python-3-oror-simple-O(n)O(1)-solution | 5 | In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie ag... | python 3 || simple O(n)/O(1) solution | 465 | rank-teams-by-votes | 0.586 | dereky4 | Medium | 20,554 | 1,366 |
linked list in binary tree | class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
#build longest prefix-suffix array
pattern, lps = [head.val], [0] #longest prefix-suffix array
j = 0
while head.next:
head = head.next
pattern.append(head.val)
... | https://leetcode.com/problems/linked-list-in-binary-tree/discuss/525814/Python3-A-naive-dp-approach | 1 | Given a binary tree root and a linked list with head as the first node.
Return True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.... | [Python3] A naive dp approach | 96 | linked-list-in-binary-tree | 0.435 | ye15 | Medium | 20,565 | 1,367 |
minimum cost to make at least one valid path in a grid | class Solution:
def minCost(self, grid: List[List[int]]) -> int:
graph = {}
m, n = len(grid), len(grid[0])
def addEdges(i, j):
graph[(i, j)] = {}
neighbors = [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
for each in neighbors:
x... | https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/1504913/Python-or-Template-or-0-1-BFS-vs-Dijkstra-or-Explanation | 3 | Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:
1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])
2 which means go to the cell to the left. (i.e go from grid[i][j] to gr... | Python | Template | 0-1 BFS vs Dijkstra | Explanation | 290 | minimum-cost-to-make-at-least-one-valid-path-in-a-grid | 0.613 | detective_dp | Hard | 20,573 | 1,368 |
increasing decreasing string | class Solution:
def sortString(self, s: str) -> str:
s = list(s)
# Big S: O(n)
result = []
# Logic is capture distinct char with set
# Remove found char from initial string
# Big O: O(n)
while len(s) > 0:
# Big O: O(n log n) Spac... | https://leetcode.com/problems/increasing-decreasing-string/discuss/543172/Python-3-Using-Set-and-Sort-with-commentary | 11 | You are given a string s. Reorder the string using the following algorithm:
Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the larg... | [Python 3] Using Set and Sort with commentary | 966 | increasing-decreasing-string | 0.774 | dentedghost | Easy | 20,582 | 1,370 |
find the longest substring containing vowels in even counts | class Solution:
def findTheLongestSubstring(self, s: str) -> int:
ans = mask = 0
seen = {0: -1}
for i, c in enumerate(s):
if c in "aeiou":
mask ^= 1 << ("aeiou".find(c))
if mask in seen: ans = max(ans, i - seen[mask])
seen.setdefault(mask... | https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1125562/Python3-bitmask | 4 | Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of th... | [Python3] bitmask | 148 | find-the-longest-substring-containing-vowels-in-even-counts | 0.629 | ye15 | Medium | 20,609 | 1,371 |
longest zigzag path in a binary tree | class Solution:
def longestZigZag(self, root: Optional[TreeNode]) -> int:
LEFT = 0
RIGHT = 1
stack = []
if root.left:
stack.append((root.left, LEFT, 1))
if root.right:
stack.append((root.right, RIGHT, 1))
long... | https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2559539/Python3-Iterative-DFS-Using-Stack-99-time-91-space-O(N)-time-O(N)-space | 0 | You are given the root of a binary tree.
A ZigZag path for a binary tree is defined as follow:
Choose any node in the binary tree and a direction (right or left).
If the current direction is right, move to the right child of the current node; otherwise, move to the left child.
Change the direction from right to left or... | [Python3] Iterative DFS Using Stack - 99% time 91% space, - O(N) time O(N) space | 35 | longest-zigzag-path-in-a-binary-tree | 0.598 | rt500 | Medium | 20,615 | 1,372 |
maximum sum bst in binary tree | class Solution:
def maxSumBST(self, root: TreeNode) -> int:
tot = -math.inf
def dfs(node):
nonlocal tot
if not node:
return 0, math.inf, -math.inf
l_res, l_min, l_max = dfs(node.left)
r_res, r_min, r_max = dfs(node.right)
# if main... | https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/1377976/Python-O(n)-short-readable-solution | 1 | Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's ... | Python O(n), short readable solution | 170 | maximum-sum-bst-in-binary-tree | 0.392 | arsamigullin | Hard | 20,624 | 1,373 |
generate a string with characters that have odd counts | class Solution:
def generateTheString(self, n: int) -> str:
a="a"
b="b"
if n%2==0:
return (((n-1)*a)+b)
return (n*a) | https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts/discuss/1232027/Easy-code-in-python-with-explanation. | 2 | Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
Example 1:
Input: n = 4
Output: "pppz"
Explanation: "pppz" is a vali... | Easy code in python with explanation. | 183 | generate-a-string-with-characters-that-have-odd-counts | 0.776 | souravsingpardeshi | Easy | 20,630 | 1,374 |
number of times binary string is prefix aligned | class Solution:
def numTimesAllBlue(self, light: List[int]) -> int:
max = count = 0
for i in range(len(light)):
if max < light[i]:
max = light[i]
if max == i + 1:
count += 1
return count | https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/1330283/Python3-solution-O(n)-time-and-O(1)-space-complexity | 4 | You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step.
A binary string i... | Python3 solution O(n) time and O(1) space complexity | 312 | number-of-times-binary-string-is-prefix-aligned | 0.659 | EklavyaJoshi | Medium | 20,652 | 1,375 |
time needed to inform all employees | class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
def find(i):
if manager[i] != -1:
informTime[i] += find(manager[i])
manager[i] = -1
return informTime[i]
return max(map(find, range(n... | https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1206574/Python3-Path-compression-(Clean-code-beats-99) | 10 | A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.
Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination r... | [Python3] Path compression (Clean code, beats 99%) | 351 | time-needed-to-inform-all-employees | 0.584 | SPark9625 | Medium | 20,658 | 1,376 |
frog position after t seconds | class Solution:
def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
if target==1:
if t>=1 and len(edges)>=1:
return 0
adj = collections.defaultdict(list)
for i in edges:
adj[min(i[0],i[1])].append(max(i[1],i[0]))
def traversal(curr, target,t):
if curr==target:
... | https://leetcode.com/problems/frog-position-after-t-seconds/discuss/1092590/Python-basic-DFS-from-a-new-grad | 1 | Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it... | Python basic DFS from a new grad | 142 | frog-position-after-t-seconds | 0.361 | yb233 | Hard | 20,681 | 1,377 |
find a corresponding node of a binary tree in a clone of that tree | class Solution:
def getTargetCopy(self, node1: TreeNode, node2: TreeNode, target: TreeNode) -> TreeNode:
if not node1 or target == node1: # if node1 is null, node2 will also be null
return node2
return self.getTargetCopy(node1.left, node2.left, target) or self.getTa... | https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046151/Python-Simple-2-approaches-Recursion(3-liner)-and-Morris | 20 | Given two binary trees original and cloned and given a reference to a node target in the original tree.
The cloned tree is a copy of the original tree.
Return a reference to the same node in the cloned tree.
Note that you are not allowed to change any of the two trees or the target node and the answer must be a referen... | Python Simple 2 approaches - Recursion(3 liner) and Morris | 1,900 | find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree | 0.87 | constantine786 | Easy | 20,688 | 1,379 |
lucky numbers in a matrix | class Solution:
def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:
rmin = [min(x) for x in matrix]
cmax = [max(x) for x in zip(*matrix)]
return [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[0])) if rmin[i] == cmax[j]] | https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/539748/Python3-store-row-min-and-column-max | 9 | Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
Example 1:
Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]
Output: [15]
Explanation: 15 is the only lucky ... | [Python3] store row min & column max | 1,500 | lucky-numbers-in-a-matrix | 0.705 | ye15 | Easy | 20,716 | 1,380 |
balance a binary search tree | class Solution:
def balanceBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
"""inorder depth-first traverse bst"""
if not node: return
dfs(node.left)
value.append(node.val)
dfs(node.right)
value = [] #collect values
... | https://leetcode.com/problems/balance-a-binary-search-tree/discuss/539780/Python3-collect-values-and-reconstruct-bst-recursively | 6 | Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.
Example 1:
Input: root = [1,null,2,null,3,null,4,n... | [Python3] collect values & reconstruct bst recursively | 363 | balance-a-binary-search-tree | 0.807 | ye15 | Medium | 20,751 | 1,382 |
maximum performance of a team | class Solution:
def maxPerformance_simple(self, n, speed, efficiency):
people = sorted(zip(speed, efficiency), key=lambda x: -x[1])
result, sum_speed = 0, 0
for s, e in people:
sum_speed += s
result = max(result, sum_speed * e)
... | https://leetcode.com/problems/maximum-performance-of-a-team/discuss/741822/Met-this-problem-in-my-interview!!!-(Python3-greedy-with-heap) | 58 | You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.
Choose at most k different engineers out of the n engineers to form a team with the... | Met this problem in my interview!!! (Python3 greedy with heap) | 2,500 | maximum-performance-of-a-team | 0.489 | dashidhy | Hard | 20,764 | 1,383 |
find the distance value between two arrays | class Solution:
def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:
n = len(arr2)
arr2.sort()
res = 0
for num in arr1:
low, high = 0, n - 1
while low <= high:
mid = (low + high) // 2
if abs(... | https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2015283/python-3-oror-simple-binary-search-solution | 4 | Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.
The distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.
Example 1:
Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
Output: 2
Exp... | python 3 || simple binary search solution | 298 | find-the-distance-value-between-two-arrays | 0.654 | dereky4 | Easy | 20,782 | 1,385 |
cinema seat allocation | class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
seats = {}
for i, j in reservedSeats:
if i not in seats: seats[i] = 0
seats[i] |= 1 << j-1
ans = 2 * (n - len(seats))
for v in seats.values():
... | https://leetcode.com/problems/cinema-seat-allocation/discuss/1124736/Python3-bitmask | 3 | A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already... | [Python3] bitmask | 256 | cinema-seat-allocation | 0.409 | ye15 | Medium | 20,818 | 1,386 |
sort integers by the power value | class Solution:
def getpower(self,num):
p=0
while(num!=1):
if num%2==0:
num=num//2
else:
num=(3*num)+1
p+=1
return p
def getKth(self, lo: int, hi: int, k: int) -> int:
... | https://leetcode.com/problems/sort-integers-by-the-power-value/discuss/1597631/Python-using-sorted-function | 1 | The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:
if x is even then x = x / 2
if x is odd then x = 3 * x + 1
For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).
Given three integers lo... | Python using sorted function | 118 | sort-integers-by-the-power-value | 0.7 | PrimeOp | Medium | 20,825 | 1,387 |
pizza with 3n slices | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
@cache
def fn(i, k, first):
"""Return max sum of k pieces from slices[i:]."""
if k == 0: return 0
if i >= len(slices) or first and i == len(slices)-1: return -inf
if i == 0:... | https://leetcode.com/problems/pizza-with-3n-slices/discuss/1124752/Python3-top-down-dp | 2 | There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:
You will pick any pizza slice.
Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
Your friend Bob will pick the next slice in the clockwise direction of your pick.
Repeat unt... | [Python3] top-down dp | 236 | pizza-with-3n-slices | 0.501 | ye15 | Hard | 20,852 | 1,388 |
create target array in the given order | class Solution:
def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
ans = []
for i in range(len(nums)):
ans.insert(index[i] , nums[i])
return ans | https://leetcode.com/problems/create-target-array-in-the-given-order/discuss/1163965/Python3-Simple-Solution | 5 | Given two arrays of integers nums and index. Your task is to create target array under the following rules:
Initially target array is empty.
From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
Repeat the previous step until there are no elements to read in nums and ... | [Python3] Simple Solution | 252 | create-target-array-in-the-given-order | 0.859 | VoidCupboard | Easy | 20,857 | 1,389 |
four divisors | class Solution:
def sumFourDivisors(self, nums: List[int]) -> int:
res = 0
for num in nums:
divisor = set()
for i in range(1, floor(sqrt(num)) + 1):
if num % i == 0:
divisor.add(num//i)
divisor.add(i)
if... | https://leetcode.com/problems/four-divisors/discuss/547308/Python3-Short-Easy-Solution | 22 | Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.
Example 1:
Input: nums = [21,4,7]
Output: 32
Explanation:
21 has 4 divisors: 1, 3, 7, 21
4 has 3 divisors: 1, 2, 4
7 has 2 divisors: 1, 7
The answ... | [Python3] Short Easy Solution | 2,500 | four-divisors | 0.413 | localhostghost | Medium | 20,910 | 1,390 |
check if there is a valid path in a grid | class Solution:
directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]
streetDirections = {
1: [1, 3],
2: [0, 2],
3: [2, 3],
4: [1, 2],
5: [0, 3],
6: [0, 1]
}
def hasValidPath(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
def dfs(... | https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/discuss/635713/Python3-dfs-solution-Check-if-There-is-a-Valid-Path-in-a-Grid | 2 | You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:
1 which means a street connecting the left cell and the right cell.
2 which means a street connecting the upper cell and the lower cell.
3 which means a street connecting the left cell and the lower cell.
4 which means ... | Python3 dfs solution - Check if There is a Valid Path in a Grid | 391 | check-if-there-is-a-valid-path-in-a-grid | 0.472 | r0bertz | Medium | 20,912 | 1,391 |
longest happy prefix | class Solution:
def longestPrefix(self, s: str) -> str:
n = [0] + [None] * (len(s) - 1)
for i in range(1, len(s)):
k = n[i - 1] # trying length k + 1
while (k > 0) and (s[i] != s[k]):
k = n[k - 1]
if s[i] == s[k]:
k += 1
... | https://leetcode.com/problems/longest-happy-prefix/discuss/2814375/Dynamic-programming-solution | 1 | A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s, return the longest happy prefix of s. Return an empty string "" if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev... | Dynamic programming solution | 24 | longest-happy-prefix | 0.45 | aknyazev87 | Hard | 20,919 | 1,392 |
find lucky integer in an array | class Solution:
def findLucky(self, arr: List[int]) -> int:
charMap = {}
for i in arr:
charMap[i] = 1 + charMap.get(i, 0)
res = []
for i in charMap:
if charMap[i] == i:
res.append(i)
... | https://leetcode.com/problems/find-lucky-integer-in-an-array/discuss/2103066/PYTHON-or-Simple-python-solution | 1 | Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.
Return the largest lucky integer in the array. If there is no lucky integer return -1.
Example 1:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[... | PYTHON | Simple python solution | 145 | find-lucky-integer-in-an-array | 0.636 | shreeruparel | Easy | 20,928 | 1,394 |
count number of teams | class Solution:
def numTeams(self, rating: List[int]) -> int:
dp = [[1, 0, 0] for i in range(len(rating))]
for i in range(1, len(rating)):
for j in range(i):
if rating[i] > rating[j]:
dp[i][1] += dp[j][0]
dp[i][2] ... | https://leetcode.com/problems/count-number-of-teams/discuss/1465532/Python-or-O(n2)-or-Slow-but-very-easy-to-understand-or-Explanation | 5 | There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).
A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[... | Python | O(n^2) | Slow but very easy to understand | Explanation | 595 | count-number-of-teams | 0.68 | detective_dp | Medium | 20,963 | 1,395 |
find all good strings | class Solution:
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
lps = [0]
k = 0
for i in range(1, len(evil)):
while k and evil[k] != evil[i]: k = lps[k-1]
if evil[k] == evil[i]: k += 1
lps.append(k)
@cache
... | https://leetcode.com/problems/find-all-good-strings/discuss/1133347/Python3-dp-and-kmp-...-finally | 3 | Given the strings s1 and s2 of size n and the string evil, return the number of good strings.
A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, retur... | [Python3] dp & kmp ... finally | 351 | find-all-good-strings | 0.422 | ye15 | Hard | 20,973 | 1,397 |
count largest group | class Solution:
def countLargestGroup(self, n: int) -> int:
dp = {0: 0}
counts = [0] * (4 * 9)
for i in range(1, n + 1):
quotient, reminder = divmod(i, 10)
dp[i] = reminder + dp[quotient]
counts[dp[i] - 1] += 1
return counts.count(max(counts)) | https://leetcode.com/problems/count-largest-group/discuss/660765/Python-DP-O(N)-99100 | 43 | You are given an integer n.
Each number from 1 to n is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
Example 1:
Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
[1,10], [2,11], ... | Python DP O(N) 99%/100% | 2,000 | count-largest-group | 0.672 | xshoan | Easy | 20,975 | 1,399 |
construct k palindrome strings | class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if k > len(s):
return False
dic = {}
for i in s:
if i not in dic:
dic[i] = 1
else:
dic[i] += 1
c = 0
for i in dic.values():
... | https://leetcode.com/problems/construct-k-palindrome-strings/discuss/1806250/Python-Solution | 1 | Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.
Example 1:
Input: s = "annabelle", k = 2
Output: true
Explanation: You can construct two palindromes using all characters in s.
Some possible constructions "anna" + "elble", "anb... | Python Solution | 91 | construct-k-palindrome-strings | 0.632 | MS1301 | Medium | 20,995 | 1,400 |
circle and rectangle overlapping | class Solution:
def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:
x = 0 if x1 <= x_center <= x2 else min(abs(x1-x_center), abs(x2-x_center))
y = 0 if y1 <= y_center <= y2 else min(abs(y1-y_center), abs(y2-y_center))
return x**2 + y... | https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/639682/Python3-two-solutions-Circle-and-Rectangle-Overlapping | 2 | You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.
Return true if the circle and rectangle are overlapped ... | Python3 two solutions - Circle and Rectangle Overlapping | 386 | circle-and-rectangle-overlapping | 0.442 | r0bertz | Medium | 21,001 | 1,401 |
reducing dishes | class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort(reverse=True)
maxSatisfaction = dishSum = 0
for dish in satisfaction:
dishSum += dish
if dishSum <= 0:
break
maxSatisfaction += dishSum
... | https://leetcode.com/problems/reducing-dishes/discuss/2152786/python-3-oror-simple-sorting-solution | 1 | A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].
Return the maximum sum of like-time... | python 3 || simple sorting solution | 102 | reducing-dishes | 0.72 | dereky4 | Hard | 21,005 | 1,402 |
minimum subsequence in non increasing order | class Solution:
def minSubsequence(self, nums: List[int]) -> List[int]:
nums.sort()
l = []
while sum(l) <= sum(nums):
l.append(nums.pop())
return l | https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1041468/Python3-simple-solution | 9 | Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum... | Python3 simple solution | 297 | minimum-subsequence-in-non-increasing-order | 0.721 | EklavyaJoshi | Easy | 21,020 | 1,403 |
number of steps to reduce a number in binary representation to one | class Solution:
def numSteps(self, s):
return len(s) + s.rstrip('0').count('0') + 2 * (s.count('1') != 1) - 1 | https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/2809472/Python3-Solution-or-One-Line | 1 | Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:
If the current number is even, you have to divide it by 2.
If the current number is odd, you have to add 1 to it.
It is guaranteed that you can always reach one for all test cases.
Exam... | ✔ Python3 Solution | One Line | 98 | number-of-steps-to-reduce-a-number-in-binary-representation-to-one | 0.522 | satyam2001 | Medium | 21,056 | 1,404 |
longest happy string | class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
count = collections.Counter({'a':a, 'b':b, 'c':c})
res = ['#']
while True:
(a1, _), (a2, _) = count.most_common(2)
if a1 == res[-1] == res[-2]:
a1 = a2
... | https://leetcode.com/problems/longest-happy-string/discuss/1226968/Python-9-line-greedy-solution-by-using-Counter | 5 | A string s is called happy if it satisfies the following conditions:
s only contains the letters 'a', 'b', and 'c'.
s does not contain any of "aaa", "bbb", or "ccc" as a substring.
s contains at most a occurrences of the letter 'a'.
s contains at most b occurrences of the letter 'b'.
s contains at most c occurrences of... | [Python] 9-line greedy solution by using Counter | 524 | longest-happy-string | 0.574 | licpotis | Medium | 21,069 | 1,405 |
stone game iii | class Solution(object):
def stoneGameIII(self, stoneValue):
"""
:type stoneValue: List[int]
:rtype: str
"""
dp = [0 for _ in range(len(stoneValue))]
if len(dp) >= 1:
dp[-1] = stoneValue[-1]
if len(dp) >= 2:
dp[-2] = max(stoneVa... | https://leetcode.com/problems/stone-game-iii/discuss/815655/Python3-beats-93-DP | 4 | Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first... | Python3 beats 93% DP | 166 | stone-game-iii | 0.596 | ethuoaiesec | Hard | 21,082 | 1,406 |
string matching in an array | class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
def add(word: str):
node = trie
for c in word:
node = node.setdefault(c, {})
def get(word: str) -> bool:
node = trie
for c in word:
if (node := no... | https://leetcode.com/problems/string-matching-in-an-array/discuss/575147/Clean-Python-3-suffix-trie-O(NlogN-%2B-N-*-S2) | 48 | Given an array of string words, return all strings in words that is a substring of another word. You can return the answer in any order.
A substring is a contiguous sequence of characters within a string
Example 1:
Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of... | Clean Python 3, suffix trie O(NlogN + N * S^2) | 5,500 | string-matching-in-an-array | 0.639 | lenchen1112 | Easy | 21,089 | 1,408 |
queries on a permutation with key | class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
permuteArr=[i for i in range(1,m+1)]
query_len=len(queries)
answer=[]
left,right=[],[]
for query in range(query_len):
index=permuteArr.index(queries[query])
answer.appen... | https://leetcode.com/problems/queries-on-a-permutation-with-key/discuss/1702309/Understandable-code-for-beginners-in-python!!! | 1 | Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) and th... | Understandable code for beginners in python!!! | 46 | queries-on-a-permutation-with-key | 0.833 | kabiland | Medium | 21,128 | 1,409 |
html entity parser | class Solution:
def entityParser(self, text: str) -> str:
html_symbol = [ '&quot;', '&apos;', '&gt;', '&lt;', '&frasl;', '&amp;']
formal_symbol = [ '"', "'", '>', '<', '/', '&']
for html_sym, formal_sym in zip(html_symbol, formal_symbol):... | https://leetcode.com/problems/html-entity-parser/discuss/575248/Python-sol-by-replace-and-regex.-85%2B-w-Hint | 11 | HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
The special characters and their entities for HTML are:
Quotation Mark: the entity is " and symbol character is ".
Single Quote Mark: the entity is ' and symbol chara... | Python sol by replace and regex. 85%+ [w/ Hint ] | 740 | html-entity-parser | 0.52 | brianchiang_tw | Medium | 21,141 | 1,410 |
number of ways to paint n × 3 grid | class Solution:
def numOfWays(self, n: int) -> int:
mod = 10 ** 9 + 7
two_color, three_color = 6, 6
for _ in range(n - 1):
two_color, three_color = (two_color * 3 + three_color * 2) % mod, (two_color * 2 + three_color * 2) % mod
return (two_color + three_color) % mod | https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/1648004/dynamic-programming-32ms-beats-99.44-in-Python | 2 | You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).
Given n the number of rows of the grid,... | dynamic programming, 32ms, beats 99.44% in Python | 205 | number-of-ways-to-paint-n-3-grid | 0.623 | kryuki | Hard | 21,149 | 1,411 |
minimum value to get positive step by step sum | class Solution:
def minStartValue(self, nums: List[int]) -> int:
for i in range(1, len(nums)): nums[i] = nums[i] + nums[i - 1]
return 1 if min(nums) >= 1 else abs(min(nums)) + 1 | https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/discuss/1431774/2-Lines-Easy-Python-Solution | 5 | Given an array of integers nums, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.
Example 1:
Input: n... | 2 Lines Easy Python Solution | 305 | minimum-value-to-get-positive-step-by-step-sum | 0.68 | caffreyu | Easy | 21,154 | 1,413 |
find the minimum number of fibonacci numbers whose sum is k | class Solution:
def findMinFibonacciNumbers(self, n: int) -> int:
def check(z):
key = [1,1]
while key[-1] + key[-2] <= z:
key.append(key[-1]+key[-2])
print(key,z)
if z in key:
return 1
return 1 + check(z-key[-1])
... | https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/discuss/1341772/Python3-easy-solution-using-recursion | 1 | Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 for n > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that... | Python3 easy solution using recursion | 333 | find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k | 0.654 | EklavyaJoshi | Medium | 21,193 | 1,414 |
the k th lexicographical string of all happy strings of length n | class Solution:
def getHappyString(self, n: int, k: int) -> str:
char = ["a", "b", "c"]
# Edge case, n = 1
if n == 1: return char[k - 1] if k <= 3 else ""
# There will be $part$ number of strings starting with each character (a, b, c)
part = 2 ** ... | https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1420200/Python3-or-Ez-for-loop-solves-ALL!-With-detailed-comments-and-graphical-examples | 2 | A happy string is a string that:
consists only of letters of the set ['a', 'b', 'c'].
s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two inte... | Python3 | Ez for loop solves ALL! With detailed comments and graphical examples | 73 | the-k-th-lexicographical-string-of-all-happy-strings-of-length-n | 0.721 | caffreyu | Medium | 21,202 | 1,415 |
restore the array | class Solution(object):
def numberOfArrays(self, s, k):
n=len(s)
new=[0]*n
new[0]=1
m=len(str(k))
for i in range(1,n):
for j in range(max(0,i-m+1),i+1):
if s[j]!="0" and int(s[j:i+1])<=k:
if j==0:
new[i]=... | https://leetcode.com/problems/restore-the-array/discuss/1165871/python-or-simple-dp | 1 | A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.
Given the string s and the integer k, return the number o... | python | simple dp | 185 | restore-the-array | 0.388 | heisenbarg | Hard | 21,218 | 1,416 |
reformat the string | class Solution:
def reformat(self, s: str) -> str:
nums, chars = [], []
[(chars, nums)[char.isdigit()].append(str(char)) for char in s]
nums_len, chars_len = len(nums), len(chars)
if 2 > nums_len - chars_len > -2:
a, b = ((chars, nums), (nums, chars))[nums_len > chars_len... | https://leetcode.com/problems/reformat-the-string/discuss/1863653/Python3-Solution | 1 | You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Retu... | Python3 Solution | 62 | reformat-the-string | 0.556 | hgalytoby | Easy | 21,220 | 1,417 |
display table of food orders in a restaurant | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
order = defaultdict(lambda : {})
foods = set()
ids = []
for i , t , name in orders:
t = int(t)
if(name in order[t]):... | https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1236252/Python3-Brute-Force-Solution | 3 | Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaurant's ... | [Python3] Brute Force Solution | 163 | display-table-of-food-orders-in-a-restaurant | 0.738 | VoidCupboard | Medium | 21,241 | 1,418 |
minimum number of frogs croaking | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
cnt, s = collections.defaultdict(int), 'croak'
ans, cur, d = 0, 0, {c:i for i, c in enumerate(s)} # d: mapping for letter & its index
for letter in croakOfFrogs: # iterate over the string
... | https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/1200924/Python-3-or-Greedy-Simulation-Clean-code-or-Explanantion | 6 | You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
A valid "croak" means a frog is ... | Python 3 | Greedy, Simulation, Clean code | Explanantion | 384 | minimum-number-of-frogs-croaking | 0.501 | idontknoooo | Medium | 21,250 | 1,419 |
build array where you can find the maximum exactly k comparisons | class Solution:
def numOfArrays(self, n: int, m: int, K: int) -> int:
MOD = 10 ** 9 + 7
# f[i][j][k] cumulative sum, first i elements, current max less than or equal to j, k more maximum to fill
f = [[[0 for _ in range(K + 1)] for _ in range(m + 1)] for _ in range(n + 1)]
for j in ra... | https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/2785539/Python-DP-cleaner-than-most-answers | 0 | You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
arr has exactly n integers.
1 <= arr[i] <= m where (0 <= i < n).
After applying the mentioned algorithm to arr, the v... | [Python] DP cleaner than most answers | 4 | build-array-where-you-can-find-the-maximum-exactly-k-comparisons | 0.635 | chaosrw | Hard | 21,256 | 1,420 |
maximum score after splitting a string | class Solution:
def maxScore(self, s: str) -> int:
zeros = ones = 0
ans = float("-inf")
for i in range(len(s)-1):
if s[i] == "0": zeros += 1
else: ones -= 1
ans = max(ans, zeros + ones)
return ans - ones + (1 if s[-1] == "1" else ... | https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/597944/Python3-linear-scan | 5 | Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
Example 1:
Input: s = "011101... | [Python3] linear scan | 482 | maximum-score-after-splitting-a-string | 0.578 | ye15 | Easy | 21,260 | 1,422 |
maximum points you can obtain from cards | class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
n = len(cardPoints)
total = sum(cardPoints)
remaining_length = n - k
subarray_sum = sum(cardPoints[:remaining_length])
min_sum = subarray_sum
for i in range(remaining_length, n... | https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2197728/Python3-O(n)-Clean-and-Simple-Sliding-Window-Solution | 38 | There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.
Your score is the sum of the points of the cards you have... | [Python3] O(n) - Clean and Simple Sliding Window Solution | 2,200 | maximum-points-you-can-obtain-from-cards | 0.523 | TLDRAlgos | Medium | 21,278 | 1,423 |
diagonal traverse ii | class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
d = collections.defaultdict(list)
for i in range(len(nums)):
for j in range(len(nums[i])):
d[(i+j)].append(nums[i][j])
ans = []
for key in d:
... | https://leetcode.com/problems/diagonal-traverse-ii/discuss/1866412/Python-easy-to-read-and-understand-or-hashmap | 0 | Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.
Example 1:
Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,4,2,7,5,3,8,6,9]
Example 2:
Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
Const... | Python easy to read and understand | hashmap | 58 | diagonal-traverse-ii | 0.504 | sanial2001 | Medium | 21,330 | 1,424 |
constrained subsequence sum | class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [0]*n
q = deque()
for i, num in enumerate(nums):
if i > k and q[0] == dp[i-k-1]:
q.popleft()
dp[i] = max(q[0] if q else 0, 0)+num
w... | https://leetcode.com/problems/constrained-subsequence-sum/discuss/2672473/Python-or-Deque | 0 | Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of element... | Python | Deque | 6 | constrained-subsequence-sum | 0.474 | jainsiddharth99 | Hard | 21,332 | 1,425 |
kids with the greatest number of candies | class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
return [x+extraCandies >= max(candies) for x in candies] | https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/discuss/2269844/Python-3-ONE-LINER | 6 | There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.
Return a boolean array result of length n, where result[i] is true if, after giving the ith kid ... | Python 3 [ONE LINER] | 143 | kids-with-the-greatest-number-of-candies | 0.875 | omkarxpatel | Easy | 21,339 | 1,431 |
max difference you can get from changing an integer | class Solution:
def maxDiff(self, num: int) -> int:
num = str(num)
i = next((i for i in range(len(num)) if num[i] != "9"), -1) #first non-9 digit
hi = int(num.replace(num[i], "9"))
if num[0] != "1": lo = int(num.replace(num[0], "1"))
else:
i = n... | https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/discuss/608687/Python3-scan-through-digits | 4 | You are given an integer num. You will apply the following steps exactly two times:
Pick a digit x (0 <= x <= 9).
Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
Replace all the occurrences of x in the decimal representation of num by y.
The new integer cannot have any leading zeros, also the new int... | [Python3] scan through digits | 151 | max-difference-you-can-get-from-changing-an-integer | 0.429 | ye15 | Medium | 21,387 | 1,432 |
check if a string can break another string | class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
return all(a<=b for a,b in zip(min(sorted(s1),sorted(s2)),max(sorted(s1),sorted(s2))))``` | https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/1415509/ONLY-CODE-N-log-N-sort-and-compare-%3A)-clean-3-liner-and-then-1-liner | 1 | Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.
A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.
Example 1:
In... | [ONLY CODE] N log N sort and compare :) clean 3 liner and then 1 liner | 60 | check-if-a-string-can-break-another-string | 0.689 | yozaam | Medium | 21,392 | 1,433 |
number of ways to wear different hats to each other | class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
n = len(hats)
h2p = collections.defaultdict(list)
for p, hs in enumerate(hats):
for h in hs:
h2p[h].append(p)
full_mask = (1 << n) - 1
mod = 10**9 + 7
@functools.lru_cache(... | https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/608721/Python-dp-with-bit-mask-memorization | 2 | There are n people and 40 types of hats labeled from 1 to 40.
Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.
Return the number of ways that the n people wear different hats to each other.
Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: ha... | Python dp with bit mask memorization | 246 | number-of-ways-to-wear-different-hats-to-each-other | 0.429 | ChelseaChenC | Hard | 21,407 | 1,434 |
destination city | class Solution:
def destCity(self, paths: List[List[str]]) -> str:
lst=[]
arr=[]
for i in paths:
lst.append(i[0])
arr.append(i[1])
ptr=set(lst)
ptr2=set(arr)
return list(ptr2-ptr)[0] | https://leetcode.com/problems/destination-city/discuss/1664716/98-faster-easy-python-solution-based-on-question-no.-997 | 9 | You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactl... | 98% faster easy python solution based on question no. 997 | 437 | destination-city | 0.776 | amannarayansingh10 | Easy | 21,411 | 1,436 |
check if all 1s are at least length k places away | class Solution:
def kLengthApart(self, nums: List[int], k: int) -> bool:
indices = [i for i, x in enumerate(nums) if x == 1]
if not indices:
return True
for i in range(1, len(indices)):
if indices[i] - indices[i-1] < k + 1:
return False
return ... | https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/609823/Python-O(n)-Easy-(For-Loop-List-Comprehension) | 2 | Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.
Example 1:
Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
Example 2:
Input: nums = [1,0,0,1,0,1], k = 2
O... | Python O(n) Easy (For Loop, List Comprehension) | 180 | check-if-all-1s-are-at-least-length-k-places-away | 0.591 | sonaksh | Easy | 21,442 | 1,437 |
longest continuous subarray with absolute diff less than or equal to limit | class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
#[8,2,4,3,6,11] limit = 5
#if the new number is greater than max this becomes new max,
#if new number is less than min this becomes new min
#if max - min exceeds limit, pop the left most element -> if the... | https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/2798749/nlogn-solution-by-this-dude | 0 | Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
Example 1:
Input: nums = [8,2,4,7], limit = 4
Output: 2
Explanation: All subarrays are:
[8] with maximum... | nlogn solution by this dude | 6 | longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit | 0.481 | ariboi27 | Medium | 21,464 | 1,438 |
find the kth smallest sum of a matrix with sorted rows | class Solution:
def kthSmallest(self, mat: List[List[int]], k: int) -> int:
row=len(mat)
col=len(mat[0])
temp=[i for i in mat[0]]
for i in range(1,row):
currSum=[]
for j in range(col):
for it in range(len(temp)):
currSum.app... | https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/1928887/Python3-or-O(m-*-knlogkn) | 2 | You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.
You are allowed to choose exactly one element from each row to form an array.
Return the kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Output: 7
Explanation: Choos... | [Python3] | O(m * knlogkn) | 66 | find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows | 0.614 | swapnilsingh421 | Hard | 21,467 | 1,439 |
build an array with stack operations | class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
stack=[]
for i in range(1,n+1):
if(i in target):
stack.append("Push")
else:
stack.append("Push")
stack.append("Pop")
if(i==(target[-1])):
... | https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1291707/Easy-Python-Solution(96.97) | 6 | You are given an integer array target and an integer n.
You have an empty stack with the two following operations:
"Push": pushes an integer to the top of the stack.
"Pop": removes the integer on the top of the stack.
You also have a stream of the integers in the range [1, n].
Use the two stack operations to make the n... | Easy Python Solution(96.97%) | 407 | build-an-array-with-stack-operations | 0.714 | Sneh17029 | Medium | 21,468 | 1,441 |
count triplets that can form two arrays of equal xor | class Solution:
def countTriplets(self, arr: List[int]) -> int:
import collections
if len(arr) < 2:
return 0
xors = arr[0]
cnt = collections.Counter()
cnt_sums = collections.Counter()
result = 0
cnt[xors] = 1
cnt_sums[xors] = 0
... | https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1271870/Python-O(n)-hash-table | 1 | Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) Wh... | Python O(n) hash table | 164 | count-triplets-that-can-form-two-arrays-of-equal-xor | 0.756 | CiFFiRO | Medium | 21,501 | 1,442 |
minimum time to collect all apples in a tree | class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
self.res = 0
d = collections.defaultdict(list)
for e in edges: # construct the graph
d[e[0]].append(e[1])
d[e[1]].append(e[0])
seen = set() # ... | https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1460342/Python-Recursive-DFS-Solution-with-detailed-explanation-in-comments | 1 | Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.
The edges ... | [Python] Recursive DFS Solution with detailed explanation in comments | 192 | minimum-time-to-collect-all-apples-in-a-tree | 0.56 | lukefall425 | Medium | 21,508 | 1,443 |
number of ways of cutting a pizza | class Solution:
def ways(self, pizza: List[str], k: int) -> int:
rows, cols = len(pizza), len(pizza[0])
# first, need way to query if a section contains an apple given a top left (r1, c1) and bottom right (r2, c2)
# we can do this in constant time by keeping track of the number of a... | https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/2677389/Python3-or-Space-Optimized-Bottom-Up-DP-or-O(k-*-r-*-c-*-(r-%2B-c))-Time-O(r-*-c)-Space | 3 | Given a rectangular pizza represented as a rows x cols matrix containing the following characters: 'A' (an apple) and '.' (empty cell) and given the integer k. You have to cut the pizza into k pieces using k-1 cuts.
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the ce... | Python3 | Space Optimized Bottom-Up DP | O(k * r * c * (r + c)) Time, O(r * c) Space | 293 | number-of-ways-of-cutting-a-pizza | 0.579 | ryangrayson | Hard | 21,515 | 1,444 |
consecutive characters | class Solution:
def maxPower(self, s: str) -> int:
# the minimum value for consecutive is 1
local_max, global_max = 1, 1
# dummy char for initialization
prev = '#'
for char in s:
if char == prev:
# ke... | https://leetcode.com/problems/consecutive-characters/discuss/637217/Python-O(n)-by-linear-scan.-w-Comment | 7 | The power of the string is the maximum length of a non-empty substring that contains only one unique character.
Given a string s, return the power of s.
Example 1:
Input: s = "leetcode"
Output: 2
Explanation: The substring "ee" is of length 2 with the character 'e' only.
Example 2:
Input: s = "abbcccddddeeeeedcba"
Ou... | Python O(n) by linear scan. [w/ Comment] | 1,100 | consecutive-characters | 0.616 | brianchiang_tw | Easy | 21,519 | 1,446 |
simplified fractions | class Solution:
def simplifiedFractions(self, n: int) -> List[str]:
if n == 1:
return []
else:
numerator = list(range(1,n))
denominator = list(range(2,n+1))
res = set()
values = set()
for i in numerator:
for j in... | https://leetcode.com/problems/simplified-fractions/discuss/1336226/Python3-solution-using-set | 3 | Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.
Example 1:
Input: n = 2
Output: ["1/2"]
Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.
Exa... | Python3 solution using set | 102 | simplified-fractions | 0.648 | EklavyaJoshi | Medium | 21,556 | 1,447 |
count good nodes in binary tree | class Solution:
def goodNodes(self, root: TreeNode) -> int:
def solve(root,val):
if root:
k = solve(root.left, max(val,root.val)) + solve(root.right, max(val,root.val))
if root.val >= val:
k+=1
return k
return 0
... | https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511520/C%2B%2B-or-PYTHON-oror-EXPLAINED-oror | 43 | Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Nodes in blue are good.
Root Node (3) is always a good node.... | 🥇 C++ | PYTHON || EXPLAINED || ; ] | 2,600 | count-good-nodes-in-binary-tree | 0.746 | karan_8082 | Medium | 21,566 | 1,448 |
form largest integer with digits that add up to target | class Solution:
def largestNumber(self, cost: List[int], target: int) -> str:
@cache
def fn(x):
"""Return max integer given target x."""
if x == 0: return 0
if x < 0: return -inf
return max(fn(x - c) * 10 + i + 1 for i, c in enumerate(cost))... | https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/discuss/1113027/Python3-top-down-dp | 1 | Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:
The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).
The total cost used must be equal to target.
The integer does not have 0 digits.
Since the answer may be very large, return it ... | [Python3] top-down dp | 117 | form-largest-integer-with-digits-that-add-up-to-target | 0.472 | ye15 | Hard | 21,606 | 1,449 |
number of students doing homework at a given time | class Solution:
def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
count = 0 # If a value meets the criteria, one will be added here.
for x, y in zip(startTime, endTime): # Zipping the two lists to allow us to iterate over them using x,y as our variables.
... | https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/discuss/1817462/Python-Simple-Solution-or-Zip-and-Iterate-86-37ms | 4 | Given two integer arrays startTime and endTime and given an integer queryTime.
The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].
Return the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays... | Python Simple Solution | Zip & Iterate - 86% 37ms | 110 | number-of-students-doing-homework-at-a-given-time | 0.759 | IvanTsukei | Easy | 21,607 | 1,450 |
rearrange words in a sentence | class Solution:
def arrangeWords(self, text: str) -> str:
return " ".join(sorted(text.split(), key=len)).capitalize() | https://leetcode.com/problems/rearrange-words-in-a-sentence/discuss/636348/Python3-one-line | 40 | Given a sentence text (A sentence is a string of space-separated words) in the following format:
First letter is in upper case.
Each word in text are separated by a single space.
Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the... | [Python3] one line | 2,600 | rearrange-words-in-a-sentence | 0.626 | ye15 | Medium | 21,649 | 1,451 |
people whose list of favorite companies is not a subset of another list | class Solution:
def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:
n = len(favoriteCompanies)
comp = []
for f in favoriteCompanies:
comp += f
comp = list(set(comp))
dictBit = {comp[i] : 1 << i for i in range(len(comp))}
def getB... | https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/discuss/2827639/Python-or-Dictionary-%2B-Bitwise-operation | 0 | Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
Example 1:
Input... | Python | Dictionary + Bitwise operation | 3 | people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list | 0.568 | CosmosYu | Medium | 21,674 | 1,452 |
maximum number of darts inside of a circular dartboard | class Solution:
def numPoints(self, points: List[List[int]], r: int) -> int:
ans = 1
for x, y in points:
angles = []
for x1, y1 in points:
if (x1 != x or y1 != y) and (d:=sqrt((x1-x)**2 + (y1-y)**2)) <= 2*r:
angle = atan2(y1-y, x1-x)
... | https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/discuss/636439/Python3-angular-sweep-O(N2-logN) | 38 | Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall.
Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice th... | [Python3] angular sweep O(N^2 logN) | 1,400 | maximum-number-of-darts-inside-of-a-circular-dartboard | 0.369 | ye15 | Hard | 21,677 | 1,453 |
check if a word occurs as a prefix of any word in a sentence | class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
for i , j in enumerate(sentence.split()):
if(j.startswith(searchWord)):
return i + 1
return -1 | https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/discuss/1170901/Python3-Simple-And-Readable-Solution-With-Explanation | 3 | Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.
Return the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the fi... | [Python3] Simple And Readable Solution With Explanation | 67 | check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence | 0.642 | VoidCupboard | Easy | 21,679 | 1,455 |
maximum number of vowels in a substring of given length | class Solution:
def maxVowels(self, s: str, k: int) -> int:
x = 0
for i in range(k):
if s[i] in ('a', 'e', 'i', 'o', 'u'):
x += 1
ans = x
for i in range(k,len(s)):
if s[i] in ('a', 'e', 'i', 'o', 'u'):
x += 1
if s[i-... | https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/discuss/1504290/Python3-simple-soluton | 2 | Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = ... | Python3 simple soluton | 89 | maximum-number-of-vowels-in-a-substring-of-given-length | 0.581 | EklavyaJoshi | Medium | 21,705 | 1,456 |
pseudo palindromic paths in a binary tree | class Solution:
def pseudoPalindromicPaths (self, root: Optional[TreeNode], cnt = 0) -> int:
if not root: return 0
cnt ^= 1 << (root.val - 1)
if root.left is None and root.right is None:
return 1 if cnt & (cnt - 1) == 0 else 0
return self.pseudoPalindromicPaths(root.l... | https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/discuss/2573237/LeetCode-The-Hard-Way-Explained-Line-By-Line | 68 | Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
Return the number of pseudo-palindromic paths going from the root node to leaf nodes.
Example 1:
Input: root = [2,3,1,3,1... | 🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | 2,600 | pseudo-palindromic-paths-in-a-binary-tree | 0.68 | wingkwong | Medium | 21,725 | 1,457 |
max dot product of two subsequences | class Solution:
def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
n=len(nums1)
m=len(nums2)
dp=[[0]*(m+1) for i in range(n+1)]
for i in range(m+1):
dp[0][i]=-1e9
for i in range(n+1):
dp[i][0]=-1e9
for i in ra... | https://leetcode.com/problems/max-dot-product-of-two-subsequences/discuss/2613290/Python-Solution-or-DP-or-LCS | 0 | Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remai... | Python Solution | DP | LCS | 8 | max-dot-product-of-two-subsequences | 0.463 | Siddharth_singh | Hard | 21,749 | 1,458 |
make two arrays equal by reversing subarrays | class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
n, m = len(target), len(arr)
if m > n:
return False
t = Counter(target)
a = Counter(arr)
for k, v in a.items():
if k in t and v == t[k]:
continue
... | https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays/discuss/2730962/Easy-solution-using-dictionary-in-python | 7 | You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.
Return true if you can make arr equal to target or false otherwise.
Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true... | Easy solution using dictionary in python | 89 | make-two-arrays-equal-by-reversing-subarrays | 0.722 | ankurbhambri | Easy | 21,751 | 1,460 |
check if a string contains all binary codes of size k | class Solution:
def hasAllCodes(self, s: str, k: int) -> bool:
return len({s[i:i+k] for i in range(len(s)-k+1)}) == 2 ** k | https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2092441/Python-oror-2-Easy-oror-One-liner-with-explanation | 26 | Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
Example 1:
Input: s = "00110110", k = 2
Output: true
Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and ... | ✅ Python || 2 Easy || One liner with explanation | 1,900 | check-if-a-string-contains-all-binary-codes-of-size-k | 0.568 | constantine786 | Medium | 21,782 | 1,461 |
course schedule iv | class Solution:
def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
#Let m = len(prereqs) and z = len(queries)
#Time: O(m + n + n*n + z) -> O(n^2)
#Space: O(n*n + n + n*n + n + z) -> O(n^2)
#process... | https://leetcode.com/problems/course-schedule-iv/discuss/2337629/Python3-or-Solved-Using-Ancestors-of-every-DAG-Graph-Node-approach(Kahn's-Algo-BFS) | 1 | There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you ... | Python3 | Solved Using Ancestors of every DAG Graph Node approach(Kahn's Algo BFS) | 28 | course-schedule-iv | 0.489 | JOON1234 | Medium | 21,813 | 1,462 |
cherry pickup ii | class Solution:
def cherryPickup(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]
def get_next_max(row, col_r1, col_r2):
res = 0
for next_col_r1 in (co... | https://leetcode.com/problems/cherry-pickup-ii/discuss/1674033/Python3-DYNAMIC-PROGRAMMING-(*)-Explained | 14 | You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.
You have two robots that can collect cherries for you:
Robot #1 is located at the top-left corner (0, 0), and
Robot #2 is located at the top-right corner... | ❤ [Python3] DYNAMIC PROGRAMMING (*´∇`)ノ, Explained | 506 | cherry-pickup-ii | 0.701 | artod | Hard | 21,816 | 1,463 |
maximum product of two elements in an array | class Solution:
def maxProduct(self, nums: List[int]) -> int:
# approach 1: find 2 max numbers in 2 loops. T = O(n). S = O(1)
# approach 2: sort and then get the last 2 max elements. T = O(n lg n). S = O(1)
# approach 3: build min heap of size 2. T = O(n lg n). S = O(1)
# python gives only min heap fe... | https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1975858/Python-3-greater-Using-heap | 3 | Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).
Example 1:
Input: nums = [3,4,5,2]
Output: 12
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(... | Python 3 -> Using heap | 195 | maximum-product-of-two-elements-in-an-array | 0.794 | mybuddy29 | Easy | 21,834 | 1,464 |
maximum area of a piece of cake after horizontal and vertical cuts | class Solution:
def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:
hc.sort()
vc.sort()
maxh = hc[0]
maxv = vc[0]
for i in range(1, len(hc)):
maxh = max(maxh, hc[i] - hc[i-1])
maxh = max(maxh, h - hc[-1])
... | https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227297/Python-easy-solution | 3 | You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:
horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and
verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical c... | Python easy solution | 81 | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | 0.409 | lokeshsenthilkumar | Medium | 21,882 | 1,465 |
reorder routes to make all paths lead to the city zero | class Solution:
def minReorder(self, n: int, connections: List[List[int]]) -> int:
cmap = {0}
count = 0
dq = deque(connections)
while dq:
u, v = dq.popleft()
if v in cmap:
cmap.add(u)
elif u in cmap:
cmap.add(v)
... | https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/1071235/Pythonor-Easy-and-fast-or-Beats-99 | 8 | Python| Easy and fast | Beats 99% | 406 | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0.618 | SlavaHerasymov | Medium | 21,926 | 1,466 | |
probability of a two boxes having the same number of distinct balls | class Solution:
def getProbability(self, balls: List[int]) -> float:
n = sum(balls)//2
@cache
def fn(i, s0, s1, c0, c1):
"""Return number of ways to distribute boxes successfully (w/o considering relative order)."""
if s0 > n or s1 > n: return 0 # impossible... | https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/discuss/1214891/Python3-top-down-dp | 0 | Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.
All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation... | [Python3] top-down dp | 130 | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0.611 | ye15 | Hard | 21,939 | 1,467 |
shuffle the array | class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
l=[]
for i in range(n):
l.append(nums[i])
l.append(nums[n+i])
return l | https://leetcode.com/problems/shuffle-the-array/discuss/941189/Simple-Python-Solution | 10 | Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: n... | Simple Python Solution | 947 | shuffle-the-array | 0.885 | lokeshsenthilkumar | Easy | 21,940 | 1,470 |
the k strongest values in an array | class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
new_arr = []
arr.sort()
med = arr[int((len(arr) - 1)//2)]
for num in arr :
new_arr.append([int(abs(num - med)), num])
new_arr = sorted(new_arr, key = lambda x : (x[0], x[1])... | https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/2516738/easy-python-solution | 0 | Given an array of integers arr and an integer k.
A value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.
If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].
Return a list of the strongest k values in the... | easy python solution | 15 | the-k-strongest-values-in-an-array | 0.602 | sghorai | Medium | 21,987 | 1,471 |
paint house iii | class Solution:
def minCost1(self, houses: List[int], cost: List[List[int]], R: int, C: int, target: int) -> int:
# think as if we are traveling downward
# at any point, if switch our column then (target--)
@functools.cache
def dp(x,y,k): # O(100*20*100) time space
... | https://leetcode.com/problems/paint-house-iii/discuss/1397505/Explained-Commented-Top-Down-greater-Bottom-Up-greater-Space-Optimized-Bottom-Up | 3 | There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
For example: houses = [1,2,2,3,3... | Explained Commented Top Down -> Bottom Up -> Space Optimized Bottom Up | 257 | paint-house-iii | 0.619 | yozaam | Hard | 21,994 | 1,473 |
final prices with a special discount in a shop | class Solution:
def finalPrices(self, prices: List[int]) -> List[int]:
len_prices = len(prices)
i = 0
while i <= len_prices-2:
for j in range(i+1, len(prices)):
if prices[i] >= prices[j] and j > i:
prices[i] = prices[i] - prices[j]
... | https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/discuss/685429/PythonPython3-Final-Prices-with-a-Special-Discount-in-a-Shop | 4 | You are given an integer array prices where prices[i] is the price of the ith item in a shop.
There is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will ... | [Python/Python3] Final Prices with a Special Discount in a Shop | 541 | final-prices-with-a-special-discount-in-a-shop | 0.755 | newborncoder | Easy | 22,005 | 1,475 |
find two non overlapping sub arrays each with target sum | class Solution:
def minSumOfLengths(self, arr: List[int], target: int) -> int:
l, windowSum, res = 0, 0, float('inf')
min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.
for r, num in enumerate(arr): # r:right pointer and index of num in ... | https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/discuss/1987219/Python-Sliding-Window-O(n)-with-detail-comments. | 5 | You are given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two r... | Python - Sliding Window - O(n) with detail comments. | 323 | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0.37 | changyou1009 | Medium | 22,034 | 1,477 |
allocate mailboxes | class Solution:
def minDistance(self, houses: List[int], k: int) -> int:
n = len(houses)
houses.sort()
cost = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(i+1,n):
mid_house = houses[(i+j)//2]
for t in range(i,j+1):
cost[... | https://leetcode.com/problems/allocate-mailboxes/discuss/1496112/Beginner-Friendly-oror-Easy-to-understand-oror-DP-solution | 3 | Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: houses ... | 📌📌 Beginner-Friendly || Easy-to-understand || DP solution 🐍 | 379 | allocate-mailboxes | 0.556 | abhi9Rai | Hard | 22,041 | 1,478 |
running sum of 1d array | class Solution(object):
def runningSum(self, nums):
result = []
current_sum = 0
for i in range(0, len(nums)):
result.append(current_sum + nums[i])
current_sum = result[i]
return result | https://leetcode.com/problems/running-sum-of-1d-array/discuss/2306599/Easy-to-understand-Python-solution | 13 | Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Ex... | Easy to understand Python solution | 324 | running-sum-of-1d-array | 0.892 | Balance-Coffee | Easy | 22,044 | 1,480 |
least number of unique integers after k removals | class Solution:
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
count = Counter(arr)
ans = len(count)
for i in sorted(count.values()):
k -= i
if k < 0:
break
ans -= 1
return ans | https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/discuss/1269930/Beats-99-runtime-oror-98-memory-oror-python-oror-easy | 11 | Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.
Example 1:
Input: arr = [5,5,4], k = 1
Output: 1
Explanation: Remove the single 4, only 5 is left.
Example 2:
Input: arr = [4,3,1,1,3,3,2], k = 3
Output: 2
Explanation: Remove 4, 2 and either o... | Beats 99% runtime || 98% memory || python || easy | 1,000 | least-number-of-unique-integers-after-k-removals | 0.569 | chikushen99 | Medium | 22,096 | 1,481 |
minimum number of days to make m bouquets | class Solution:
def checker(self,arr, d, m, k) -> bool:
'''
d -> days
m -> bouquets
k -> adjacent flowers
return bool
'''
arr = [10**9] + arr + [10**9] #appending array with maximum values
idx = []
for i in range(len(arr)):
... | https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/discuss/707611/Python-Binary-Search-or-Mathematical-function-definition-(75-Speed) | 3 | You are given an integer array bloomDay, an integer m and an integer k.
You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.
The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.
Return the minimum numbe... | [Python] Binary Search | Mathematical function definition (75% Speed) | 223 | minimum-number-of-days-to-make-m-bouquets | 0.557 | uds5501 | Medium | 22,104 | 1,482 |
xor operation in an array | class Solution:
def xorOperation(self, n: int, start: int) -> int:
ans=0
for i in range(n):
ans^=start+(2*i)
return ans | https://leetcode.com/problems/xor-operation-in-an-array/discuss/942598/Simple-Python-Solutions | 8 | You are given an integer n and an integer start.
Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.
Return the bitwise XOR of all elements of nums.
Example 1:
Input: n = 5, start = 0
Output: 8
Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.
Where "^... | Simple Python Solutions | 604 | xor-operation-in-an-array | 0.842 | lokeshsenthilkumar | Easy | 22,117 | 1,486 |
making file names unique | class Solution:
def getFolderNames(self, names: List[str]) -> List[str]:
# names : array of names
# n : size of names
# create folders at the i'th minute for each name = names[i]
# If name was used previously, append a suffix "(k)" - note parenthesis - where k is the smalles... | https://leetcode.com/problems/making-file-names-unique/discuss/1646944/Very-simple-python3-solution-using-hashmap-and-comments | 3 | Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].
Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in th... | Very simple python3 solution using hashmap and comments | 307 | making-file-names-unique | 0.359 | jumpstarter | Medium | 22,153 | 1,487 |
avoid flood in the city | class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
pq = []
fill = set()
d = collections.defaultdict(list)
ans = []
for i, rain in enumerate(rains):
d[rain].append(i)
for rain in rains:
if rain > 0:
... | https://leetcode.com/problems/avoid-flood-in-the-city/discuss/1842629/Python-easy-to-read-and-understand-or-heap | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.
Given an integer array rains where:
rains[i] > 0 mean... | Python easy to read and understand | heap | 193 | avoid-flood-in-the-city | 0.261 | sanial2001 | Medium | 22,158 | 1,488 |
find critical and pseudo critical edges in minimum spanning tree | class Solution:
def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:
graph = dict()
for u, v, w in edges:
graph.setdefault(u, []).append((v, w))
graph.setdefault(v, []).append((u, w))
ref = self.mst(n, graph)
... | https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/discuss/702027/Python3-Prim's-algo | 4 | Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and w... | [Python3] Prim's algo | 355 | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0.526 | ye15 | Hard | 22,160 | 1,489 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.