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 number of operations to make arrays similar | class Solution:
def makeSimilar(self, A: List[int], B: List[int]) -> int:
if sum(A)!=sum(B): return 0
# The first intuition is that only odd numbers can be chaged to odd numbers and even to even hence separate them
# Now minimum steps to making the target to highest number in B is by convert... | https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar/discuss/2734139/Python-or-Simple-OddEven-Sorting-O(nlogn)-or-Walmart-OA-India-or-Simple-Explanation | 3 | You are given two positive integer arrays nums and target, of the same length.
In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:
set nums[i] = nums[i] + 2 and
set nums[j] = nums[j] - 2.
Two arrays are considered to be similar if the frequency of each element is the sam... | Python | Simple Odd/Even Sorting O(nlogn) | Walmart OA India | Simple Explanation | 245 | minimum-number-of-operations-to-make-arrays-similar | 0.649 | tarushfx | Hard | 33,552 | 2,449 |
odd string difference | class Solution:
def oddString(self, words: List[str]) -> str:
k=len(words[0])
arr=[]
for i in words:
l=[]
for j in range(1,k):
diff=ord(i[j])-ord(i[j-1])
l.append(diff)
arr.append(l)
for i in range(len(arr)):
... | https://leetcode.com/problems/odd-string-difference/discuss/2774188/Easy-to-understand-python-solution | 2 | You are given an array of equal-length strings words. Assume that the length of each string is n.
Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters i... | Easy to understand python solution | 87 | odd-string-difference | 0.595 | Vistrit | Easy | 33,559 | 2,451 |
words within two edits of dictionary | class Solution:
def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:
# T: ((N + M) * L^3), S: O(M * L^3)
N, M, L = len(queries), len(dictionary), len(queries[0])
validWords = set()
for word in dictionary:
for w in self.wordModifications... | https://leetcode.com/problems/words-within-two-edits-of-dictionary/discuss/2757378/Python-Simple-HashSet-solution-O((N%2BM)-*-L3) | 2 | You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.
In one edit you can take a word from queries, and change any letter in it to any other letter. Find all words from queries that, after a maximum of two edits, equal some word ... | [Python] Simple HashSet solution O((N+M) * L^3) | 45 | words-within-two-edits-of-dictionary | 0.603 | rcomesan | Medium | 33,583 | 2,452 |
destroy sequential targets | class Solution:
def destroyTargets(self, nums: List[int], space: int) -> int:
# example: nums = [3,7,8,1,1,5], space = 2
groups = defaultdict(list)
for num in nums:
groups[num % space].append(num)
# print(groups) # defaultdict(<class 'list'>, {1: [3, 7, 1, 1, 5], 0: [... | https://leetcode.com/problems/destroy-sequential-targets/discuss/2756374/Python-or-Greedy-or-Group-or-Example | 3 | You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * spac... | Python | Greedy | Group | Example | 122 | destroy-sequential-targets | 0.373 | yzhao156 | Medium | 33,608 | 2,453 |
next greater element iv | class Solution:
def secondGreaterElement(self, nums: List[int]) -> List[int]:
ans = [-1] * len(nums)
s, ss = [], []
for i, x in enumerate(nums):
while ss and nums[ss[-1]] < x: ans[ss.pop()] = x
buff = []
while s and nums[s[-1]] < x: buff.append(s.pop())
... | https://leetcode.com/problems/next-greater-element-iv/discuss/2757259/Python3-intermediate-stack | 1 | You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.
The second greater integer of nums[i] is nums[j] such that:
j > i
nums[j] > nums[i]
There exists exactly one index k such that nums[k] > nums[i] and i < k < j.
If there is no suc... | [Python3] intermediate stack | 38 | next-greater-element-iv | 0.396 | ye15 | Hard | 33,619 | 2,454 |
average value of even numbers that are divisible by three | class Solution:
def averageValue(self, nums: List[int]) -> int:
l=[]
for i in nums:
if i%6==0:
l.append(i)
return sum(l)//len(l) if len(l)>0 else 0 | https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three/discuss/2770799/Easy-Python-Solution | 2 | Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.
Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.
Example 1:
Input: nums = [1,3,6,10,12,15]
Output: 9
Explanation: 6 and 12 are ... | Easy Python Solution | 107 | average-value-of-even-numbers-that-are-divisible-by-three | 0.58 | Vistrit | Easy | 33,623 | 2,455 |
most popular video creator | class Solution:
def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]:
memo = {}
#tracking the max popular video count
overall_max_popular_video_count = -1
#looping over the creators
for i in range(len(creators)):
if crea... | https://leetcode.com/problems/most-popular-video-creator/discuss/2758104/Python-Hashmap-solution-or-No-Sorting | 5 | You are given two string arrays creators and ids, and an integer array views, all of length n. The ith video on a platform was created by creator[i], has an id of ids[i], and has views[i] views.
The popularity of a creator is the sum of the number of views on all of the creator's videos. Find the creator with the highe... | Python Hashmap solution | No Sorting | 330 | most-popular-video-creator | 0.441 | dee7 | Medium | 33,656 | 2,456 |
minimum addition to make integer beautiful | class Solution:
def makeIntegerBeautiful(self, n: int, target: int) -> int:
i=n
l=1
while i<=10**12:
s=0
for j in str(i):
s+=int(j)
if s<=target:
return i-n
i//=10**l
i+=1
i*=10**l
... | https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/discuss/2758079/Check-next-10-next-100-next-1000-and-so-on... | 2 | You are given two positive integers n and target.
An integer is considered beautiful if the sum of its digits is less than or equal to target.
Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.
Example 1:
Input: n = ... | Check next 10, next 100, next 1000 and so on... | 97 | minimum-addition-to-make-integer-beautiful | 0.368 | shreyasjain0912 | Medium | 33,677 | 2,457 |
height of binary tree after subtree removal queries | class Solution:
def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
depth = {}
height = {}
nodes_at_depth = {}
max_height = 0
def rec(n, d):
nonlocal max_height
if n is None:
return 0
height_b... | https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/discuss/2760795/Python3-Triple-dict-depth-height-nodes_at_depth | 0 | You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m.
You have to perform m independent queries on the tree where in the ith query you do the following:
Remove the subtree rooted at the node with the value queries[i] from t... | Python3 Triple dict depth, height, nodes_at_depth | 12 | height-of-binary-tree-after-subtree-removal-queries | 0.354 | godshiva | Hard | 33,696 | 2,458 |
apply operations to an array | class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
nums[i]*=2
nums[i+1]=0
temp = []
zeros = []
a=nums
for i in range(len(a)):
if a... | https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786435/Python-Simple-Python-Solution-89-ms | 3 | You are given a 0-indexed array nums of size n consisting of non-negative integers.
You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums:
If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise... | [ Python ] 🐍🐍 Simple Python Solution ✅✅ 89 ms | 31 | apply-operations-to-an-array | 0.671 | sourav638 | Easy | 33,698 | 2,460 |
maximum sum of distinct subarrays with length k | class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
seen = collections.Counter(nums[:k]) #from collections import Counter (elements and their respective count are stored as a dictionary)
summ = sum(nums[:k])
res = 0
if len(seen) ==... | https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783646/Python-easy-solution-using-libraries | 4 | You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:
The length of the subarray is k, and
All the elements of the subarray are distinct.
Return the maximum subarray sum of all the subarrays that meet the conditions. If no su... | ✅✅Python easy solution using libraries | 224 | maximum-sum-of-distinct-subarrays-with-length-k | 0.344 | Sumit6258 | Medium | 33,748 | 2,461 |
total cost to hire k workers | class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
q = costs[:candidates]
qq = costs[max(candidates, len(costs)-candidates):]
heapify(q)
heapify(qq)
ans = 0
i, ii = candidates, len(costs)-candidates-1
for _ in range(k):
... | https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783147/Python3-priority-queues | 24 | You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.
You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:
You will run k sessions and hire exactly one worker in each session.
In each hiring session, choose the... | [Python3] priority queues | 1,200 | total-cost-to-hire-k-workers | 0.374 | ye15 | Medium | 33,780 | 2,462 |
minimum total distance traveled | class Solution:
def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:
robot.sort()
factory.sort()
m, n = len(robot), len(factory)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m): dp[i][-1] = inf
for j in range(n-1, -1, -1):
... | https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783245/Python3-O(MN)-DP | 13 | There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at... | [Python3] O(MN) DP | 769 | minimum-total-distance-traveled | 0.397 | ye15 | Hard | 33,799 | 2,463 |
number of distinct averages | class Solution:
def distinctAverages(self, nums: List[int]) -> int:
av=[]
nums.sort()
while nums:
av.append((nums[-1]+nums[0])/2)
nums.pop(-1)
nums.pop(0)
return len(set(av)) | https://leetcode.com/problems/number-of-distinct-averages/discuss/2817811/Easy-Python-Solution | 2 | You are given a 0-indexed integer array nums of even length.
As long as nums is not empty, you must repetitively:
Find the minimum number in nums and remove it.
Find the maximum number in nums and remove it.
Calculate the average of the two removed numbers.
The average of two numbers a and b is (a + b) / 2.
For example... | Easy Python Solution | 75 | number-of-distinct-averages | 0.588 | Vistrit | Easy | 33,805 | 2,465 |
count ways to build good strings | class Solution:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
def recursive(s,ans):
if len(s)>=low and len(s)<=high:
ans+=[s]
if len(s)>high:
return
recursive(s+"0"*zero,ans)
recursive(s+"1"*one,a... | https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2813134/Easy-solution-from-Recursion-to-memoization-oror-3-approaches-oror-PYTHON3 | 1 | Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:
Append the character '0' zero times.
Append the character '1' one times.
This can be performed any number of times.
A good string is a string constructed by the... | Easy solution from Recursion to memoization || 3 approaches || PYTHON3 | 32 | count-ways-to-build-good-strings | 0.419 | dabbiruhaneesh | Medium | 33,846 | 2,466 |
most profitable path in a tree | class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
path_b = set([bob])
lvl_b = {bob:0}
g = defaultdict(list)
for u, v in edges:
g[u].append(v)
g[v].append(u)
n = len(amount)
node_lvl = [0] ... | https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2838006/BFS-%2B-Graph-%2B-level-O(n) | 0 | There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
At every node i, there is a gate. You are also given an array of even integers amount,... | BFS + Graph + level, O(n) | 2 | most-profitable-path-in-a-tree | 0.464 | goodgoodwish | Medium | 33,859 | 2,467 |
split message based on limit | class Solution:
def splitMessage(self, message: str, limit: int) -> List[str]:
def splitable_within(parts_limit):
# check the message length achievable with <parts_limit> parts
length = sum(limit - len(str(i)) - len(str(parts_limit)) - 3 for i in range(1, parts_limit + 1))
... | https://leetcode.com/problems/split-message-based-on-limit/discuss/2807491/Python-Simple-dumb-O(N)-solution | 2 | You are given a string, message, and a positive integer, limit.
You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up ... | [Python] Simple dumb O(N) solution | 62 | split-message-based-on-limit | 0.483 | vudinhhung942k | Hard | 33,868 | 2,468 |
convert the temperature | class Solution:
def convertTemperature(self, celsius: float) -> List[float]:
return [(celsius + 273.15),(celsius * 1.80 + 32.00)] | https://leetcode.com/problems/convert-the-temperature/discuss/2839560/Python-or-Easy-Solution | 4 | You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.
You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit].
Return the array ans. Answers within 10-5 of the actual answer will be accepted.
... | Python | Easy Solution✔ | 127 | convert-the-temperature | 0.909 | manayathgeorgejames | Easy | 33,880 | 2,469 |
number of subarrays with lcm equal to k | class Solution:
def subarrayLCM(self, nums: List[int], k: int) -> int:
def find_lcm(num1, num2):
if(num1>num2):
num = num1
den = num2
else:
num = num2
den = num1
rem = num % den
while(rem != 0):
... | https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808943/Beginners-Approach-%3A | 1 | Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The least common multiple of an array is the smallest positive integer that is divisible by all... | Beginners Approach : | 57 | number-of-subarrays-with-lcm-equal-to-k | 0.388 | goxy_coder | Medium | 33,919 | 2,470 |
minimum number of operations to sort a binary tree by level | class Solution:
def minimumOperations(self, root: Optional[TreeNode]) -> int:
ans = 0
queue = deque([root])
while queue:
vals = []
for _ in range(len(queue)):
node = queue.popleft()
vals.append(node.val)
if node.left:... | https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2808960/Python3-BFS | 6 | You are given the root of a binary tree with unique values.
In one operation, you can choose any two nodes at the same level and swap their values.
Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.
The level of a node is the number of edges along the ... | [Python3] BFS | 567 | minimum-number-of-operations-to-sort-a-binary-tree-by-level | 0.629 | ye15 | Medium | 33,930 | 2,471 |
maximum number of non overlapping palindrome substrings | class Solution:
def maxPalindromes(self, s: str, k: int) -> int:
n = len(s)
dp = [0] * (n + 1)
for i in range(k, n + 1):
dp[i] = dp[i - 1]
for length in range(k, k + 2):
j = i - length
if j < 0:
break
... | https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2808845/Python3-DP-with-Explanations-or-Only-Check-Substrings-of-Length-k-and-k-%2B-1 | 11 | You are given a string s and a positive integer k.
Select a set of non-overlapping substrings from the string s that satisfy the following conditions:
The length of each substring is at least k.
Each substring is a palindrome.
Return the maximum number of substrings in an optimal selection.
A substring is a contiguous ... | [Python3] DP with Explanations | Only Check Substrings of Length k and k + 1 | 542 | maximum-number-of-non-overlapping-palindrome-substrings | 0.366 | xil899 | Hard | 33,937 | 2,472 |
number of unequal triplets in array | class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
c = Counter(nums)
res = 0
left = 0
right = len(nums)
for _, freq in c.items():
right -= freq
res += left * freq * right
left += freq
retur... | https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2834169/Python-Hashmap-O(n)-with-diagrams | 10 | You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions:
0 <= i < j < k < nums.length
nums[i], nums[j], and nums[k] are pairwise distinct.
In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k].
Return the number of trip... | Python Hashmap O(n) with diagrams | 242 | number-of-unequal-triplets-in-array | 0.699 | cheatcode-ninja | Easy | 33,956 | 2,475 |
closest nodes queries in a binary search tree | class Solution(object):
def closestNodes(self, root, queries):
def dfs(root, arr):
if not root: return
dfs(root.left, arr)
arr.append(root.val)
dfs(root.right, arr)
arr = []
dfs(root, arr)
ans = []
n = len(arr)
for key i... | https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2831726/Binary-Search-Approach-or-Python | 11 | You are given the root of a binary search tree and an array queries of size n consisting of positive integers.
Find a 2D array answer of size n where answer[i] = [mini, maxi]:
mini is the largest value in the tree that is smaller than or equal to queries[i]. If a such value does not exist, add -1 instead.
maxi is the s... | Binary Search Approach | Python | 975 | closest-nodes-queries-in-a-binary-search-tree | 0.404 | its_krish_here | Medium | 33,977 | 2,476 |
minimum fuel cost to report to the capital | class Solution:
def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:
n = len(roads) + 1
graph = defaultdict(list)
for a, b in roads:
graph[a].append(b)
graph[b].append(a)
def dfs(u, p):
cnt = 1
for v in graph[u... | https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2834516/Python-DFS-Picture-explanation-O(N) | 33 | There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting c... | [Python] DFS - Picture explanation - O(N) | 528 | minimum-fuel-cost-to-report-to-the-capital | 0.53 | hiepit | Medium | 33,984 | 2,477 |
number of beautiful partitions | class Solution:
def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:
n = len(s)
MOD = 10**9 + 7
def isPrime(c):
return c in ['2', '3', '5', '7']
@lru_cache(None)
def dp(i, k):
if k == 0 and i <= n:
return 1
... | https://leetcode.com/problems/number-of-beautiful-partitions/discuss/2833244/Python-Top-down-DP-Clean-and-Concise-O(N-*-K) | 21 | You are given a string s that consists of the digits '1' to '9' and two integers k and minLength.
A partition of s is called beautiful if:
s is partitioned into k non-intersecting substrings.
Each substring has a length of at least minLength.
Each substring starts with a prime digit and ends with a non-prime digit. Pri... | [Python] Top down DP - Clean & Concise - O(N * K) | 382 | number-of-beautiful-partitions | 0.294 | hiepit | Hard | 33,997 | 2,478 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.