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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
minimum absolute difference queries | class Solution:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
loc = {}
for i, x in enumerate(nums): loc.setdefault(x, []).append(i)
keys = sorted(loc)
ans = []
for l, r in queries:
prev, val = 0, inf
for x i... | https://leetcode.com/problems/minimum-absolute-difference-queries/discuss/1284341/Python3-binary-search | 8 | The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.
For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is no... | [Python3] binary search | 681 | minimum-absolute-difference-queries | 0.439 | ye15 | Medium | 26,966 | 1,906 |
remove one element to make the array strictly increasing | class Solution:
def canBeIncreasing(self, nums: List[int]) -> bool:
stack = []
for i in range(1, len(nums)):
if nums[i-1] >= nums[i]: stack.append(i)
if not stack: return True
if len(stack) > 1: return False
i = stack[0]
return (i == 1 o... | https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1298457/Python3-collect-non-conforming-indices | 15 | Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.
The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).
Example 1:
Inp... | [Python3] collect non-conforming indices | 1,200 | remove-one-element-to-make-the-array-strictly-increasing | 0.26 | ye15 | Easy | 26,967 | 1,909 |
remove all occurrences of a substring | class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
lps = [0]
k = 0
for i in range(1, len(part)):
while k and part[k] != part[i]: k = lps[k-1]
if part[k] == part[i]: k += 1
lps.append(k)
stack = [("", 0)]
for c... | https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1298899/Python3-kmp | 9 | Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:
Find the leftmost occurrence of the substring part and remove it from s.
Return s after removing all occurrences of part.
A substring is a contiguous sequence of characters in a string.
Example ... | [Python3] kmp | 955 | remove-all-occurrences-of-a-substring | 0.742 | ye15 | Medium | 26,988 | 1,910 |
maximum alternating subsequence sum | class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
ma=0
mi=0
for num in nums:
ma=max(ma,num-mi)
mi=min(mi,num-ma)
return ma | https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298531/4-lines-oror-96-faster-oror-Easy-approach | 7 | The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.
Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the el... | π 4 lines || 96% faster || Easy-approach π | 358 | maximum-alternating-subsequence-sum | 0.593 | abhi9Rai | Medium | 27,014 | 1,911 |
maximum product difference between two pairs | class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return (nums[-1]*nums[-2])-(nums[0]*nums[1]) | https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2822079/Python-oror-96.20-Faster-oror-2-Lines-oror-Sorting | 1 | The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).
For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) ... | Python || 96.20% Faster || 2 Lines || Sorting | 44 | maximum-product-difference-between-two-pairs | 0.814 | DareDevil_007 | Easy | 27,027 | 1,913 |
cyclically rotating a grid | class Solution:
def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0]) # dimensions
for r in range(min(m, n)//2):
i = j = r
vals = []
for jj in range(j, n-j-1): vals.append(grid[i][jj])
for... | https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1299526/Python3-brute-force | 24 | You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotat... | [Python3] brute-force | 988 | cyclically-rotating-a-grid | 0.481 | ye15 | Medium | 27,068 | 1,914 |
number of wonderful substrings | class Solution:
def wonderfulSubstrings(self, word: str) -> int:
ans = mask = 0
freq = defaultdict(int, {0: 1})
for ch in word:
mask ^= 1 << ord(ch)-97
ans += freq[mask]
for i in range(10): ans += freq[mask ^ 1 << i]
freq[mask] += 1
re... | https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1299537/Python3-freq-table-w.-mask | 11 | A wonderful string is a string where at most one letter appears an odd number of times.
For example, "ccjjc" and "abab" are wonderful, but "ab" is not.
Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same... | [Python3] freq table w. mask | 678 | number-of-wonderful-substrings | 0.45 | ye15 | Medium | 27,076 | 1,915 |
count ways to build rooms in an ant colony | class Solution:
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
tree = defaultdict(list)
for i, x in enumerate(prevRoom): tree[x].append(i)
def fn(n):
"""Return number of nodes and ways to build sub-tree."""
if not tree[n]: return 1, 1 # leaf
... | https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/discuss/1299545/Python3-post-order-dfs | 8 | You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already ... | [Python3] post-order dfs | 762 | count-ways-to-build-rooms-in-an-ant-colony | 0.493 | ye15 | Hard | 27,079 | 1,916 |
build array from permutation | class Solution:
def buildArray(self, nums: List[int]) -> List[int]:
return [nums[nums[i]] for i in range(len(nums))] | https://leetcode.com/problems/build-array-from-permutation/discuss/1314345/Python3-1-line | 11 | Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.
A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Example 1:
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4... | [Python3] 1-line | 1,800 | build-array-from-permutation | 0.912 | ye15 | Easy | 27,080 | 1,920 |
eliminate maximum number of monsters | class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
for i, t in enumerate(sorted((d+s-1)//s for d, s in zip(dist, speed))):
if i == t: return i
return len(dist) | https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314370/Python3-3-line | 4 | You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.
The monsters walk toward the city at a constant speed. The speed of each monster is giv... | [Python3] 3-line | 312 | eliminate-maximum-number-of-monsters | 0.379 | ye15 | Medium | 27,128 | 1,921 |
count good numbers | class Solution:
def countGoodNumbers(self, n: int) -> int:
'''
ans=1
MOD=int(10**9+7)
for i in range(n):
if i%2==0:
ans*=5
else:
ans*=4
ans%=MOD
return ans
'''
MOD=int(10**9+7)
fives,... | https://leetcode.com/problems/count-good-numbers/discuss/1314484/Python3-Powermod-hack-3-lines | 5 | A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).
For example, "2582" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, "3245" is not good because 3 is at an even ... | [Python3] Powermod hack, 3 lines | 396 | count-good-numbers | 0.384 | mikeyliu | Medium | 27,137 | 1,922 |
count square sum triples | ```class Solution:
def countTriples(self, n: int) -> int:
count = 0
sqrt = 0
for i in range(1,n-1):
for j in range(i+1, n):
sqrt = ((i*i) + (j*j)) ** 0.5
if sqrt % 1 == 0 and sqrt <= n:
count += 2
return (count)
*Ple... | https://leetcode.com/problems/count-square-sum-triples/discuss/2318104/Easy-Solution-oror-PYTHON | 2 | A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Example 1:
Input: n = 5
Output: 2
Explanation: The square triples are (3,4,5) and (4,3,5).
Example 2:
Input: n = 10
Output: 4
Explanation: The squar... | Easy Solution || PYTHON | 134 | count-square-sum-triples | 0.68 | Jonny69 | Easy | 27,145 | 1,925 |
nearest exit from entrance in maze | class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
q = collections.deque([(*entrance, 0)])
m, n = len(maze), len(maze[0])
maze[entrance[0]][entrance[1]] == '+'
while q:
x, y, c = q.popleft()
if (x == 0 or x == m-1 or ... | https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1329534/Python-3-or-BFS-Deque-In-place-or-Explanation | 5 | You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down,... | Python 3 | BFS, Deque, In-place | Explanation | 197 | nearest-exit-from-entrance-in-maze | 0.49 | idontknoooo | Medium | 27,157 | 1,926 |
sum game | class Solution:
def sumGame(self, num: str) -> bool:
n = len(num)
q_cnt_1 = s1 = 0
for i in range(n//2): # get digit sum and question mark count for the first half of `num`
if num[i] == '?':
q_cnt_1 += 1
else:
s1 += int(num[i])
... | https://leetcode.com/problems/sum-game/discuss/1330360/Python-3-or-Simple-Math-or-Explanation | 16 | Alice and Bob take turns playing a game, with Alice starting first.
You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:
Choose an index i where num[i] == '?'.
Replace num[i] with any digit between '0' ... | Python 3 | Simple Math | Explanation | 396 | sum-game | 0.469 | idontknoooo | Medium | 27,202 | 1,927 |
minimum cost to reach destination in time | class Solution:
def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:
n = len(passingFees)
mat = {}
for x, y, time in edges:
if x not in mat: mat[x] = set()
if y not in mat: mat[y] = set()
mat[x].add((y, time))
... | https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/discuss/2841255/Python-Dijkstra's-Algorithm%3A-36-time-8-space | 0 | There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing ... | Python Dijkstra's Algorithm: 36% time, 8% space | 2 | minimum-cost-to-reach-destination-in-time | 0.374 | hqz3 | Hard | 27,204 | 1,928 |
concatenation of array | class Solution:
def getConcatenation(self, nums: List[int]) -> List[int]:
nums.extend(nums)
return nums | https://leetcode.com/problems/concatenation-of-array/discuss/2044719/Easy-Python-two-liner-code | 10 | Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.
Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The a... | Easy Python two liner code | 743 | concatenation-of-array | 0.912 | Shivam_Raj_Sharma | Easy | 27,207 | 1,929 |
unique length 3 palindromic subsequences | class Solution(object):
def countPalindromicSubsequence(self, s):
d=defaultdict(list)
for i,c in enumerate(s):
d[c].append(i)
ans=0
for el in d:
if len(d[el])<2:
continue
a=d[el][0]
b=d[el][-1]
ans+=len(set(s... | https://leetcode.com/problems/unique-length-3-palindromic-subsequences/discuss/1330186/easy-python-solution | 32 | Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string g... | easy python solution | 1,100 | unique-length-3-palindromic-subsequences | 0.515 | aayush_chhabra | Medium | 27,274 | 1,930 |
painting a grid with three different colors | class Solution:
def colorTheGrid(self, m: int, n: int) -> int:
@cache
def fn(i, j, mask):
"""Return number of ways to color grid."""
if j == n: return 1
if i == m: return fn(0, j+1, mask)
ans = 0
for x in 1<<2*i, 1<<2*i+1, 0b11<... | https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1338695/Python3-top-down-dp | 1 | You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + ... | [Python3] top-down dp | 263 | painting-a-grid-with-three-different-colors | 0.57 | ye15 | Hard | 27,285 | 1,931 |
merge bsts to create single bst | class Solution:
def canMerge(self, trees: List[TreeNode]) -> TreeNode:
roots, leaves, loners, n = {}, {}, set(), len(trees)
if n == 1:
return trees[0]
for tree in trees:
if not tree.left and not tree.right:
loners.add(tree.val)
continue... | https://leetcode.com/problems/merge-bsts-to-create-single-bst/discuss/1410066/Python3-Recursive-tree-building-solution | 0 | You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:
Select two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal t... | Python3 Recursive tree building solution | 134 | merge-bsts-to-create-single-bst | 0.353 | yiseboge | Hard | 27,287 | 1,932 |
maximum number of words you can type | class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
text = text.split()
length = len(text)
brokenLetters = set(brokenLetters)
for word in text:
for char in word:
if char in brokenLetters:
length -= 1
... | https://leetcode.com/problems/maximum-number-of-words-you-can-type/discuss/1355349/Easy-Fast-Python-Solutions-(2-Approaches-28ms-32ms-Faster-than-93) | 10 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can... | Easy, Fast Python Solutions (2 Approaches - 28ms, 32ms; Faster than 93%) | 624 | maximum-number-of-words-you-can-type | 0.71 | the_sky_high | Easy | 27,288 | 1,935 |
add minimum number of rungs | class Solution:
def addRungs(self, rungs: List[int], dist: int) -> int:
return sum((a - b - 1) // dist for a, b in zip(rungs, [0] + rungs)) | https://leetcode.com/problems/add-minimum-number-of-rungs/discuss/1344878/Divide-gaps-by-dist | 37 | You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.
You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (th... | Divide gaps by dist | 1,800 | add-minimum-number-of-rungs | 0.429 | votrubac | Medium | 27,323 | 1,936 |
maximum number of points with cost | class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
m, n = len(points), len(points[0])
dp = points[0]
left = [0] * n ## left side contribution
right = [0] * n ## right side contribution
for r in range(1, m):
for c in ran... | https://leetcode.com/problems/maximum-number-of-points-with-cost/discuss/2119013/Python%3A-Dynamic-Programming-O(mn)-Solution | 14 | You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.
However, you will lose points if you pi... | Python: Dynamic Programming O(mn) Solution | 784 | maximum-number-of-points-with-cost | 0.362 | dadhania | Medium | 27,340 | 1,937 |
check if all characters have equal number of occurrences | class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
return len(set(Counter(s).values())) == 1 | https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/discuss/1359715/Python3-1-line | 35 | Given a string s, return true if s is a good string, or false otherwise.
A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Example 1:
Input: s = "abacbc"
Output: true
Explanation: The characters that appear in s are 'a', 'b', and 'c'. All charact... | [Python3] 1-line | 2,100 | check-if-all-characters-have-equal-number-of-occurrences | 0.768 | ye15 | Easy | 27,350 | 1,941 |
the number of the smallest unoccupied chair | class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
arrivals = []
departures = []
for ind, (x, y) in enumerate(times):
heappush(arrivals, (x, ind))
heappush(departures, (y, ind))
d = {}
occupied = [0] * len(times)... | https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/discuss/1359713/Python-Simple-Heap-Solution-with-Explanation | 20 | There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.
For example, if chairs 0, 1, and 5 are occupied when a friend ... | Python - Simple Heap Solution with Explanation | 1,100 | the-number-of-the-smallest-unoccupied-chair | 0.406 | ajith6198 | Medium | 27,391 | 1,942 |
describe the painting | class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
# via this mapping, we can easily know which coordinates should be took into consideration.
mapping = defaultdict(int)
for s, e, c in segments:
mapping[s] += c
mapping[e] -= c
... | https://leetcode.com/problems/describe-the-painting/discuss/1359717/Python-Easy-solution-in-O(n*logn)-with-detailed-explanation | 129 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, en... | [Python] Easy solution in O(n*logn) with detailed explanation | 2,000 | describe-the-painting | 0.48 | fishballLin | Medium | 27,398 | 1,943 |
number of visible people in a queue | class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
ans = [0]*len(heights)
stack = [] # mono-stack
for i in reversed(range(len(heights))):
while stack and stack[-1] <= heights[i]:
ans[i] += 1
stack.pop()
if... | https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1359735/Python3-mono-stack | 10 | There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.
A person can see another person to their right in the queue if everybody in between is shorter than both of them... | [Python3] mono-stack | 667 | number-of-visible-people-in-a-queue | 0.697 | ye15 | Hard | 27,403 | 1,944 |
sum of digits of string after convert | class Solution:
def getLucky(self, s: str, k: int) -> int:
s = "".join(str(ord(ch) - 96) for ch in s)
for _ in range(k):
x = sum(int(ch) for ch in s)
s = str(x)
return x | https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1360730/Python3-simulation | 5 | You are given a string s consisting of lowercase English letters, and an integer k.
First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the tra... | [Python3] simulation | 487 | sum-of-digits-of-string-after-convert | 0.612 | ye15 | Easy | 27,409 | 1,945 |
largest number after mutating substring | class Solution:
def maximumNumber(self, num: str, change: List[int]) -> str:
num = list(num)
on = False
for i, ch in enumerate(num):
x = int(ch)
if x < change[x]:
on = True
num[i] = str(change[x])
elif x > change[x] and o... | https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/1360736/Python3-greedy | 7 | You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].
You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] w... | [Python3] greedy | 572 | largest-number-after-mutating-substring | 0.346 | ye15 | Medium | 27,437 | 1,946 |
maximum compatibility score sum | class Solution:
def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:
m = len(students)
score = [[0]*m for _ in range(m)]
for i in range(m):
for j in range(m):
score[i][j] = sum(x == y for x, y in zip(students[i], me... | https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1360746/Python3-permutations | 16 | There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).
The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array th... | [Python3] permutations | 1,100 | maximum-compatibility-score-sum | 0.609 | ye15 | Medium | 27,443 | 1,947 |
delete duplicate folders in system | class Solution:
def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
paths.sort()
tree = {"#": -1}
for i, path in enumerate(paths):
node = tree
for x in path: node = node.setdefault(x, {})
node["#"] = i
see... | https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/1360749/Python3-serialize-sub-trees | 4 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system.
For example, ["one", "two", "three"] represents the path "/one/two/three".
Two folders (not necessarily on the same level) are i... | [Python3] serialize sub-trees | 469 | delete-duplicate-folders-in-system | 0.579 | ye15 | Hard | 27,452 | 1,948 |
three divisors | class Solution:
def isThree(self, n: int) -> bool:
return sum(n%i == 0 for i in range(1, n+1)) == 3 | https://leetcode.com/problems/three-divisors/discuss/1375468/Python3-1-line | 14 | Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.
An integer m is a divisor of n if there exists an integer k such that n = k * m.
Example 1:
Input: n = 2
Output: false
Explantion: 2 has only two divisors: 1 and 2.
Example 2:
Input: n = 4
Output: true
Explantion: 4 has... | [Python3] 1-line | 866 | three-divisors | 0.572 | ye15 | Easy | 27,454 | 1,952 |
maximum number of weeks for which you can work | class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
_sum, _max = sum(milestones), max(milestones)
# (_sum - _max) is the sum of milestones from (2) the rest of projects, if True, we can form another project with the same amount of milestones as (1)
# can refer to the section `Why the ... | https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375390/Python-Solution-with-detailed-explanation-and-proof-and-common-failure-analysis | 232 | There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.
You can work on the projects following these two rules:
Every week, you will finish exactly one milestone of one project. You must work every week.
You ... | [Python] Solution with detailed explanation & proof & common failure analysis | 7,200 | maximum-number-of-weeks-for-which-you-can-work | 0.391 | fishballLin | Medium | 27,482 | 1,953 |
minimum garden perimeter to collect enough apples | class Solution:
def minimumPerimeter(self, nap: int) -> int:
# here for n = 2 , there are two series :
# (1) Diagnal points for n=3 , diagnal apples = 2*n = 6
# (2) there is series = 2,3,3 = 2+ (sigma(3)-sigma(2))*2
# how to solve:
# ... | https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1589250/Explanation-for-Intuition-behind-the-math-formula-derivation | 2 | In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0).
Given an integer neededApples, return the mi... | Explanation for Intuition behind the math formula derivation | 123 | minimum-garden-perimeter-to-collect-enough-apples | 0.53 | martian_rock | Medium | 27,487 | 1,954 |
count number of special subsequences | class Solution:
def countSpecialSubsequences(self, nums: List[int]) -> int:
total_zeros = 0 # number of subsequences of 0s so far
total_ones = 0 # the number of subsequences of 0s followed by 1s so far
total_twos = 0 # the number of special subsequences so far
M = 1000000007... | https://leetcode.com/problems/count-number-of-special-subsequences/discuss/1387357/Simple-Python-with-comments.-One-pass-O(n)-with-O(1)-space | 4 | A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.
For example, [0,1,2] and [0,0,1,1,1,2] are special.
In contrast, [2,1,0], [1], and [0,1,2,0] are not special.
Given an array nums (consisting of only integers 0, 1, and 2), return the numb... | Simple Python with comments. One pass O(n) with O(1) space | 151 | count-number-of-special-subsequences | 0.513 | IlyaL | Hard | 27,499 | 1,955 |
delete characters to make fancy string | class Solution:
def makeFancyString(self, s: str) -> str:
stack = []
for letter in s:
if len(stack) > 1 and letter == stack[-1] == stack[-2]:
stack.pop()
stack.append(letter)
return ''.join(stack) | https://leetcode.com/problems/delete-characters-to-make-fancy-string/discuss/2714159/Python-or-Easy-Solution | 6 | A fancy string is a string where no three consecutive characters are equal.
Given a string s, delete the minimum possible number of characters from s to make it fancy.
Return the final string after the deletion. It can be shown that the answer will always be unique.
Example 1:
Input: s = "leeetcode"
Output: "leetcode... | Python | Easy Solutionβ | 113 | delete-characters-to-make-fancy-string | 0.567 | manayathgeorgejames | Easy | 27,503 | 1,957 |
check if move is legal | class Solution:
def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:
for di, dj in (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1):
i, j = rMove+di, cMove+dj
step = 0
while 0 <= i < 8 and 0 <= j < 8:
... | https://leetcode.com/problems/check-if-move-is-legal/discuss/1389250/Python3-check-8-directions | 5 | You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.
Each move in this game consists of choosing a free cell and changing it to the color you ... | [Python3] check 8 directions | 312 | check-if-move-is-legal | 0.445 | ye15 | Medium | 27,526 | 1,958 |
minimum total space wasted with k resizing operations | class Solution:
def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:
@cache
def fn(i, k):
"""Return min waste from i with k ops."""
if i == len(nums): return 0
if k < 0: return inf
ans = inf
rmx = rsm = 0
... | https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/discuss/1389260/Python3-dp | 14 | You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).
The size of the array at time t, sizet, mus... | [Python3] dp | 987 | minimum-total-space-wasted-with-k-resizing-operations | 0.42 | ye15 | Medium | 27,530 | 1,959 |
maximum product of the length of two palindromic substrings | class Solution:
def maxProduct(self, s: str) -> int:
n = len(s)
# Manacher's algo
hlen = [0]*n # half-length
center = right = 0
for i in range(n):
if i < right: hlen[i] = min(right - i, hlen[2*center - i])
while 0 <= i-1-hlen[i] and i+1+hlen... | https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/discuss/1393832/Python3-Manacher | 3 | You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l]... | [Python3] Manacher | 200 | maximum-product-of-the-length-of-two-palindromic-substrings | 0.293 | ye15 | Hard | 27,534 | 1,960 |
check if string is a prefix of array | class Solution:
def isPrefixString(self, s: str, words: List[str]) -> bool:
i = 0
for word in words:
if s[i:i+len(word)] != word: return False
i += len(word)
if i == len(s): return True
return False | https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/discuss/1390199/Python3-move-along-s | 22 | Given a string s and an array of strings words, determine whether s is a prefix string of words.
A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.
Return true if s is a prefix string of words, or false otherwise.
Exam... | [Python3] move along s | 1,200 | check-if-string-is-a-prefix-of-array | 0.541 | ye15 | Easy | 27,535 | 1,961 |
remove stones to minimize the total | class Solution:
def minStoneSum(self, piles: List[int], k: int) -> int:
pq = [-x for x in piles]
heapify(pq)
for _ in range(k): heapreplace(pq, pq[0]//2)
return -sum(pq) | https://leetcode.com/problems/remove-stones-to-minimize-the-total/discuss/1390207/Python3-priority-queue | 7 | You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:
Choose any piles[i] and remove floor(piles[i] / 2) stones from it.
Notice that you can apply the operation on the same pile more than... | [Python3] priority queue | 413 | remove-stones-to-minimize-the-total | 0.593 | ye15 | Medium | 27,556 | 1,962 |
minimum number of swaps to make the string balanced | class Solution:
def minSwaps(self, s: str) -> int:
res, bal = 0, 0
for ch in s:
bal += 1 if ch == '[' else -1
if bal == -1:
res += 1
bal = 1
return res | https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/discuss/1390576/Two-Pointers | 19 | You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
A string is called balanced if and only if:
It is the empty string, or
It can be written as AB, where both A and B are balanced strings, or
It can be written as [C], where C is ... | Two Pointers | 2,000 | minimum-number-of-swaps-to-make-the-string-balanced | 0.684 | votrubac | Medium | 27,563 | 1,963 |
find the longest valid obstacle course at each position | class Solution:
def longestObstacleCourseAtEachPosition(self, obs: List[int]) -> List[int]:
local = []
res=[0 for _ in range(len(obs))]
for i in range(len(obs)):
n=obs[i]
if len(local)==0 or local[-1]<=n:
local.append(n)
res[i]=len(local)
else:
ind... | https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/discuss/1390573/Clean-and-Simple-oror-98-faster-oror-Easy-Code | 1 | You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.
For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:
You choose any number of obstacle... | π Clean & Simple || 98% faster || Easy-Code π | 48 | find-the-longest-valid-obstacle-course-at-each-position | 0.469 | abhi9Rai | Hard | 27,574 | 1,964 |
number of strings that appear as substrings in word | class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
return sum(x in word for x in patterns) | https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/discuss/1404073/Python3-1-line | 19 | Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: patterns = ["a","abc","bc","d"], word = "abc"
Output: 3
Explanation:
- "a" appears as a substring in "... | [Python3] 1-line | 1,400 | number-of-strings-that-appear-as-substrings-in-word | 0.799 | ye15 | Easy | 27,576 | 1,967 |
array with elements not equal to average of neighbors | class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
nums.sort()
if len(nums)==3:
nums[1],nums[0] = nums[0],nums[1]
return nums
for i in range(1,len(nums)-1):
if nums[i]-nums[i-1] == nums[i+1]-nums[i]:
if i!=... | https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/discuss/2280763/O(nlogn)-Solution-or-Python | 0 | You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - ... | O(nlogn) Solution | Python | 27 | array-with-elements-not-equal-to-average-of-neighbors | 0.496 | user7457RV | Medium | 27,600 | 1,968 |
minimum non zero product of the array elements | class Solution:
def minNonZeroProduct(self, p: int) -> int:
x = (1 << p) - 1
return pow(x-1, (x-1)//2, 1_000_000_007) * x % 1_000_000_007 | https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/discuss/1403953/Python3-2-line | 6 | You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:
Choose two elements x and y from nums.
Choose a bit in x and swap it with its corres... | [Python3] 2-line | 569 | minimum-non-zero-product-of-the-array-elements | 0.338 | ye15 | Medium | 27,603 | 1,969 |
last day where you can still cross | class Solution(object):
def latestDayToCross(self, row, col, cells):
l,h=0,len(cells)-1
ans=-1
while l<=h:
m=(l+h)>>1
if self.isPath(cells,m,row,col):
l=m+1
ans=m+1
else:
h=m-1
return ans
def isPa... | https://leetcode.com/problems/last-day-where-you-can-still-cross/discuss/2489142/Python3-or-Binary-Search-%2B-BFS | 0 | There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.
Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D ... | [Python3] | Binary Search + BFS | 36 | last-day-where-you-can-still-cross | 0.495 | swapnilsingh421 | Hard | 27,606 | 1,970 |
find if path exists in graph | class Solution(object):
def validPath(self, n, edges, start, end):
"""
:type n: int
:type edges: List[List[int]]
:type start: int
:type end: int
:rtype: bool
"""
visited = [False]*n
d = {}
#store the undirected edges for both vertices
... | https://leetcode.com/problems/find-if-path-exists-in-graph/discuss/1406782/Python-Easy-to-Understand-or-Beginners | 29 | There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge,... | Python - Easy to Understand | Beginners | 6,800 | find-if-path-exists-in-graph | 0.504 | Sibu0811 | Easy | 27,608 | 1,971 |
minimum time to type word using special typewriter | class Solution:
def minTimeToType(self, word: str) -> int:
ans = len(word)
prev = "a"
for ch in word:
val = (ord(ch) - ord(prev)) % 26
ans += min(val, 26 - val)
prev = ch
return ans | https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/discuss/1417585/Python3-greedy | 48 | There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.
Each second, you may perform one of the following operations:
Move the pointer ... | [Python3] greedy | 2,200 | minimum-time-to-type-word-using-special-typewriter | 0.714 | ye15 | Easy | 27,634 | 1,974 |
maximum matrix sum | class Solution:
def maxMatrixSum(self, matrix: List[List[int]]) -> int:
ans = mult = 0
val = inf
for i in range(len(matrix)):
for j in range(len(matrix)):
ans += abs(matrix[i][j])
val = min(val, abs(matrix[i][j]))
if matrix[i][j] ... | https://leetcode.com/problems/maximum-matrix-sum/discuss/1417592/Python3-greedy | 12 | You are given an n x n integer matrix. You can do the following operation any number of times:
Choose any two adjacent elements of matrix and multiply each of them by -1.
Two elements are considered adjacent if and only if they share a border.
Your goal is to maximize the summation of the matrix's elements. Return the ... | [Python3] greedy | 581 | maximum-matrix-sum | 0.457 | ye15 | Medium | 27,647 | 1,975 |
number of ways to arrive at destination | class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
graph = {}
for u, v, time in roads:
graph.setdefault(u, {})[v] = time
graph.setdefault(v, {})[u] = time
dist = [inf]*n
dist[-1] = 0
stack = [(n-1, 0)]
wh... | https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/discuss/1417598/Python3-dfs-%2B-dp | 5 | You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n and... | [Python3] dfs + dp | 846 | number-of-ways-to-arrive-at-destination | 0.323 | ye15 | Medium | 27,653 | 1,976 |
number of ways to separate numbers | class Solution:
def numberOfCombinations(self, num: str) -> int:
n = len(num)
lcs = [[0]*(n+1) for _ in range(n)]
for i in reversed(range(n)):
for j in reversed(range(i+1, n)):
if num[i] == num[j]: lcs[i][j] = 1 + lcs[i+1][j+1]
def cmp(i, j, d):... | https://leetcode.com/problems/number-of-ways-to-separate-numbers/discuss/1424057/Python3-dp | 3 | You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have writte... | [Python3] dp | 367 | number-of-ways-to-separate-numbers | 0.209 | ye15 | Hard | 27,660 | 1,977 |
find greatest common divisor of array | class Solution:
def findGCD(self, nums: List[int]) -> int:
gcd = lambda a, b: a if b == 0 else gcd(b, a % b)
return gcd(max(nums), min(nums)) | https://leetcode.com/problems/find-greatest-common-divisor-of-array/discuss/2580234/2-lines-PythonJavascript-(no-built-in-gcd-function) | 1 | Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
Example 1:
Input: nums = [2,5,6,9,10]
Output: 2
Explanation:
The smallest number in nums is 2.... | 2 lines Python/Javascript (no built in gcd function) | 125 | find-greatest-common-divisor-of-array | 0.767 | SmittyWerbenjagermanjensen | Easy | 27,661 | 1,979 |
find unique binary string | class Solution:
def findDifferentBinaryString(self, nums: List[str]) -> str:
return list(set(list((map(lambda x:"".join(list(map(str,x))),list(itertools.product([0,1],repeat=len(nums)))))))-set(nums))[0] | https://leetcode.com/problems/find-unique-binary-string/discuss/1657090/One-line-python-Solution | 2 | Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Example 1:
Input: nums = ["01","10"]
Output: "11"
Explanation: "11" does not appear in nums. "00" would also b... | One line python Solution | 159 | find-unique-binary-string | 0.643 | amannarayansingh10 | Medium | 27,687 | 1,980 |
minimize the difference between target and chosen elements | class Solution:
def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:
# store the mxn size of the matrix
m = len(mat)
n = len(mat[0])
dp = defaultdict(defaultdict)
# Sorting each row of the array for more efficient pruning
... | https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/discuss/1418634/100-efficient-or-Pruning-%2B-Memoization-or-Dynamic-Programming-or-Explanation | 24 | You are given an m x n integer matrix mat and an integer target.
Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.
Return the minimum absolute difference.
The absolute difference between two numbers a and b is the absolute va... | β
100% efficient | Pruning + Memoization | Dynamic Programming | Explanation | 2,200 | minimize-the-difference-between-target-and-chosen-elements | 0.323 | CaptainX | Medium | 27,714 | 1,981 |
find array given subset sums | class Solution:
def recoverArray(self, n: int, sums: List[int]) -> List[int]:
res = [] # Result set
sums.sort()
while len(sums) > 1:
num = sums[-1] - sums[-2] # max - secondMax
countMap = Counter(sums) # Get count of each elements
excluding = [] ... | https://leetcode.com/problems/find-array-given-subset-sums/discuss/1431457/Easy-Explanation-for-Noobs-%2B-Python-code-with-comments | 57 | You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).
Return the array ans of length n representing the unknown array. If multiple answers exist, r... | Easy Explanation for Noobs + Python code with comments | 1,500 | find-array-given-subset-sums | 0.489 | sumit686215 | Hard | 27,718 | 1,982 |
minimum difference between highest and lowest of k scores | class Solution:
def minimumDifference(self, nums: List[int], k: int) -> int:
nums.sort()
return min(nums[i+k-1]-nums[i] for i in range(len(nums)-k+1)) | https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/discuss/1433298/Python3-greedy-2-line | 2 | You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.
Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.
Return the minimum possible difference.
Example... | [Python3] greedy 2-line | 151 | minimum-difference-between-highest-and-lowest-of-k-scores | 0.536 | ye15 | Easy | 27,720 | 1,984 |
find the kth largest integer in the array | class Solution:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
nums = sorted(map(int, nums), reverse=True)
return str(nums[k-1]) | https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/discuss/1432093/Python-or-The-Right-Way-during-Interview-or-Comparators | 28 | You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.
Return the string that represents the kth largest integer in nums.
Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" ... | Python | The Right Way during Interview | Comparators | 1,800 | find-the-kth-largest-integer-in-the-array | 0.447 | malraharsh | Medium | 27,738 | 1,985 |
minimum number of work sessions to finish the tasks | class Solution:
def minSessions(self, tasks: List[int], sessionTime: int) -> int:
subsets = []
self.ans = len(tasks)
def func(idx):
if len(subsets) >= self.ans:
return
if idx == len(tasks):
self.ans = min(self.ans,... | https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/discuss/1433054/Python-or-Backtracking-or-664ms-or-100-time-and-space-or-Explanation | 22 | There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the follo... | Python | Backtracking | 664ms | 100% time and space | Explanation | 1,000 | minimum-number-of-work-sessions-to-finish-the-tasks | 0.331 | detective_dp | Medium | 27,760 | 1,986 |
number of unique good subsequences | class Solution:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
@cache
def fn(i, mask, v):
"""Return # unique good subsequences starting with 1."""
if i == len(binary) or not mask: return v
x = int(binary[i])
if not mask & (... | https://leetcode.com/problems/number-of-unique-good-subsequences/discuss/1433355/Python3-bit-mask-dp | 1 | You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of "0").
Find the number of unique good subsequences of binary.
For example, if binary = "001", then all the good subsequences are ["0", "0", "1"], so the unique good subseque... | [Python3] bit-mask dp | 139 | number-of-unique-good-subsequences | 0.524 | ye15 | Hard | 27,768 | 1,987 |
find the middle index in array | class Solution:
def findMiddleIndex(self, nums: List[int]) -> int:
left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]
right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
for i, num in enumerate(nums): # we can use normal for loop as well.
... | https://leetcode.com/problems/find-the-middle-index-in-array/discuss/2321632/Python-98.85-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum | 8 | Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].
If middleIndex == 0, the left side sum is consid... | Python 98.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum | 224 | find-the-middle-index-in-array | 0.673 | rlakshay14 | Easy | 27,770 | 1,991 |
find all groups of farmland | class Solution:
def findFarmland(self, land: List[List[int]]) -> List[List[int]]:
m, n = len(land), len(land[0])
ans = []
for i in range(m):
for j in range(n):
if land[i][j]: # found farmland
mini, minj = i, j
maxi, maxj =... | https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444115/Python3-dfs | 5 | You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adja... | [Python3] dfs | 207 | find-all-groups-of-farmland | 0.687 | ye15 | Medium | 27,804 | 1,992 |
the number of good subsets | class Solution:
def numberOfGoodSubsets(self, nums: List[int]) -> int:
freq = [0] * 31
for x in nums: freq[x] += 1
masks = [0] * 31
for x in range(1, 31):
if x == 1: masks[x] = 0b10
else:
bits = 0
xx = x
... | https://leetcode.com/problems/the-number-of-good-subsets/discuss/1444318/Python3-dp | 2 | You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.
For example, if nums = [1, 2, 3, 4]:
[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.
[1, 4] and [4] are not good... | [Python3] dp | 203 | the-number-of-good-subsets | 0.344 | ye15 | Hard | 27,820 | 1,994 |
count special quadruplets | class Solution:
def countQuadruplets(self, nums: List[int]) -> int:
idx = defaultdict(list)
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
idx[nums[j]-nums[i]].append(i)
count = 0
for i in range(len(nums)-3):
for j in ra... | https://leetcode.com/problems/count-special-quadruplets/discuss/1445362/Python-non-brute-force.-Time%3A-O(N2)-Space%3A-O(N2) | 4 | Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
nums[a] + nums[b] + nums[c] == nums[d], and
a < b < c < d
Example 1:
Input: nums = [1,2,3,6]
Output: 1
Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.
Example... | Python, non-brute force. Time: O(N^2), Space: O(N^2) | 729 | count-special-quadruplets | 0.593 | blue_sky5 | Easy | 27,822 | 1,995 |
the number of weak characters in the game | class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
properties.sort(key=lambda x: (-x[0],x[1]))
ans = 0
curr_max = 0
for _, d in properties:
if d < curr_max:
ans += 1
else:
... | https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1445198/Python-Sort | 209 | You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.
A character is said to be weak if any other ... | Python - Sort | 9,000 | the-number-of-weak-characters-in-the-game | 0.44 | lokeshsenthilkumar | Medium | 27,837 | 1,996 |
first day where you have been in all the rooms | class Solution:
def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
odd = [0]
even = [1]
for i in range(1, len(nextVisit)):
odd.append((even[-1] + 1) % 1_000_000_007)
even.append((2*odd[-1] - odd[nextVisit[i]] + 1) % 1_000_000_007)
return odd[-1] | https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/1446619/Python3-dp | 3 | There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.
Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:
Ass... | [Python3] dp | 139 | first-day-where-you-have-been-in-all-the-rooms | 0.367 | ye15 | Medium | 27,870 | 1,997 |
reverse prefix of word | class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
try:
ix = word.index(ch)
return word[:ix+1][::-1] + word[ix+1:]
except ValueError:
return word | https://leetcode.com/problems/reverse-prefix-of-word/discuss/1472737/Easy-Python-Solution-(28ms)-or-Faster-than-93 | 6 | Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.
For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at ... | Easy Python Solution (28ms) | Faster than 93% | 506 | reverse-prefix-of-word | 0.778 | the_sky_high | Easy | 27,875 | 2,000 |
number of pairs of interchangeable rectangles | class Solution:
def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
preSum = []
for rec in rectangles:
preSum.append(rec[1]/rec[0])
dic1 = {}
for i in range(len(preSum)-1, -1, -1):
if preSum[i] not in dic1.keys():
... | https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/discuss/2818774/O(n)-solution-of-Combined-Dictionary-and-Pre-sum-in-Python | 0 | You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are inter... | O(n) solution of Combined Dictionary and Pre sum in Python | 3 | number-of-pairs-of-interchangeable-rectangles | 0.451 | DNST | Medium | 27,917 | 2,001 |
maximum product of the length of two palindromic subsequences | class Solution:
def maxProduct(self, s: str) -> int:
subs = []
n = len(s)
def dfs(curr, ind, inds):
if ind == n:
if curr == curr[::-1]:
subs.append((curr, inds))
return
dfs(curr+s[ind], ind+1, inds|{ind})
... | https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/discuss/1458484/Python-Bruteforce | 3 | Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
A subsequence is a stri... | Python - Bruteforce | 232 | maximum-product-of-the-length-of-two-palindromic-subsequences | 0.533 | ajith6198 | Medium | 27,929 | 2,002 |
smallest missing genetic value in each subtree | class Solution:
def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:
ans = [1] * len(parents)
if 1 in nums:
tree = {}
for i, x in enumerate(parents):
tree.setdefault(x, []).append(i)
k = nums.i... | https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/discuss/1461767/Python3-dfs | 0 | There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.
There are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are give... | [Python3] dfs | 89 | smallest-missing-genetic-value-in-each-subtree | 0.443 | ye15 | Hard | 27,936 | 2,003 |
count number of pairs with absolute difference k | class Solution:
def countKDifference(self, nums: List[int], k: int) -> int:
seen = defaultdict(int)
counter = 0
for num in nums:
tmp, tmp2 = num - k, num + k
if tmp in seen:
counter += seen[tmp]
if tmp2 in seen:
counter += s... | https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/discuss/1471015/Python-Clean-and-concise.-Dictionary-T.C-O(N) | 36 | Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.
The value of |x| is defined as:
x if x >= 0.
-x if x < 0.
Example 1:
Input: nums = [1,2,2,1], k = 1
Output: 4
Explanation: The pairs with an absolute difference of 1 are:
- [1,2,2,1]
- [1,2,... | [Python] Clean & concise. Dictionary T.C O(N) | 3,700 | count-number-of-pairs-with-absolute-difference-k | 0.823 | asbefu | Easy | 27,937 | 2,006 |
find original array from doubled array | class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
"""
The idea is to:
1st sort the numbers
2nd Create a counter to save the frequency of each number
3nd iterate the array and for each number check if the double exists.
... | https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1470895/Python-Sorting.-Easy-to-understand-and-clean-T.C%3A-O(n-log-n)-S.C%3A-O(N) | 13 | An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.
Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements ... | [Python] Sorting. Easy to understand and clean T.C: O(n log n) S.C: O(N) | 981 | find-original-array-from-doubled-array | 0.409 | asbefu | Medium | 27,983 | 2,007 |
maximum earnings from taxi | class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
d = {}
for start,end,tip in rides:
if end not in d:
d[end] =[[start,tip]]
else:
d[end].append([start,tip])
dp = [0]*(n+1)
... | https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1485339/Python-Solution-Maximum-Earnings-from-Taxi | 2 | There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi.
The passengers are represented by a 0-indexed 2D ... | [Python] Solution - Maximum Earnings from Taxi | 2,100 | maximum-earnings-from-taxi | 0.432 | SaSha59 | Medium | 28,021 | 2,008 |
minimum number of operations to make array continuous | class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
nums = sorted(set(nums))
ans = ii = 0
for i, x in enumerate(nums):
if x - nums[ii] >= n: ii += 1
ans = max(ans, i - ii + 1)
return n - ans | https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1471593/Python3-sliding-window | 5 | You are given an integer array nums. In one operation, you can replace any element in nums with any integer.
nums is considered continuous if both of the following conditions are fulfilled:
All elements in nums are unique.
The difference between the maximum element and the minimum element in nums equals nums.length - 1... | [Python3] sliding window | 218 | minimum-number-of-operations-to-make-array-continuous | 0.458 | ye15 | Hard | 28,030 | 2,009 |
final value of variable after performing operations | class Solution:
def finalValueAfterOperations(self, operations: List[str]) -> int:
x = 0
for o in operations:
if '+' in o:
x += 1
else:
x -= 1
return x | https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1472568/Python3-A-Simple-Solution-and-A-One-Line-Solution | 18 | There is a programming language with only four operations and one variable X:
++X and X++ increments the value of the variable X by 1.
--X and X-- decrements the value of the variable X by 1.
Initially, the value of X is 0.
Given an array of strings operations containing a list of operations, return the final value of ... | [Python3] A Simple Solution and A One Line Solution | 1,800 | final-value-of-variable-after-performing-operations | 0.888 | terrencetang | Easy | 28,035 | 2,011 |
sum of beauty in the array | class Solution:
def sumOfBeauties(self, nums: List[int]) -> int:
beauty=[0]*len(nums)
for i in range(1,len(nums)-1):
leftarr=nums[:i]
rightarr=nums[i+1:]
if(max(leftarr)<nums[i] and min(rightarr)>nums[i]):
beauty[i]=2
elif(nums[i-1]<num... | https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1477177/Python3-or-Brute-Force-(TLE)-and-O(n)-solution-with-explanation-or-86ile-runtime | 1 | You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:
2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.
0, if none of the p... | Python3 | Brute Force (TLE) and O(n) solution with explanation | 86%ile runtime | 54 | sum-of-beauty-in-the-array | 0.467 | aaditya47 | Medium | 28,091 | 2,012 |
longest subsequence repeated k times | class Solution:
def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:
freq = [0] * 26
for ch in s: freq[ord(ch)-97] += 1
cand = [chr(i+97) for i, x in enumerate(freq) if x >= k] # valid candidates
def fn(ss):
"""Return True if ss is a k-repeate... | https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1477019/Python3-bfs | 9 | You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
A subsequence seq is repeated k... | [Python3] bfs | 409 | longest-subsequence-repeated-k-times | 0.556 | ye15 | Hard | 28,101 | 2,014 |
maximum difference between increasing elements | class Solution:
def maximumDifference(self, nums: List[int]) -> int:
ans = -1
prefix = inf
for i, x in enumerate(nums):
if i and x > prefix: ans = max(ans, x - prefix)
prefix = min(prefix, x)
return ans | https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1486318/Python3-prefix-min | 6 | Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
Return the maximum difference. If no such i and j exists, return -1.
Example 1:
Input: nums = [7,1,5,4]
Output: 4
Explanation:
The maximum ... | [Python3] prefix min | 557 | maximum-difference-between-increasing-elements | 0.535 | ye15 | Easy | 28,104 | 2,016 |
grid game | class Solution(object):
def gridGame(self, grid):
top, bottom = grid
top_sum = sum(top)
bottom_sum = 0
res = float('inf')
for i in range(len(top)):
top_sum -= top[i]
res = min(res, max(top_sum, bottom_sum))
bottom_sum += b... | https://leetcode.com/problems/grid-game/discuss/1486349/Python-Easy | 3 | You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.
Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down (... | Python - Easy | 181 | grid-game | 0.43 | lokeshsenthilkumar | Medium | 28,129 | 2,017 |
check if word can be placed in crossword | class Solution:
def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:
for x in board, zip(*board):
for row in x:
for s in "".join(row).split("#"):
for w in word, word[::-1]:
if len(s) == len(w) and all(ss in (" ... | https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486326/Python3-row-by-row-and-col-by-col | 10 | You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.
A word can be placed horizontally (left to right or right to left) or vertically (top... | [Python3] row-by-row & col-by-col | 1,300 | check-if-word-can-be-placed-in-crossword | 0.494 | ye15 | Medium | 28,137 | 2,018 |
the score of students solving math expression | class Solution:
def scoreOfStudents(self, s: str, answers: List[int]) -> int:
@cache
def fn(lo, hi):
"""Return possible answers of s[lo:hi]."""
if lo+1 == hi: return {int(s[lo])}
ans = set()
for mid in range(lo+1, hi, 2):
for... | https://leetcode.com/problems/the-score-of-students-solving-math-expression/discuss/1487285/Python3-somewhat-dp | 6 | You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by followi... | [Python3] somewhat dp | 267 | the-score-of-students-solving-math-expression | 0.338 | ye15 | Hard | 28,146 | 2,019 |
convert 1d array into 2d array | class Solution:
def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:
ans = []
if len(original) == m*n:
for i in range(0, len(original), n):
ans.append(original[i:i+n])
return ans | https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1499000/Python3-simulation | 36 | You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.
The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the construct... | [Python3] simulation | 2,800 | convert-1d-array-into-2d-array | 0.584 | ye15 | Easy | 28,148 | 2,022 |
number of pairs of strings with concatenation equal to target | class Solution:
def numOfPairs(self, nums: List[str], target: str) -> int:
freq = Counter(nums)
ans = 0
for k, v in freq.items():
if target.startswith(k):
suffix = target[len(k):]
ans += v * freq[suffix]
if k == suffix: ans -= fr... | https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499007/Python3-freq-table | 36 | Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Example 1:
Input: nums = ["777","7","77","77"], target = "7777"
Output: 4
Explanation: Valid pairs are:
- (0, 1): "777" + "7"
- (1... | [Python3] freq table | 2,600 | number-of-pairs-of-strings-with-concatenation-equal-to-target | 0.729 | ye15 | Medium | 28,182 | 2,023 |
maximize the confusion of an exam | class Solution:
def maxConsecutiveAnswers(self, string: str, k: int) -> int:
result = 0
j = 0
count1 = k
for i in range(len(string)):
if count1 == 0 and string[i] == "F":
while string[j] != "F":
j+=1
count1+=1
j+=1
if string[i] == "F":
if count1 > 0:
count1-=1
if i - j + 1... | https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1951750/WEEB-DOES-PYTHONC%2B%2B-SLIDING-WINDOW | 2 | A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).
You are given a string answerKey, where answerKey[i] is the origin... | WEEB DOES PYTHON/C++ SLIDING WINDOW | 95 | maximize-the-confusion-of-an-exam | 0.598 | Skywalker5423 | Medium | 28,206 | 2,024 |
maximum number of ways to partition an array | class Solution:
def waysToPartition(self, nums: List[int], k: int) -> int:
prefix = [0]
loc = defaultdict(list)
for i, x in enumerate(nums):
prefix.append(prefix[-1] + x)
if i < len(nums)-1: loc[prefix[-1]].append(i)
ans = 0
if prefix[-1] % ... | https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/discuss/1499024/Python3-binary-search | 2 | You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer k. You can choose to cha... | [Python3] binary search | 227 | maximum-number-of-ways-to-partition-an-array | 0.321 | ye15 | Hard | 28,221 | 2,025 |
minimum moves to convert string | class Solution:
def minimumMoves(self, s: str) -> int:
ans = i = 0
while i < len(s):
if s[i] == "X":
ans += 1
i += 3
else: i += 1
return ans | https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1500215/Python3-scan | 28 | You are given a string s consisting of n characters which are either 'X' or 'O'.
A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.
Return the minimum number of moves required so that all the characters... | [Python3] scan | 1,200 | minimum-moves-to-convert-string | 0.537 | ye15 | Easy | 28,223 | 2,027 |
find missing observations | class Solution:
def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:
missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)
if rem == 0:
if 1 <= missing_val <= 6:
return [missing_val] * n
elif 1 <= missing_val < 6:
retu... | https://leetcode.com/problems/find-missing-observations/discuss/1506196/Divmod-and-list-comprehension-96-speed | 2 | You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.
You are given an integer array rolls of length m where rolls[i] is the val... | Divmod and list comprehension, 96% speed | 133 | find-missing-observations | 0.439 | EvgenySH | Medium | 28,241 | 2,028 |
stone game ix | class Solution:
def stoneGameIX(self, stones: List[int]) -> bool:
freq = defaultdict(int)
for x in stones: freq[x % 3] += 1
if freq[0]%2 == 0: return freq[1] and freq[2]
return abs(freq[1] - freq[2]) >= 3 | https://leetcode.com/problems/stone-game-ix/discuss/1500343/Python3-freq-table | 3 | Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.
Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The pl... | [Python3] freq table | 165 | stone-game-ix | 0.264 | ye15 | Medium | 28,250 | 2,029 |
smallest k length subsequence with occurrences of a letter | class Solution:
def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:
counts,total = 0, 0
n = len(s)
for ch in s:
if ch==letter:
total +=1
stack = []
occ = 0
for idx,ch in enumerate(s):
if ch==lette... | https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/discuss/1502134/PYTHON3-O(n)-using-stack-with-explanation | 2 | You are given a string s, an integer k, a letter letter, and an integer repetition.
Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.
A subsequence is a s... | [PYTHON3] O(n) using stack with explanation | 300 | smallest-k-length-subsequence-with-occurrences-of-a-letter | 0.387 | irt | Hard | 28,252 | 2,030 |
two out of three | class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:
s1, s2, s3 = set(nums1), set(nums2), set(nums3)
return (s1&s2) | (s2&s3) | (s1&s3) | https://leetcode.com/problems/two-out-of-three/discuss/1513311/Python3-set | 20 | Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.
Example 1:
Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output: [3,2]
Explanation: The values that are present... | [Python3] set | 1,400 | two-out-of-three | 0.726 | ye15 | Easy | 28,255 | 2,032 |
minimum operations to make a uni value grid | class Solution:
def minOperations(self, grid: List[List[int]], x: int) -> int:
vals = [x for row in grid for x in row]
if len(set(val%x for val in vals)) > 1: return -1 # impossible
median = sorted(vals)[len(vals)//2] # O(N) possible via "quick select"
return sum(abs(val - median)//x... | https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1513319/Python3-median-4-line | 21 | You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.
A uni-value grid is a grid where all the elements of it are equal.
Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.
Exampl... | [Python3] median 4-line | 1,100 | minimum-operations-to-make-a-uni-value-grid | 0.524 | ye15 | Medium | 28,297 | 2,033 |
partition array into two arrays to minimize sum difference | class Solution:
def minimumDifference(self, nums: List[int]) -> int:
N = len(nums) // 2 # Note this is N/2, ie no. of elements required in each.
def get_sums(nums): # generate all combinations sum of k elements
ans = {}
N = len(nums)
for k in range(1, N+1... | https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/discuss/1513435/Python-or-Easy-Explanation-or-Meet-in-the-Middle | 117 | You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.
Return the minimum possible absolute difference.
Example 1:
Input: nums =... | Python | Easy Explanation | Meet in the Middle | 8,800 | partition-array-into-two-arrays-to-minimize-sum-difference | 0.183 | malraharsh | Hard | 28,307 | 2,035 |
minimum number of moves to seat everyone | class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
seats.sort()
students.sort()
return sum(abs(seat - student) for seat, student in zip(seats, students)) | https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/discuss/1539518/O(n)-counting-sort-in-Python | 7 | There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.
You may perform the following move any number of times:
Increase or decrease the ... | O(n) counting sort in Python | 841 | minimum-number-of-moves-to-seat-everyone | 0.821 | mousun224 | Easy | 28,310 | 2,037 |
remove colored pieces if both neighbors are the same color | class Solution:
def winnerOfGame(self, s: str) -> bool:
a = b = 0
for i in range(1,len(s)-1):
if s[i-1] == s[i] == s[i+1]:
if s[i] == 'A':
a += 1
else:
b += 1
return a>b | https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/discuss/1524153/C%2B%2BPythonJava-Count-%22AAA%22-and-%22BBB%22 | 75 | There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.
Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.
Alice is o... | [C++/Python/Java] Count "AAA" and "BBB" | 5,000 | remove-colored-pieces-if-both-neighbors-are-the-same-color | 0.582 | lokeshsenthilkumar | Medium | 28,351 | 2,038 |
the time when the network becomes idle | class Solution:
def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:
graph = {}
for u, v in edges:
graph.setdefault(u, []).append(v)
graph.setdefault(v, []).append(u)
dist = [-1]*len(graph)
dist[0] = 0
val = 0
... | https://leetcode.com/problems/the-time-when-the-network-becomes-idle/discuss/1524183/Python3-graph | 5 | There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience... | [Python3] graph | 176 | the-time-when-the-network-becomes-idle | 0.508 | ye15 | Medium | 28,361 | 2,039 |
kth smallest product of two sorted arrays | class Solution:
def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:
def fn(val):
"""Return count of products <= val."""
ans = 0
for x in nums1:
if x < 0: ans += len(nums2) - bisect_left(nums2, ceil(val/x))
... | https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/discuss/1524190/Python3-binary-search | 8 | Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.
Example 1:
Input: nums1 = [2,5], nums2 = [3,4], k = 2
Output: 8
Explanation: The 2 smallest products are:
- nums1[0... | [Python3] binary search | 1,300 | kth-smallest-product-of-two-sorted-arrays | 0.291 | ye15 | Hard | 28,368 | 2,040 |
check if numbers are ascending in a sentence | class Solution:
def areNumbersAscending(self, s: str) -> bool:
nums = [int(w) for w in s.split() if w.isdigit()]
return all(nums[i-1] < nums[i] for i in range(1, len(nums))) | https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1525219/Python3-2-line | 24 | A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.
For example, "a puppy has 2 eyes 4 legs" is a sentence with seven tokens: "2" and "4" ... | [Python3] 2-line | 1,400 | check-if-numbers-are-ascending-in-a-sentence | 0.661 | ye15 | Easy | 28,372 | 2,042 |
count number of maximum bitwise or subsets | class Solution:
def countMaxOrSubsets(self, nums: List[int]) -> int:
target = reduce(or_, nums)
@cache
def fn(i, mask):
"""Return number of subsets to get target."""
if mask == target: return 2**(len(nums)-i)
if i == len(nums): return 0
... | https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525225/Python3-top-down-dp | 8 | Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if... | [Python3] top-down dp | 729 | count-number-of-maximum-bitwise-or-subsets | 0.748 | ye15 | Medium | 28,406 | 2,044 |
second minimum time to reach destination | class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u-1].append(v-1)
graph[v-1].append(u-1)
pq = [(0, 0)]
seen = [[] for _ in range(n)]
least =... | https://leetcode.com/problems/second-minimum-time-to-reach-destination/discuss/1525227/Python3-Dijkstra-and-BFS | 6 | A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected... | [Python3] Dijkstra & BFS | 462 | second-minimum-time-to-reach-destination | 0.389 | ye15 | Hard | 28,417 | 2,045 |
number of valid words in a sentence | class Solution:
def countValidWords(self, sentence: str) -> int:
def fn(word):
"""Return true if word is valid."""
seen = False
for i, ch in enumerate(word):
if ch.isdigit() or ch in "!.," and i != len(word)-1: return False
elif... | https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537625/Python3-check-words | 20 | A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.
A token is a valid word if all three of the following are true:
It only c... | [Python3] check words | 1,200 | number-of-valid-words-in-a-sentence | 0.295 | ye15 | Easy | 28,420 | 2,047 |
next greater numerically balanced number | class Solution:
def nextBeautifulNumber(self, n: int) -> int:
while True:
n += 1
nn = n
freq = defaultdict(int)
while nn:
nn, d = divmod(nn, 10)
freq[d] += 1
if all(k == v for k, v in freq.items()): return n | https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1537537/Python3-brute-force | 3 | An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.
Given an integer n, return the smallest numerically balanced number strictly greater than n.
Example 1:
Input: n = 1
Output: 22
Explanation:
22 is numerically balanced since:
- The digit 2 o... | [Python3] brute-force | 151 | next-greater-numerically-balanced-number | 0.471 | ye15 | Medium | 28,436 | 2,048 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.