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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
count nodes with the highest score | class Solution:
def countHighestScoreNodes(self, parents: List[int]) -> int:
graph = collections.defaultdict(list)
for node, parent in enumerate(parents): # build graph
graph[parent].append(node)
n = len(parents) # total number of nodes
d = collec... | https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/1537603/Python-3-or-Graph-DFS-Post-order-Traversal-O(N)-or-Explanation | 63 | There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.
Each node has a score. To find the score of a node, consider if th... | Python 3 | Graph, DFS, Post-order Traversal, O(N) | Explanation | 3,300 | count-nodes-with-the-highest-score | 0.471 | idontknoooo | Medium | 28,444 | 2,049 |
parallel courses iii | class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = { course:[] for course in range(n)}
inDegree = [0]*n
# 1- build graph
# convert 1-base into 0-baseindexes and add to graph
# Note: choose Prev->next since it helps to p... | https://leetcode.com/problems/parallel-courses-iii/discuss/1546258/Python-solution-using-topology-sort-and-BFS | 1 | You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given ... | Python solution using topology sort and BFS | 91 | parallel-courses-iii | 0.595 | MAhmadian | Hard | 28,452 | 2,050 |
kth distinct string in an array | class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
freq = Counter(arr)
for x in arr:
if freq[x] == 1: k -= 1
if k == 0: return x
return "" | https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549003/Python3-freq-table | 19 | A distinct string is a string that is present only once in an array.
Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".
Note that the strings are considered in the order in which they appear in the array.... | [Python3] freq table | 1,200 | kth-distinct-string-in-an-array | 0.718 | ye15 | Easy | 28,458 | 2,053 |
two best non overlapping events | class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
events.sort()
heap = []
res2,res1 = 0,0
for s,e,p in events:
while heap and heap[0][0]<s:
res1 = max(res1,heapq.heappop(heap)[1])
res2 = max(res2,res1+p)
heapq.heappush(heap,(e,p))
... | https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1549284/Heap-oror-very-Easy-oror-Well-Explained | 13 | You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values ... | ππ Heap || very-Easy || Well-Explained π | 502 | two-best-non-overlapping-events | 0.45 | abhi9Rai | Medium | 28,492 | 2,054 |
plates between candles | class Solution:
def platesBetweenCandles(self, s: str, qs: List[List[int]]) -> List[int]:
n=len(s)
prefcandle=[-1]*n #this stores the position of closest candle from current towards left
suffcandle=[0]*n #this stores the position of closest candle from current towards right
... | https://leetcode.com/problems/plates-between-candles/discuss/1549304/100-faster-Linear-Python-solution-or-Prefix-sum-or-O(N) | 12 | There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.
You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes th... | 100 % faster Linear Python solution | Prefix sum | O(N) | 1,200 | plates-between-candles | 0.444 | acloj97 | Medium | 28,496 | 2,055 |
number of valid move combinations on chessboard | class Solution:
BOARD_SIZE = 8
def diag(self, r, c):
# Return all diagonal indices except (r, c)
# Diagonal indices has the same r - c
inv = r - c
result = []
for ri in range(self.BOARD_SIZE):
ci = ri - inv
if 0 <= ci < self.BOARD_SIZE and ri ... | https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/discuss/2331905/Python3-or-DFS-with-backtracking-or-Clean-code-with-comments | 1 | There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates t... | Python3 | DFS with backtracking | Clean code with comments | 58 | number-of-valid-move-combinations-on-chessboard | 0.59 | snorkin | Hard | 28,506 | 2,056 |
smallest index with equal value | class Solution:
def smallestEqual(self, nums: List[int]) -> int:
return next((i for i, x in enumerate(nums) if i%10 == x), -1) | https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1549993/Python3-1-line | 10 | Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.
x mod y denotes the remainder when x is divided by y.
Example 1:
Input: nums = [0,1,2]
Output: 0
Explanation:
i=0: 0 mod 10 = 0 == nums[0].
i=1: 1 mod 10 = 1 == nums[1].
i=2: 2... | [Python3] 1-line | 646 | smallest-index-with-equal-value | 0.712 | ye15 | Easy | 28,508 | 2,057 |
find the minimum and maximum number of nodes between critical points | class Solution:
def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:
min_res = math.inf
min_point = max_point = last_point = None
prev_val = head.val
head = head.next
i = 1
while head.next:
if ((head.next.val < head.val and prev_val... | https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1551353/Python-O(1)-memory-O(n)-time-beats-100.00 | 1 | A critical point in a linked list is defined as either a local maxima or a local minima.
A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.
A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.... | Python O(1) memory, O(n) time beats 100.00% | 125 | find-the-minimum-and-maximum-number-of-nodes-between-critical-points | 0.57 | dereky4 | Medium | 28,534 | 2,058 |
minimum operations to convert number | class Solution:
def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:
ans = 0
seen = {start}
queue = deque([start])
while queue:
for _ in range(len(queue)):
val = queue.popleft()
if val == goal: return ans
... | https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550007/Python3-bfs | 17 | You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x:
If 0 <= x ... | [Python3] bfs | 1,200 | minimum-operations-to-convert-number | 0.473 | ye15 | Medium | 28,540 | 2,059 |
check if an original string exists given two encoded strings | class Solution:
def possiblyEquals(self, s1: str, s2: str) -> bool:
def gg(s):
"""Return possible length"""
ans = [int(s)]
if len(s) == 2:
if s[1] != '0': ans.append(int(s[0]) + int(s[1]))
return ans
elif len(s) == 3:... | https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/discuss/1550012/Python3-dp | 82 | An original string, consisting of lowercase English letters, can be encoded by the following steps:
Arbitrarily split it into a sequence of some number of non-empty substrings.
Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).
Concatenate the seque... | [Python3] dp | 6,200 | check-if-an-original-string-exists-given-two-encoded-strings | 0.407 | ye15 | Hard | 28,550 | 2,060 |
count vowel substrings of a string | class Solution:
def countVowelSubstrings(self, word: str) -> int:
ans = 0
freq = defaultdict(int)
for i, x in enumerate(word):
if x in "aeiou":
if not i or word[i-1] not in "aeiou":
jj = j = i # set anchor
freq.clear()
... | https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563707/Python3-sliding-window-O(N) | 16 | A substring is a contiguous (non-empty) sequence of characters within a string.
A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.
Given a string word, return the number of vowel substrings in word.
Example 1:
Input: word = "aeiouu"
Outpu... | [Python3] sliding window O(N) | 1,900 | count-vowel-substrings-of-a-string | 0.659 | ye15 | Easy | 28,552 | 2,062 |
vowels of all substrings | class Solution:
def countVowels(self, word: str) -> int:
count = 0
sz = len(word)
for pos in range(sz):
if word[pos] in 'aeiou':
count += (sz - pos) * (pos + 1)
return count | https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564075/Detailed-explanation-of-why-(len-pos)-*-(pos-%2B-1)-works | 77 | Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word.
A substring is a contiguous (non-empty) sequence of characters within a string.
Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calcul... | Detailed explanation of why (len - pos) * (pos + 1) works | 2,000 | vowels-of-all-substrings | 0.551 | bitmasker | Medium | 28,564 | 2,063 |
minimized maximum of products distributed to any store | class Solution:
def minimizedMaximum(self, n: int, quantities: List[int]) -> int:
lo, hi = 1, max(quantities)
while lo < hi:
mid = lo + hi >> 1
if sum(ceil(qty/mid) for qty in quantities) <= n: hi = mid
else: lo = mid + 1
return lo | https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1563731/Python3-binary-search | 9 | You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.
You need to distribute all products to the retail stores follow... | [Python3] binary search | 296 | minimized-maximum-of-products-distributed-to-any-store | 0.5 | ye15 | Medium | 28,577 | 2,064 |
maximum path quality of a graph | class Solution:
def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:
ans = 0
graph = collections.defaultdict(dict)
for u, v, t in edges:
graph[u][v] = t
graph[v][u] = t
def dfs(curr, visited, score, cost):
... | https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1564102/Python-DFS-and-BFS-solution | 2 | There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the... | [Python] DFS and BFS solution | 424 | maximum-path-quality-of-a-graph | 0.576 | nightybear | Hard | 28,583 | 2,065 |
check whether two strings are almost equivalent | class Solution:
def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
freq = [0]*26
for x in word1: freq[ord(x)-97] += 1
for x in word2: freq[ord(x)-97] -= 1
return all(abs(x) <= 3 for x in freq) | https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1576339/Python3-freq-table | 2 | Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3.
Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.
The frequency of a l... | [Python3] freq table | 140 | check-whether-two-strings-are-almost-equivalent | 0.646 | ye15 | Easy | 28,589 | 2,068 |
most beautiful item for each query | class Solution:
def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:
items.sort()
dic = dict()
res = []
gmax = 0
for p,b in items:
gmax = max(b,gmax)
dic[p] = gmax
keys = sorted(dic.keys())
for q in queries:
ind = bisect.bisect_left(keys,q)
if ind<len(keys) and ... | https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1596922/Well-Explained-oror-99-faster-oror-Mainly-for-Beginners | 4 | You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item ... | ππ Well-Explained || 99% faster || Mainly for Beginners π | 124 | most-beautiful-item-for-each-query | 0.498 | abhi9Rai | Medium | 28,612 | 2,070 |
maximum number of tasks you can assign | class Solution:
def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:
# workers sorted in reverse order, tasks sorted in normal order
def can_assign(n):
task_i = 0
task_temp = deque()
n_pills = pills
for i in ... | https://leetcode.com/problems/maximum-number-of-tasks-you-can-assign/discuss/1588356/python-binary-search-%2B-greedy-with-deque-O(nlogn) | 9 | You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be a... | [python] binary search + greedy with deque O(nlogn) | 403 | maximum-number-of-tasks-you-can-assign | 0.346 | hkwu6013 | Hard | 28,622 | 2,071 |
time needed to buy tickets | class Solution:
def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:
secs = 0
i = 0
while tickets[k] != 0:
if tickets[i] != 0: # if it is zero that means we dont have to count it anymore
tickets[i] -= 1 # decrease the value by 1 everytime
... | https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1577018/Python-or-BruteForce-and-O(N) | 30 | There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.
You are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].
Each person takes exactl... | [Python] | BruteForce and O(N) | 1,600 | time-needed-to-buy-tickets | 0.62 | GigaMoksh | Easy | 28,625 | 2,073 |
reverse nodes in even length groups | class Solution:
def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:
n, node = 0, head
while node: n, node = n+1, node.next
k, node = 0, head
while n:
k += 1
size = min(k, n)
stack = []
if not si... | https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1577058/Python3-using-stack | 11 | You are given the head of a linked list.
The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,
The 1st node is assigned to the first group.
The 2nd ... | [Python3] using stack | 445 | reverse-nodes-in-even-length-groups | 0.521 | ye15 | Medium | 28,656 | 2,074 |
decode the slanted ciphertext | class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
cols, res = len(encodedText) // rows, ""
for i in range(cols):
for j in range(i, len(encodedText), cols + 1):
res += encodedText[j]
return res.rstrip() | https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1576914/Jump-Columns-%2B-1 | 57 | A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.
originalText is placed first in a top-left to bottom-right manner.
The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, unt... | Jump Columns + 1 | 2,000 | decode-the-slanted-ciphertext | 0.502 | votrubac | Medium | 28,663 | 2,075 |
process restricted friend requests | class Solution:
def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:
result = [False for _ in requests]
connected_components = [{i} for i in range(n)]
connected_comp_dict = {}
for i in range(n):
... | https://leetcode.com/problems/process-restricted-friend-requests/discuss/1577153/Python-272-ms36-MB-Maintain-connected-components-of-the-graph | 2 | You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.
You are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.
In... | [Python] [272 ms,36 MB] Maintain connected components of the graph | 189 | process-restricted-friend-requests | 0.532 | LonelyQuantum | Hard | 28,677 | 2,076 |
two furthest houses with different colors | class Solution:
def maxDistance(self, colors: List[int]) -> int:
ans = 0
for i, x in enumerate(colors):
if x != colors[0]: ans = max(ans, i)
if x != colors[-1]: ans = max(ans, len(colors)-1-i)
return ans | https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1589119/Python3-one-of-end-points-will-be-used | 25 | There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.
Return the maximum distance between two houses with different colors.
The distance between the ith and jth houses is... | [Python3] one of end points will be used | 887 | two-furthest-houses-with-different-colors | 0.671 | ye15 | Easy | 28,678 | 2,078 |
watering plants | class Solution:
def wateringPlants(self, plants: List[int], capacity: int) -> int:
ans = 0
can = capacity
for i, x in enumerate(plants):
if can < x:
ans += 2*i
can = capacity
ans += 1
can -= x
return ans | https://leetcode.com/problems/watering-plants/discuss/1589030/Python3-simulation | 19 | You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.
Each plant needs a specific amount of water. You will water the... | [Python3] simulation | 1,000 | watering-plants | 0.8 | ye15 | Medium | 28,701 | 2,079 |
sum of k mirror numbers | class Solution:
def kMirror(self, k: int, n: int) -> int:
def fn(x):
"""Return next k-symmetric number."""
n = len(x)//2
for i in range(n, len(x)):
if int(x[i])+1 < k:
x[i] = x[~i] = str(int(x[i])+1)
for i... | https://leetcode.com/problems/sum-of-k-mirror-numbers/discuss/1589048/Python3-enumerate-k-symmetric-numbers | 41 | A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k.
For example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.
On the contrary, 4 i... | [Python3] enumerate k-symmetric numbers | 2,700 | sum-of-k-mirror-numbers | 0.421 | ye15 | Hard | 28,741 | 2,081 |
count common words with one occurrence | class Solution:
def countWords(self, words1: List[str], words2: List[str]) -> int:
freq1, freq2 = Counter(words1), Counter(words2)
return len({w for w, v in freq1.items() if v == 1} & {w for w, v in freq2.items() if v == 1}) | https://leetcode.com/problems/count-common-words-with-one-occurrence/discuss/1598944/Python3-2-line-freq-table | 10 | Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.
Example 1:
Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
Explanation:
- "leetcode" appears exactly once in each of the two arrays. We coun... | [Python3] 2-line freq table | 1,200 | count-common-words-with-one-occurrence | 0.697 | ye15 | Easy | 28,746 | 2,085 |
minimum number of food buckets to feed the hamsters | class Solution:
def minimumBuckets(self, street: str) -> int:
street = list(street)
ans = 0
for i, ch in enumerate(street):
if ch == 'H' and (i == 0 or street[i-1] != '#'):
if i+1 < len(street) and street[i+1] == '.': street[i+1] = '#'
elif i an... | https://leetcode.com/problems/minimum-number-of-food-buckets-to-feed-the-hamsters/discuss/1598954/Python3-greedy | 10 | You are given a 0-indexed string hamsters where hamsters[i] is either:
'H' indicating that there is a hamster at index i, or
'.' indicating that index i is empty.
You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its... | [Python3] greedy | 541 | minimum-number-of-food-buckets-to-feed-the-hamsters | 0.451 | ye15 | Medium | 28,788 | 2,086 |
minimum cost homecoming of a robot in a grid | class Solution:
def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:
src_x,src_y = startPos[0],startPos[1]
end_x,end_y = homePos[0], homePos[1]
if src_x < end_x:
rc = sum(rowCosts[src_x+1:end_x+1])
elif src_x > end_x:
rc = sum(... | https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/discuss/1598918/Greedy-Approach-oror-Well-Coded-and-Explained-oror-95-faster | 3 | There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow... | ππ Greedy Approach || Well-Coded and Explained || 95% faster π | 276 | minimum-cost-homecoming-of-a-robot-in-a-grid | 0.513 | abhi9Rai | Medium | 28,797 | 2,087 |
count fertile pyramids in a land | class Solution:
def countPyramids(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
vals = [[inf]*n for _ in range(m)]
for i in range(m):
for j in range(n):
if grid[i][j] == 0: vals[i][j] = 0
elif j == 0: vals[i][j] = 1
... | https://leetcode.com/problems/count-fertile-pyramids-in-a-land/discuss/1598873/Python3-just-count | 5 | A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren.
A pyramidal plot of land can be defined as a set of cells with the following criteria:... | [Python3] just count | 415 | count-fertile-pyramids-in-a-land | 0.635 | ye15 | Hard | 28,802 | 2,088 |
find target indices after sorting array | class Solution:
def targetIndices(self, nums, target):
ans = []
for i,num in enumerate(sorted(nums)):
if num == target: ans.append(i)
return ans | https://leetcode.com/problems/find-target-indices-after-sorting-array/discuss/2024498/Python-Solution-%2B-One-Line! | 10 | You are given a 0-indexed integer array nums and a target element target.
A target index is an index i such that nums[i] == target.
Return a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing... | Python - Solution + One-Line! | 377 | find-target-indices-after-sorting-array | 0.766 | domthedeveloper | Easy | 28,813 | 2,089 |
k radius subarray averages | class Solution:
def getAverages(self, nums: List[int], k: int) -> List[int]:
res = [-1]*len(nums)
left, curWindowSum, diameter = 0, 0, 2*k+1
for right in range(len(nums)):
curWindowSum += nums[right]
if (right-left+1 >= diameter):
res[left+k] = curWindowSum//diameter
curWindow... | https://leetcode.com/problems/k-radius-subarray-averages/discuss/1599973/Python-3-or-Sliding-Window-or-Illustration-with-picture | 48 | You are given a 0-indexed array nums of n integers, and an integer k.
The k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-r... | Python 3 | Sliding Window | Illustration with picture | 1,300 | k-radius-subarray-averages | 0.426 | ndus | Medium | 28,861 | 2,090 |
removing minimum and maximum from array | class Solution:
def minimumDeletions(self, nums: List[int]) -> int:
imin = nums.index(min(nums))
imax = nums.index(max(nums))
return min(max(imin, imax)+1, len(nums)-min(imin, imax), len(nums)+1+min(imin, imax)-max(imin, imax)) | https://leetcode.com/problems/removing-minimum-and-maximum-from-array/discuss/1599862/Python3-3-candidates | 5 | You are given a 0-indexed array of distinct integers nums.
There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.
A deletion is defined as either removing an element fr... | [Python3] 3 candidates | 226 | removing-minimum-and-maximum-from-array | 0.566 | ye15 | Medium | 28,879 | 2,091 |
find all people with secret | class Solution:
def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:
can = {0, firstPerson}
for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]):
queue = set()
graph = defaultdict(list)
for x, y, _ ... | https://leetcode.com/problems/find-all-people-with-secret/discuss/1599870/Python3-BFS-or-DFS-by-group | 29 | You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given a... | [Python3] BFS or DFS by group | 3,100 | find-all-people-with-secret | 0.342 | ye15 | Hard | 28,900 | 2,092 |
finding 3 digit even numbers | class Solution:
def findEvenNumbers(self, digits: List[int]) -> List[int]:
ans = set()
for x, y, z in permutations(digits, 3):
if x != 0 and z & 1 == 0:
ans.add(100*x + 10*y + z)
return sorted(ans) | https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1611987/Python3-brute-force | 29 | You are given an integer array digits, where each element is a digit. The array may contain duplicates.
You need to find all the unique integers that follow the given requirements:
The integer consists of the concatenation of three elements from digits in any arbitrary order.
The integer does not have leading zeros.
Th... | [Python3] brute-force | 1,900 | finding-3-digit-even-numbers | 0.574 | ye15 | Easy | 28,911 | 2,094 |
delete the middle node of a linked list | class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow,fast,prev=head,head,None
while fast and fast.next:
prev=slow
slow=slow.next
fast=fast.next.next
if prev==None:
return None
prev.next=slow.next
... | https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2700533/Fastest-python-solution-TC%3A-O(N)SC%3A-O(1) | 12 | You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
The middle node of a linked list of size n is the βn / 2βth node from the start using 0-based indexing, where βxβ denotes the largest integer less than or equal to x.
For n = 1, 2, 3, 4, and 5, the middle n... | Fastest python solution TC: O(N),SC: O(1) | 1,200 | delete-the-middle-node-of-a-linked-list | 0.605 | shubham_1307 | Medium | 28,930 | 2,095 |
step by step directions from a binary tree node to another | class Solution:
def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
def lca(node):
"""Return lowest common ancestor of start and dest nodes."""
if not node or node.val in (startValue , destValue): return node
left, right =... | https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1612179/Python3-lca | 108 | You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t.
Find the shortest path starting from node s a... | [Python3] lca | 8,100 | step-by-step-directions-from-a-binary-tree-node-to-another | 0.488 | ye15 | Medium | 28,951 | 2,096 |
valid arrangement of pairs | class Solution:
def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:
graph = defaultdict(list)
degree = defaultdict(int) # net out degree
for x, y in pairs:
graph[x].append(y)
degree[x] += 1
degree[y] -= 1
for k... | https://leetcode.com/problems/valid-arrangement-of-pairs/discuss/1612010/Python3-Hierholzer's-algo | 32 | You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti.
Return any valid arrangement of pairs.
Note: The inputs will be generated such that there exists a valid arrangement of pairs.
... | [Python3] Hierholzer's algo | 1,400 | valid-arrangement-of-pairs | 0.41 | ye15 | Hard | 28,970 | 2,097 |
find subsequence of length k with the largest sum | class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
tuple_heap = [] # Stores (value, index) as min heap
for i, val in enumerate(nums):
if len(tuple_heap) == k:
heappushpop(tuple_heap, (val, i)) # To prevent size of heap growing larger than k
... | https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1705383/Python-Simple-Solution-or-100-Time | 10 | You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.
Return any such subsequence as an integer array of length k.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of t... | Python Simple Solution | 100% Time | 806 | find-subsequence-of-length-k-with-the-largest-sum | 0.425 | anCoderr | Easy | 28,973 | 2,099 |
find good days to rob the bank | class Solution:
def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:
suffix = [0]*len(security)
for i in range(len(security)-2, 0, -1):
if security[i] <= security[i+1]: suffix[i] = suffix[i+1] + 1
ans = []
prefix = 0
for i in range(l... | https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1623325/Python3-prefix-and-suffix | 5 | You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time.
The ith day is a good day to rob the bank if:
There are at least time d... | [Python3] prefix & suffix | 243 | find-good-days-to-rob-the-bank | 0.492 | ye15 | Medium | 29,003 | 2,100 |
detonate the maximum bombs | class Solution:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
if len(bombs)==1:
return 1
adlist={i:[] for i in range(len(bombs))}
for i in range(len(bombs)):
x1,y1,r1=bombs[i]
for j in range(i+1,len(bombs)):
... | https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1870271/Python-Solution-that-you-want-%3A | 2 | You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.
The bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and ... | Python Solution that you want : | 201 | detonate-the-maximum-bombs | 0.413 | goxy_coder | Medium | 29,011 | 2,101 |
rings and rods | class Solution:
def countPoints(self, r: str) -> int:
ans = 0
for i in range(10):
i = str(i)
if 'R'+i in r and 'G'+i in r and 'B'+i in r:
ans += 1
return ans | https://leetcode.com/problems/rings-and-rods/discuss/2044864/Python-simple-solution | 7 | There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.
You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring w... | Python simple solution | 353 | rings-and-rods | 0.814 | StikS32 | Easy | 29,018 | 2,103 |
sum of subarray ranges | class Solution:
def subArrayRanges(self, nums: List[int]) -> int:
def fn(op):
"""Return min sum (if given gt) or max sum (if given lt)."""
ans = 0
stack = []
for i in range(len(nums) + 1):
while stack and (i == len(nums) or op(nums[... | https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624416/Python3-stack | 17 | You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,2,3]
Output: 4
Explanat... | [Python3] stack | 3,900 | sum-of-subarray-ranges | 0.602 | ye15 | Medium | 29,052 | 2,104 |
watering plants ii | class Solution:
def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:
ans = 0
lo, hi = 0, len(plants)-1
canA, canB = capacityA, capacityB
while lo < hi:
if canA < plants[lo]: ans += 1; canA = capacityA
canA -= plants[lo]
... | https://leetcode.com/problems/watering-plants-ii/discuss/1624252/Python3-2-pointers | 8 | Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following w... | [Python3] 2 pointers | 340 | watering-plants-ii | 0.501 | ye15 | Medium | 29,071 | 2,105 |
maximum fruits harvested after at most k steps | class Solution:
def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:
fruitMap = defaultdict(int)
for position, amount in fruits:
fruitMap[position] = amount
if k == 0:
return fruitMap[startPos]
... | https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/discuss/1624294/Sliding-Window-or-Prefix-Suffix-Sum-or-Easy-to-understand | 1 | Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique.
You are also given an integer startPos an... | β
Sliding Window | Prefix Suffix Sum | Easy to understand | 268 | maximum-fruits-harvested-after-at-most-k-steps | 0.351 | CaptainX | Hard | 29,081 | 2,106 |
find first palindromic string in the array | class Solution:
def firstPalindrome(self, words):
for word in words:
if word == word[::-1]: return word
return "" | https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2022159/Python-Clean-and-Simple-%2B-One-Liner! | 3 | Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".
A string is palindromic if it reads the same forward and backward.
Example 1:
Input: words = ["abc","car","ada","racecar","cool"]
Output: "ada"
Explanation: The first string that i... | Python - Clean and Simple + One-Liner! | 128 | find-first-palindromic-string-in-the-array | 0.786 | domthedeveloper | Easy | 29,084 | 2,108 |
adding spaces to a string | class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
arr = []
prev = 0
for space in spaces:
arr.append(s[prev:space])
prev = space
arr.append(s[space:])
return " ".join(arr) | https://leetcode.com/problems/adding-spaces-to-a-string/discuss/1635075/Python-Split-and-Join-to-the-rescue.-From-TLE-to-Accepted-!-Straightforward | 8 | You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.
For example, given s = "EnjoyYourCoffee" and spaces = [5, 9], we place spaces before 'Y' and 'C', w... | [Python] Split and Join to the rescue. From TLE to Accepted ! Straightforward | 388 | adding-spaces-to-a-string | 0.563 | mostlyAditya | Medium | 29,132 | 2,109 |
number of smooth descent periods of a stock | class Solution:
def getDescentPeriods(self, prices: List[int]) -> int:
ans = 0
for i, x in enumerate(prices):
if i == 0 or prices[i-1] != x + 1: cnt = 0
cnt += 1
ans += cnt
return ans | https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/discuss/1635103/Python3-counting | 6 | You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day.
A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of... | [Python3] counting | 279 | number-of-smooth-descent-periods-of-a-stock | 0.576 | ye15 | Medium | 29,164 | 2,110 |
minimum operations to make the array k increasing | class Solution:
def kIncreasing(self, arr: List[int], k: int) -> int:
def fn(sub):
"""Return ops to make sub non-decreasing."""
vals = []
for x in sub:
k = bisect_right(vals, x)
if k == len(vals): vals.append(x)
e... | https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/discuss/1635109/Python3-almost-LIS | 2 | You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k.
The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1.
For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because:
arr[0] <= arr[2] (4 <= 5)
arr[1] <= arr[3] (1... | [Python3] almost LIS | 177 | minimum-operations-to-make-the-array-k-increasing | 0.378 | ye15 | Hard | 29,178 | 2,111 |
maximum number of words found in sentences | class Solution:
def mostWordsFound(self, ss: List[str]) -> int:
return max(s.count(" ") for s in ss) + 1 | https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/1646786/Count-Spaces | 64 | A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
You are given an array of strings sentences, where each sentences[i] represents a single sentence.
Return the maximum number of words that appear in a single sentence.
Example 1:
Input: sentences = ["alice and bob l... | Count Spaces | 8,100 | maximum-number-of-words-found-in-sentences | 0.88 | votrubac | Easy | 29,184 | 2,114 |
find all possible recipes from given supplies | class Solution:
def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
graph, can_make, supplies = {recipe : [] for recipe in recipes}, {}, set(supplies)
def dfs(recipe : str) -> bool:
if recipe not in can_make:
can_... | https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646903/DFS | 62 | You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingre... | DFS | 7,200 | find-all-possible-recipes-from-given-supplies | 0.485 | votrubac | Medium | 29,230 | 2,115 |
check if a parentheses string can be valid | class Solution:
def canBeValid(self, s: str, locked: str) -> bool:
def validate(s: str, locked: str, op: str) -> bool:
bal, wild = 0, 0
for i in range(len(s)):
if locked[i] == "1":
bal += 1 if s[i] == op else -1
else:
... | https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1646594/Left-to-right-and-right-to-left | 175 | A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:
It is ().
It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.
It can be written as (A), where A is a valid parentheses string.
You are given a pare... | Left-to-right and right-to-left | 8,600 | check-if-a-parentheses-string-can-be-valid | 0.315 | votrubac | Medium | 29,255 | 2,116 |
abbreviating the product of a range | class Solution:
def abbreviateProduct(self, left: int, right: int) -> str:
ans = prefix = suffix = 1
trailing = 0
flag = False
for x in range(left, right+1):
if not flag:
ans *= x
while ans % 10 == 0: ans //= 10
if ans ... | https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1646615/Python3-quasi-brute-force | 10 | You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right].
Since the product may be very large, you will abbreviate it following these steps:
Count all trailing zeros in the product and remove them. Let us denote this count as C.
Fo... | [Python3] quasi brute-force | 525 | abbreviating-the-product-of-a-range | 0.28 | ye15 | Hard | 29,260 | 2,117 |
a number after a double reversal | class Solution:
def isSameAfterReversals(self, num: int) -> bool:
return not num or num % 10 | https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1648940/Python3-1-Liner-or-O(1)-Time-and-Space-or-Short-and-Clean-Explanation | 12 | Reversing an integer means to reverse all its digits.
For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.
Given an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.
Examp... | [Python3] 1 Liner | O(1) Time and Space | Short and Clean Explanation | 578 | a-number-after-a-double-reversal | 0.758 | PatrickOweijane | Easy | 29,265 | 2,119 |
execution of all suffix instructions staying in a grid | class Solution:
def executeInstructions(self, n: int, startPos: list[int], s: str) -> list[int]:
def num_of_valid_instructions(s, pos, start, end):
row, colon = pos
k = 0
for i in range(start, end):
cur = s[i]
row += (cur == 'D') - (cur ==... | https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2838969/Python-Straight-forward-O(n-2)-solution-(still-fast-85) | 1 | There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).
You are also given a 0-indexed string s of length m wher... | [Python] Straight-forward O(n ^ 2) solution (still fast - 85%) | 4 | execution-of-all-suffix-instructions-staying-in-a-grid | 0.836 | Mark_computer | Medium | 29,307 | 2,120 |
intervals between identical elements | class Solution:
def getDistances(self, arr: List[int]) -> List[int]:
loc = defaultdict(list)
for i, x in enumerate(arr): loc[x].append(i)
for k, idx in loc.items():
prefix = list(accumulate(idx, initial=0))
vals = []
for i, x in enumerate(idx):
... | https://leetcode.com/problems/intervals-between-identical-elements/discuss/1647480/Python3-prefix-sum | 9 | You are given a 0-indexed array of n integers arr.
The interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|.
Return an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and e... | [Python3] prefix sum | 1,100 | intervals-between-identical-elements | 0.433 | ye15 | Medium | 29,326 | 2,121 |
recover the original array | class Solution:
def recoverArray(self, nums: List[int]) -> List[int]:
nums.sort()
cnt = Counter(nums)
for i in range(1, len(nums)):
diff = nums[i] - nums[0]
if diff and diff&1 == 0:
ans = []
freq = cnt.copy()
for k... | https://leetcode.com/problems/recover-the-original-array/discuss/1647488/Python3-brute-force | 11 | Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner:
lower[i] = arr[i] - k, for every index i where 0 <= i < n
higher[i] = arr[i] + k, for every index i where 0 <= i < n
Unfortu... | [Python3] brute-force | 503 | recover-the-original-array | 0.381 | ye15 | Hard | 29,336 | 2,122 |
check if all as appears before all bs | class Solution:
def checkString(self, s: str) -> bool:
return ''.join(sorted(s)) == s | https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1662586/Python-O(NlogN)-sort-solution-and-O(N)-linear-scan-solution | 4 | Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.
Example 1:
Input: s = "aaabbb"
Output: true
Explanation:
The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.
Hence, every 'a' appears be... | [Python] O(NlogN) sort solution and O(N) linear scan solution | 193 | check-if-all-as-appears-before-all-bs | 0.716 | kryuki | Easy | 29,341 | 2,124 |
number of laser beams in a bank | class Solution:
def numberOfBeams(self, bank: List[str]) -> int:
a, s = [x.count("1") for x in bank if x.count("1")], 0
# ex: bank is [[00101], [01001], [00000], [11011]]
# a would return [2, 2, 4]
for c in range(len(a)-1):
s += (a[c]*a[c+1])
# basic math to find the total amou... | https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2272999/PYTHON-3-99.13-LESS-MEMORY-or-94.93-FASTER-or-EXPLANATION | 7 | Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.
There... | [PYTHON 3] 99.13% LESS MEMORY | 94.93% FASTER | EXPLANATION | 130 | number-of-laser-beams-in-a-bank | 0.826 | omkarxpatel | Medium | 29,379 | 2,125 |
destroying asteroids | class Solution:
def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:
asteroids = sorted(asteroids)
for i in asteroids:
if i <= mass:
mass += i
else:
return False
return True | https://leetcode.com/problems/destroying-asteroids/discuss/1775912/Simple-python-solution-or-85-lesser-memory | 2 | You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.
You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to ... | βSimple python solution | 85% lesser memory | 129 | destroying-asteroids | 0.495 | Coding_Tan3 | Medium | 29,412 | 2,126 |
maximum employees to be invited to a meeting | class Solution:
def maximumInvitations(self, favorite: List[int]) -> int:
n = len(favorite)
graph = [[] for _ in range(n)]
for i, x in enumerate(favorite): graph[x].append(i)
def bfs(x, seen):
"""Return longest arm of x."""
ans = 0
queue... | https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/discuss/1661041/Python3-quite-a-tedious-solution | 5 | A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.
The employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to... | [Python3] quite a tedious solution | 1,000 | maximum-employees-to-be-invited-to-a-meeting | 0.337 | ye15 | Hard | 29,427 | 2,127 |
capitalize the title | class Solution:
def capitalizeTitle(self, title: str) -> str:
title = title.split()
word = ""
for i in range(len(title)):
if len(title[i]) < 3:
word = word + title[i].lower() + " "
else:
word = word + title[i].capitalize() + " "
... | https://leetcode.com/problems/capitalize-the-title/discuss/1716077/Python-Easy-Solution | 4 | You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:
If the length of the word is 1 or 2 letters, change all letters to lowercase.
Otherwise, change the first le... | Python Easy Solution | 413 | capitalize-the-title | 0.603 | yashitanamdeo | Easy | 29,428 | 2,129 |
maximum twin sum of a linked list | class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
nums = []
curr = head
while curr:
nums.append(curr.val)
curr = curr.next
N = len(nums)
res = 0
for i in range(N // 2):
res = max(res, nums[i] + nums[N - i ... | https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676025/Need-to-know-O(1)-space-solution-in-Python | 16 | In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
The twin sum is define... | Need-to-know O(1) space solution in Python | 1,900 | maximum-twin-sum-of-a-linked-list | 0.814 | kryuki | Medium | 29,470 | 2,130 |
longest palindrome by concatenating two letter words | class Solution:
def longestPalindrome(self, words: List[str]) -> int:
dc=defaultdict(lambda:0)
for a in words:
dc[a]+=1
count=0
palindromswords=0
inmiddle=0
wds=set(words)
for a in wds:
if(a==a[::-1]):
if(dc[a]%2==1):
... | https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772128/using-dictnory-in-TCN | 5 | You are given an array of strings words. Each element of words consists of two lowercase English letters.
Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.
Return the length of the longest palindrome that you can ... | using dictnory in TC=N | 349 | longest-palindrome-by-concatenating-two-letter-words | 0.491 | droj | Medium | 29,493 | 2,131 |
stamping the grid | class Solution:
def prefix_sum(self, grid: List[List[int]]) -> List[List[int]]:
ps = [[grid[row][col] for col in range(len(grid[0]))]for row in range(len(grid))]
for row in range(len(grid)):
for col in range(1, len(grid[0])):
ps[row][col] = ps... | https://leetcode.com/problems/stamping-the-grid/discuss/2489712/Python3-solution%3A-faster-than-most-submissions-oror-Very-simple | 0 | You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).
You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements:
Cover all the empty cells.
Do not cover any of the occupied cells.
We can pu... | βοΈ Python3 solution: faster than most submissions || Very simple | 40 | stamping-the-grid | 0.309 | Omegang | Hard | 29,544 | 2,132 |
check if every row and column contains all numbers | class Solution:
def checkValid(self, matrix: List[List[int]]) -> bool:
lst = [0]*len(matrix)
for i in matrix:
if len(set(i)) != len(matrix):
return False
for j in range(len(i)):
lst[j] += i[j]
return len(set(lst)) == 1 | https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1775747/Python-3-or-7-Line-solution-or-87-Faster-runtime-or-92.99-lesser-memory | 6 | An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).
Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.
Example 1:
Input: matrix = [[1,2,3],[3,1,2],[2,3,1]]
Output: true
Explanation: In this case, n = 3, and every row... | βPython 3 | 7 Line solution | 87% Faster runtime | 92.99% lesser memory | 855 | check-if-every-row-and-column-contains-all-numbers | 0.53 | Coding_Tan3 | Easy | 29,546 | 2,133 |
minimum swaps to group all 1s together ii | class Solution:
def minSwaps(self, nums: List[int]) -> int:
width = sum(num == 1 for num in nums) #width of the window
nums += nums
res = width
curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width]
for i in range(width, len(nums)):
... | https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1677262/Sliding-window-with-comments-Python | 21 | A swap is defined as taking two distinct positions in an array and swapping the values in them.
A circular array is defined as an array where we consider the first element and the last element to be adjacent.
Given a binary circular array nums, return the minimum number of swaps required to group all 1's present in the... | Sliding window with comments, Python | 645 | minimum-swaps-to-group-all-1s-together-ii | 0.507 | kryuki | Medium | 29,587 | 2,134 |
count words obtained after adding a letter | class Solution:
def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:
seen = set()
for word in startWords:
m = 0
for ch in word: m ^= 1 << ord(ch)-97
seen.add(m)
ans = 0
for word in targetWords:
m = ... | https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/discuss/1676852/Python3-bitmask | 84 | You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.
For each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.
The conversion opera... | [Python3] bitmask | 5,900 | count-words-obtained-after-adding-a-letter | 0.428 | ye15 | Medium | 29,602 | 2,135 |
earliest possible day of full bloom | class Solution:
def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:
res = 0
for grow, plant in sorted(zip(growTime, plantTime)):
res = max(res, grow) + plant
return res | https://leetcode.com/problems/earliest-possible-day-of-full-bloom/discuss/1676837/Grow-then-plant | 203 | You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each:
plantTime[i] is the number of full days it takes you to plant the ith seed.... | Grow then plant | 6,900 | earliest-possible-day-of-full-bloom | 0.749 | votrubac | Hard | 29,614 | 2,136 |
divide a string into groups of size k | class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
length = len(s)
res=[]
for i in range(0,length,k):
if i+k>length:
break
res.append(s[i:i+k])
mod =length%k
if mod!= 0:
fill_str = fill... | https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/discuss/1694807/Python-O(n)-solution | 2 | A string s can be partitioned into groups of size k using the following procedure:
The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.
For the last group, if the string does not ... | Python O(n) solution | 100 | divide-a-string-into-groups-of-size-k | 0.652 | SamyakKrSahoo | Easy | 29,649 | 2,138 |
minimum moves to reach target score | class Solution:
def minMoves(self, target: int, maxDoubles: int) -> int:
moves = 0
while maxDoubles > 0 and target > 1:
if target % 2 == 1:
target -= 1
else:
target //= 2
maxDoubles -= 1
moves += 1
moves += target - 1
... | https://leetcode.com/problems/minimum-moves-to-reach-target-score/discuss/1722491/Easy-Solution-python-explained-30ms | 2 | You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.
In one move, you can either:
Increment the current integer by one (i.e., x = x + 1).
Double the current integer (i.e., x = 2 * x).
You can use the increment operation any number of times, however, you can only u... | Easy Solution python explained 30ms | 83 | minimum-moves-to-reach-target-score | 0.484 | Volver805 | Medium | 29,687 | 2,139 |
solving questions with brainpower | class Solution:
def mostPoints(self, q: List[List[int]]) -> int:
@cache
def dfs(i: int) -> int:
return 0 if i >= len(q) else max(dfs(i + 1), q[i][0] + dfs(i + 1 + q[i][1]))
return dfs(0) | https://leetcode.com/problems/solving-questions-with-brainpower/discuss/1692963/DP | 132 | You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri].
The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you p... | DP | 5,500 | solving-questions-with-brainpower | 0.46 | votrubac | Medium | 29,711 | 2,140 |
maximum running time of n computers | class Solution:
def maxRunTime(self, n: int, batteries: List[int]) -> int:
batteries.sort()
extra = sum(batteries[:-n])
batteries = batteries[-n:]
ans = prefix = 0
for i, x in enumerate(batteries):
prefix += x
if i+1 < len(batteries) and ba... | https://leetcode.com/problems/maximum-running-time-of-n-computers/discuss/1692965/Python3-greedy | 39 | You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries.
Initially, you can insert at most one battery into each computer. After tha... | [Python3] greedy | 1,400 | maximum-running-time-of-n-computers | 0.389 | ye15 | Hard | 29,741 | 2,141 |
minimum cost of buying candies with discount | class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort(reverse=True)
res, i, N = 0, 0, len(cost)
while i < N:
res += sum(cost[i : i + 2])
i += 3
return res | https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/discuss/1712364/Python-Simple-solution-or-100-faster-or-O(N-logN)-Time-or-O(1)-Space | 9 | A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.
The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.
For example, if there are 4 candies with costs ... | [Python] Simple solution | 100% faster | O(N logN) Time | O(1) Space | 454 | minimum-cost-of-buying-candies-with-discount | 0.609 | eshikashah | Easy | 29,744 | 2,144 |
count the hidden sequences | class Solution:
def numberOfArrays(self, diff: List[int], lower: int, upper: int) -> int:
diff = list(accumulate(diff, initial = 0))
return max(0, upper - lower - (max(diff) - min(diff)) + 1) | https://leetcode.com/problems/count-the-hidden-sequences/discuss/1714246/Right-Left | 5 | You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].
You are further given two integers lo... | Right - Left | 266 | count-the-hidden-sequences | 0.365 | votrubac | Medium | 29,769 | 2,145 |
k highest ranked items within a price range | class Solution:
def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
ans = []
queue = deque([(0, *start)])
grid[start[0]][start[1]] *= -1
while queue:
x, i, j = queu... | https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/discuss/1709702/Python3-bfs | 1 | You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following:
0 represents a wall that you cannot pass through.
1 represents an empty cell that you can freely move to and from.
All other positive integers represent the price... | [Python3] bfs | 32 | k-highest-ranked-items-within-a-price-range | 0.412 | ye15 | Medium | 29,779 | 2,146 |
number of ways to divide a long corridor | class Solution:
def numberOfWays(self, corridor: str) -> int:
#edge case
num_S = corridor.count('S')
if num_S == 0 or num_S % 2 == 1:
return 0
mod = 10 ** 9 + 7
curr_s = 0
divide_spots = []
for char in corridor:
curr_s += (char... | https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/discuss/1709706/simple-Python-solution-(time%3A-O(N)-space%3A-O(1)) | 2 | Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant.
One room divider has already been installed to the left of index 0, and another to the ... | simple Python solution (time: O(N), space: O(1)) | 92 | number-of-ways-to-divide-a-long-corridor | 0.399 | kryuki | Hard | 29,783 | 2,147 |
count elements with strictly smaller and greater elements | class Solution:
def countElements(self, nums: List[int]) -> int:
res = 0
mn = min(nums)
mx = max(nums)
for i in nums:
if i > mn and i < mx:
res += 1
return res | https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/discuss/2507825/Very-very-easy-code-in-just-3-lines-using-Python | 7 | Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Example 1:
Input: nums = [11,7,2,15]
Output: 2
Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 11 has e... | Very very easy code in just 3 lines using Python | 44 | count-elements-with-strictly-smaller-and-greater-elements | 0.6 | ankurbhambri | Easy | 29,793 | 2,148 |
rearrange array elements by sign | class Solution:
def rearrangeArray(self, nums: List[int]) -> List[int]:
return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t] | https://leetcode.com/problems/rearrange-array-elements-by-sign/discuss/1711329/Two-Pointers | 20 | You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.
You should return the array of nums such that the the array follows the given conditions:
Every consecutive pair of integers have opposite signs.
For all integers with the same sign, the order in... | Two Pointers | 5,200 | rearrange-array-elements-by-sign | 0.811 | votrubac | Medium | 29,821 | 2,149 |
find all lonely numbers in the array | class Solution:
def findLonely(self, nums: List[int]) -> List[int]:
m = Counter(nums)
return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0] | https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/discuss/1711316/Counter | 43 | You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
Return all lonely numbers in nums. You may return the answer in any order.
Example 1:
Input: nums = [10,6,5,8]
Output: [10,8]
Explanation:
- 10 is a lonely number s... | Counter | 3,400 | find-all-lonely-numbers-in-the-array | 0.608 | votrubac | Medium | 29,862 | 2,150 |
maximum good people based on statements | class Solution:
def maximumGood(self, statements: List[List[int]]) -> int:
ans, n = 0, len(statements)
for person in itertools.product([0, 1], repeat=n): # use itertools to create a list only contains 0 or 1
valid = True # initially, we think the `person... | https://leetcode.com/problems/maximum-good-people-based-on-statements/discuss/1711677/Python-3-or-Itertools-and-Bitmask-or-Explanation | 2 | There are two types of persons:
The good person: The person who always tells the truth.
The bad person: The person who might tell the truth and might lie.
You are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i... | Python 3 | Itertools & Bitmask | Explanation | 126 | maximum-good-people-based-on-statements | 0.486 | idontknoooo | Hard | 29,880 | 2,151 |
keep multiplying found values by two | class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
while original in nums:
original *= 2
return original | https://leetcode.com/problems/keep-multiplying-found-values-by-two/discuss/2531609/Python-solution-simple-faster-than-80-less-memory-than-99 | 2 | You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.
You then do the following steps:
If original is found in nums, multiply it by two (i.e., set original = 2 * original).
Otherwise, stop the process.
Repeat this process with th... | Python solution simple faster than 80% less memory than 99% | 62 | keep-multiplying-found-values-by-two | 0.731 | Theo704 | Easy | 29,886 | 2,154 |
all divisions with the highest score of a binary array | class Solution:
def maxScoreIndices(self, nums: List[int]) -> List[int]:
ans = [0]
cand = most = nums.count(1)
for i, x in enumerate(nums):
if x == 0: cand += 1
elif x == 1: cand -= 1
if cand > most: ans, most = [i+1], cand
elif cand == most: ... | https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/discuss/1732887/Python3-scan | 2 | You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:
numsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclus... | [Python3] scan | 39 | all-divisions-with-the-highest-score-of-a-binary-array | 0.634 | ye15 | Medium | 29,934 | 2,155 |
find substring with given hash value | class Solution:
def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:
pp = pow(power, k-1, modulo)
hs = ii = 0
for i, ch in enumerate(reversed(s)):
if i >= k: hs -= (ord(s[~(i-k)]) - 96)*pp
hs = (hs * power + (ord(ch) - 96)) % modulo
... | https://leetcode.com/problems/find-substring-with-given-hash-value/discuss/1732936/Python3-rolling-hash | 2 | The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:
hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.
Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.
You are given a string s an... | [Python3] rolling hash | 79 | find-substring-with-given-hash-value | 0.221 | ye15 | Hard | 29,954 | 2,156 |
minimum sum of four digit number after splitting digits | class Solution:
def minimumSum(self, num: int) -> int:
num = sorted(str(num),reverse=True)
n = len(num)
res = 0
even_iteration = False
position = 0
for i in range(n):
res += int(num[i])*(10**position)
if even_iteration:
posi... | https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/discuss/1747018/Python-simple-and-fast-with-explanation-no-permutation | 43 | You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.
For example, given num = 2932, you have the following digits: two 2's, one 9 a... | Python - simple & fast with explanation - no permutation | 4,300 | minimum-sum-of-four-digit-number-after-splitting-digits | 0.879 | fatamorgana | Easy | 29,961 | 2,160 |
partition array according to given pivot | class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
ans=[]
nums.remove(pivot)
i=0
ans.append(pivot)
for j in nums:
if j<pivot:
ans.insert(i,j)
i=i+1
elif j==pivot:
ans.insert(i+1,j)
else:
ans.append(j)
return ans | https://leetcode.com/problems/partition-array-according-to-given-pivot/discuss/1748566/Python-Simple-and-Clean-Python-Solution-by-Removing-and-Appending | 5 | You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:
Every element less than pivot appears before every element greater than pivot.
Every element equal to pivot appears in between the elements less than and greater than pivot.
The relative o... | [ Python ] ββ Simple and Clean Python Solution by Removing and Appending | 475 | partition-array-according-to-given-pivot | 0.845 | ASHOK_KUMAR_MEGHVANSHI | Medium | 30,013 | 2,161 |
minimum cost to set cooking time | class Solution:
def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:
def count_cost(minutes, seconds): # Calculates cost for certain configuration of minutes and seconds
time = f'{minutes // 10}{minutes % 10}{seconds // 10}{seconds % 10}' # mm:ss
... | https://leetcode.com/problems/minimum-cost-to-set-cooking-time/discuss/1746996/Simple-Python-Solution | 10 | A generic microwave supports cooking times for:
at least 1 second.
at most 99 minutes and 99 seconds.
To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the second... | Simple Python Solution | 513 | minimum-cost-to-set-cooking-time | 0.396 | anCoderr | Medium | 30,053 | 2,162 |
minimum difference in sums after removal of elements | class Solution:
def minimumDifference(self, nums: List[int]) -> int:
n = len(nums) // 3
# calculate max_sum using min_heap for second part
min_heap = nums[(2 * n) :]
heapq.heapify(min_heap)
max_sum = [0] * (n + 2)
max_sum[n + 1] = sum(min_heap)
for i in rang... | https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/discuss/2392142/Python-solution-or-O(nlogn)-or-explained-with-diagram-or-heap-and-dp-solution | 1 | You are given a 0-indexed integer array nums consisting of 3 * n elements.
You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:
The first n elements belonging to the first part and their sum is sumfirst.
The next n elements... | Python solution | O(nlogn) | explained with diagram | heap and dp solution | 64 | minimum-difference-in-sums-after-removal-of-elements | 0.467 | wilspi | Hard | 30,059 | 2,163 |
sort even and odd indices independently | class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
n = len(nums)
for i in range(0,n,2):
for j in range(i+2,n,2):
if nums[i] > nums[j]:
nums[i],nums[j] = nums[j], nums[i]
for i in range(1,n,2):
for j in range(i+2,n,2):
if nums[i] < nums[j]:
nums[i],nums[j] = nums[j], num... | https://leetcode.com/problems/sort-even-and-odd-indices-independently/discuss/2214566/Python-oror-In-Place-Sorting | 1 | You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:
Sort the values at odd indices of nums in non-increasing order.
For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order... | Python || In Place Sorting | 186 | sort-even-and-odd-indices-independently | 0.664 | morpheusdurden | Easy | 30,062 | 2,164 |
smallest value of the rearranged number | class Solution:
def smallestNumber(self, num: int) -> int:
if num == 0 : return 0
snum = sorted(str(num))
if snum[0] == '-' :
return -int("".join(snum[:0:-1]))
elif snum[0] == '0' :
x = snum.count('0')
return "".join([snum[x]]+['0'*x]+snu... | https://leetcode.com/problems/smallest-value-of-the-rearranged-number/discuss/1755847/PYTHON3-or-EASY-SOLUTION-or | 1 | You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.
Return the rearranged number with minimal value.
Note that the sign of the number does not change after rearranging the digits.
Example 1:
Input: num = 310
Output: 103
Explanation: The... | PYTHON3 | EASY SOLUTION | | 108 | smallest-value-of-the-rearranged-number | 0.513 | rohitkhairnar | Medium | 30,084 | 2,165 |
minimum time to remove all cars containing illegal goods | class Solution:
def minimumTime(self, s: str) -> int:
ans = inf
prefix = 0
for i, ch in enumerate(s):
if ch == '1': prefix = min(2 + prefix, i+1)
ans = min(ans, prefix + len(s)-1-i)
return ans | https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/discuss/2465604/Python3-dp | 0 | You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods.
As the train conductor, you would like to get rid of all the cars containing illegal goods. You can ... | [Python3] dp | 24 | minimum-time-to-remove-all-cars-containing-illegal-goods | 0.402 | ye15 | Hard | 30,094 | 2,167 |
count operations to obtain zero | class Solution:
def countOperations(self, num1: int, num2: int) -> int:
ans = 0
while num1 and num2:
ans += num1//num2
num1, num2 = num2, num1%num2
return ans | https://leetcode.com/problems/count-operations-to-obtain-zero/discuss/1766882/Python3-simulation | 4 | You are given two non-negative integers num1 and num2.
In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.
For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num... | [Python3] simulation | 385 | count-operations-to-obtain-zero | 0.755 | ye15 | Easy | 30,096 | 2,169 |
minimum operations to make the array alternating | class Solution:
def minimumOperations(self, nums: List[int]) -> int:
pad = lambda x: x + [(None, 0)]*(2-len(x))
even = pad(Counter(nums[::2]).most_common(2))
odd = pad(Counter(nums[1::2]).most_common(2))
return len(nums) - (max(even[0][1] + odd[1][1], even[1][1] + odd[0][1]) if even[... | https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/discuss/1766909/Python3-4-line | 19 | You are given a 0-indexed array nums consisting of n positive integers.
The array nums is called alternating if:
nums[i - 2] == nums[i], where 2 <= i <= n - 1.
nums[i - 1] != nums[i], where 1 <= i <= n - 1.
In one operation, you can choose an index i and change nums[i] into any positive integer.
Return the minimum numb... | [Python3] 4-line | 1,600 | minimum-operations-to-make-the-array-alternating | 0.332 | ye15 | Medium | 30,123 | 2,170 |
removing minimum number of magic beans | class Solution:
def minimumRemoval(self, beans: List[int]) -> int:
beans.sort()
return sum(beans) - max((len(beans)-i)*x for i, x in enumerate(beans)) | https://leetcode.com/problems/removing-minimum-number-of-magic-beans/discuss/1766873/Python3-2-line | 4 | You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.
Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean ha... | [Python3] 2-line | 163 | removing-minimum-number-of-magic-beans | 0.42 | ye15 | Medium | 30,138 | 2,171 |
maximum and sum of array | class Solution:
def maximumANDSum(self, nums: List[int], numSlots: int) -> int:
@cache
def fn(k, m):
"""Return max AND sum."""
if k == len(nums): return 0
ans = 0
for i in range(numSlots):
if m & 1<<2*i == 0 or m & ... | https://leetcode.com/problems/maximum-and-sum-of-array/discuss/1766984/Python3-dp-(top-down) | 13 | You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots.
You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of e... | [Python3] dp (top-down) | 591 | maximum-and-sum-of-array | 0.475 | ye15 | Hard | 30,149 | 2,172 |
count equal and divisible pairs in an array | class Solution:
def countPairs(self, nums: List[int], k: int) -> int:
n=len(nums)
c=0
for i in range(0,n):
for j in range(i+1,n):
if nums[i]==nums[j] and ((i*j)%k==0):
c+=1
return c | https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/discuss/1783447/Python3-Solution-fastest | 6 | Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.
Example 1:
Input: nums = [3,1,2,2,2,1,3], k = 2
Output: 4
Explanation:
There are 4 pairs that meet all the requirements:
- nums[0] == n... | Python3 Solution fastest | 812 | count-equal-and-divisible-pairs-in-an-array | 0.803 | Anilchouhan181 | Easy | 30,151 | 2,176 |
find three consecutive integers that sum to a given number | class Solution:
def sumOfThree(self, num: int) -> List[int]:
return [] if num % 3 else [num//3-1, num//3, num//3+1] | https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/discuss/1783425/Python3-1-line | 5 | Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.
Example 1:
Input: num = 33
Output: [10,11,12]
Explanation: 33 can be expressed as 10 + 11 + 12 = 33.
10, 11, 12 are 3 consecutive int... | [Python3] 1-line | 258 | find-three-consecutive-integers-that-sum-to-a-given-number | 0.637 | ye15 | Medium | 30,184 | 2,177 |
maximum split of positive even integers | class Solution:
def maximumEvenSplit(self, finalSum: int) -> List[int]:
l=set()
if finalSum%2!=0:
return l
else:
s=0
i=2 # even pointer 2, 4, 6, 8, 10, 12...........
while(s<finalSum):
s+=i #... | https://leetcode.com/problems/maximum-split-of-positive-even-integers/discuss/1783966/Simple-Python-Solution-with-Explanation-oror-O(sqrt(n))-Time-Complexity-oror-O(1)-Space-Complexity | 51 | You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.
For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum num... | Simple Python Solution with Explanation || O(sqrt(n)) Time Complexity || O(1) Space Complexity | 2,000 | maximum-split-of-positive-even-integers | 0.591 | HimanshuGupta_p1 | Medium | 30,208 | 2,178 |
count good triplets in an array | class Solution:
def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
hashmap2 = {}
for i in range(n):
hashmap2[nums2[i]] = i
indices = []
for num in nums1:
indices.append(hashmap2[num])
from sortedcontainers import ... | https://leetcode.com/problems/count-good-triplets-in-an-array/discuss/1783361/Python-3-SortedList-solution-O(NlogN) | 13 | You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].
A good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2... | Python 3 SortedList solution, O(NlogN) | 554 | count-good-triplets-in-an-array | 0.371 | xil899 | Hard | 30,226 | 2,179 |
count integers with even digit sum | class Solution:
def countEven(self, num: int) -> int:
return num // 2 if sum([int(k) for k in str(num)]) % 2 == 0 else (num - 1) // 2 | https://leetcode.com/problems/count-integers-with-even-digit-sum/discuss/1785049/lessPython3greater-O(1)-Discrete-Formula-100-faster-1-LINE | 9 | Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.
The digit sum of a positive integer is the sum of all its digits.
Example 1:
Input: num = 4
Output: 2
Explanation:
The only integers less than or equal to 4 whose digit sums are even are 2 and 4. ... | <Python3> O(1) - Discrete Formula - 100% faster - 1 LINE | 845 | count-integers-with-even-digit-sum | 0.645 | drknzz | Easy | 30,229 | 2,180 |
merge nodes in between zeros | class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
d=ListNode(0)
t=0
r=ListNode(0,d)
while head:
if head.val!=0:
t+=head.val
else:
print(t)
if t!=0:
d.next=L... | https://leetcode.com/problems/merge-nodes-in-between-zeros/discuss/1784873/Python-3-or-Dummy-Node-O(N)-Time-Solution | 6 | You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.
For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list s... | Python 3 | Dummy Node O(N) Time Solution | 576 | merge-nodes-in-between-zeros | 0.867 | MrShobhit | Medium | 30,271 | 2,181 |
construct string with repeat limit | class Solution:
def repeatLimitedString(self, s: str, repeatLimit: int) -> str:
pq = [(-ord(k), v) for k, v in Counter(s).items()]
heapify(pq)
ans = []
while pq:
k, v = heappop(pq)
if ans and ans[-1] == k:
if not pq: break
k... | https://leetcode.com/problems/construct-string-with-repeat-limit/discuss/1784789/Python3-priority-queue | 23 | You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.
Return the lexicographically largest repeatLimitedString possible.
A string a is lexic... | [Python3] priority queue | 1,100 | construct-string-with-repeat-limit | 0.519 | ye15 | Medium | 30,294 | 2,182 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.