problem_title
stringlengths
3
77
python_solutions
stringlengths
81
8.45k
post_href
stringlengths
64
213
upvotes
int64
0
1.2k
question
stringlengths
0
3.6k
post_title
stringlengths
2
100
views
int64
1
60.9k
slug
stringlengths
3
77
acceptance
float64
0.14
0.91
user
stringlengths
3
26
difficulty
stringclasses
3 values
__index_level_0__
int64
0
34k
number
int64
1
2.48k
number of distinct roll sequences
class Solution: def distinctSequences(self, n: int) -> int: @lru_cache def fn(n, p0, p1): """Return total number of distinct sequences.""" if n == 0: return 1 ans = 0 for x in range(1, 7): if x not in (p0, p1) and gcd(x, p0) ...
https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2196009/Python3-top-down-dp
2
You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied: The greatest common divisor of any adjacent values in the sequence is equal to 1. There is at least a gap of 2 rolls between equal valued...
[Python3] top-down dp
48
number-of-distinct-roll-sequences
0.562
ye15
Hard
31,929
2,318
check if matrix is x matrix
class Solution: def checkXMatrix(self, grid: List[List[int]]) -> bool: a=0 j=len(grid)-1 for i in range(0,len(grid)): if grid[i][i]==0 or grid[i][j]==0: return False else: if i!=j: a=grid[i][i]+grid[i][j] ...
https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2368873/Easiest-Python-solution-you-will-find.......-Single-loop
1
A square matrix is said to be an X-Matrix if both of the following conditions hold: All the elements in the diagonals of the matrix are non-zero. All other elements are 0. Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false. Example 1: ...
Easiest Python solution you will find....... Single loop
46
check-if-matrix-is-x-matrix
0.673
guneet100
Easy
31,934
2,319
count number of ways to place houses
class Solution: def countHousePlacements(self, n: int) -> int: pre,ppre = 2,1 if n==1: return 4 for i in range(1,n): temp = pre+ppre ppre = pre pre = temp return ((pre)**2)%((10**9) + 7)
https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198265/Python-Simple-Solution-or-O(n)-time-complexity-or-Basic-Approach-or-DP
2
There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed. Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer...
Python Simple Solution | O(n) time complexity | Basic Approach | DP
95
count-number-of-ways-to-place-houses
0.401
AkashHooda
Medium
31,953
2,320
maximum score of spliced array
class Solution: def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int: # create a difference array between nums1 and nums2 # idea: find two subarray(elements are contiguous) in the diff # one is the subarray that have the minimum negative sum # another one is the ...
https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198195/Python-or-Easy-to-Understand-or-With-Explanation-or-No-Kadane
2
You are given two 0-indexed integer arrays nums1 and nums2, both of length n. You can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right]. For example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 ...
Python | Easy to Understand | With Explanation | No Kadane
150
maximum-score-of-spliced-array
0.554
Mikey98
Hard
31,968
2,321
minimum score after removals on a tree
class Solution: def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: n = len(nums) graph = [[] for _ in range(n)] for u, v in edges: graph[u].append(v) graph[v].append(u) def fn(u): score[u] = nums[u] ...
https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198386/Python3-dfs
6
There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge b...
[Python3] dfs
241
minimum-score-after-removals-on-a-tree
0.506
ye15
Hard
31,980
2,322
decode the message
class Solution: def decodeMessage(self, key: str, message: str) -> str: mapping = {' ': ' '} i = 0 res = '' letters = 'abcdefghijklmnopqrstuvwxyz' for char in key: if char not in mapping: mapping[char] = letters[i] i += 1 ...
https://leetcode.com/problems/decode-the-message/discuss/2229844/Easy-Python-solution-using-Hashing
23
You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. Align the substitution table with the regular English alphab...
Easy Python solution using Hashing
1,400
decode-the-message
0.848
MiKueen
Easy
31,986
2,325
spiral matrix iv
class Solution: def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: matrix = [[-1]*n for i in range(m)] current = head direction = 1 i, j = 0, -1 while current: for _ in range(n): if curre...
https://leetcode.com/problems/spiral-matrix-iv/discuss/2230251/Python-easy-solution-using-direction-variable
1
You are given two integers m and n, which represent the dimensions of a matrix. You are also given the head of a linked list of integers. Generate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty s...
Python easy solution using direction variable
36
spiral-matrix-iv
0.745
HunkWhoCodes
Medium
32,017
2,326
number of people aware of a secret
class Solution: def peopleAwareOfSecret(self, n: int, d: int, f: int) -> int: dp, md = [1] + [0] * (f - 1), 10**9 + 7 for i in range(1, n): dp[i % f] = (md + dp[(i + f - d) % f] - dp[i % f] + (0 if i == 1 else dp[(i - 1) % f])) % md return sum(dp) % md
https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229808/Two-Queues-or-Rolling-Array
53
On day 1, one person discovers a secret. You are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after disc...
Two Queues or Rolling Array
3,300
number-of-people-aware-of-a-secret
0.445
votrubac
Medium
32,025
2,327
number of increasing paths in a grid
class Solution: def countPaths(self, grid: List[List[int]]) -> int: rows, cols = len(grid), len(grid[0]) dp = {} mod = (10 ** 9) + 7 def dfs(r, c, prev): if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] <= prev: return 0 if (r, c) in...
https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2691096/Python-(Faster-than-94)-or-DFS-%2B-DP-O(N*M)-solution
0
You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions. Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7. Two paths are considere...
Python (Faster than 94%) | DFS + DP O(N*M) solution
3
number-of-increasing-paths-in-a-grid
0.476
KevinJM17
Hard
32,038
2,328
evaluate boolean binary tree
class Solution: def evaluateTree(self, root: Optional[TreeNode]) -> bool: if root.val==0 or root.val==1: return root.val if root.val==2: return self.evaluateTree(root.left) or self.evaluateTree(root.right) if root.val==3: return sel...
https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2566445/Easy-python-6-line-solution
6
You are given the root of a full binary tree with the following properties: Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. The evaluation of a node is as follows: If...
Easy python 6 line solution
282
evaluate-boolean-binary-tree
0.791
shubham_1307
Easy
32,044
2,331
the latest time to catch a bus
class Solution: def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int: buses.sort() passengers.sort() passenger = 0 for bus in buses: maxed_out = False cap = capacity while passenger < ...
https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2259189/Clean-and-Concise-Greedy-with-Intuitive-Explanation
5
You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the ith bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the jth passenger. All bus departure times are unique. All passenger arrival tim...
Clean and Concise Greedy with Intuitive Explanation
472
the-latest-time-to-catch-a-bus
0.229
wickedmishra
Medium
32,058
2,332
minimum sum of squared difference
class Solution: def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int: n = len(nums1) k = k1+k2 # can combine k's because items can be turned negative diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2))) # First binary search to find o...
https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2259712/Python-Easy-to-understand-binary-search-solution
1
You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n. The sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n. You are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 ...
[Python] Easy to understand binary search solution
106
minimum-sum-of-squared-difference
0.255
fomiee
Medium
32,063
2,333
subarray with elements greater than varying threshold
class Solution: def validSubarraySize(self, nums: List[int], threshold: int) -> int: # Stack elements are the array's indices idx, and montonic with respect to nums[idx]. # When the index of the nearest smaller value to nums[idx] comes to the top of the ...
https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2260689/Python3.-oror-Stack-9-lines-oror-TM-%3A-986-ms28-MB
7
You are given an integer array nums and an integer threshold. Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k. Return the size of any such subarray. If there is no such subarray, return -1. A subarray is a contiguous non-empty sequence of elements within an ar...
Python3. || Stack, 9 lines || T/M : 986 ms/28 MB
101
subarray-with-elements-greater-than-varying-threshold
0.404
warrenruud
Hard
32,070
2,334
minimum amount of time to fill cups
class Solution: def fillCups(self, amount: List[int]) -> int: pq = [-q for q in amount if q != 0] heapq.heapify(pq) ret = 0 while len(pq) > 1: first = heapq.heappop(pq) second = heapq.heappop(pq) first += 1 second += 1 ...
https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2262041/Python-or-Straightforward-MaxHeap-Solution
7
You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water. You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot ...
Python | Straightforward MaxHeap Solution
563
minimum-amount-of-time-to-fill-cups
0.555
lukefall425
Easy
32,075
2,335
move pieces to obtain a string
class Solution: # Criteria for a valid transormation: # 1) The # of Ls, # of Rs , and # of _s must be equal between the two strings # # 2) The ordering of Ls and Rs in the two strings must be the same. # ...
https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2274805/Python3-oror-10-lines-w-explanation-oror-TM%3A-96-44
3
You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where: The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there ...
Python3 || 10 lines, w/ explanation || T/M: 96%/ 44%
127
move-pieces-to-obtain-a-string
0.481
warrenruud
Medium
32,090
2,337
count the number of ideal arrays
class Solution: def idealArrays(self, n: int, maxValue: int) -> int: ans = maxValue freq = {x : 1 for x in range(1, maxValue+1)} for k in range(1, n): temp = Counter() for x in freq: for m in range(2, maxValue//x+1): ans += comb(...
https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261351/Python3-freq-table
26
You are given two integers n and maxValue, which are used to describe an ideal array. A 0-indexed integer array arr of length n is considered ideal if the following conditions hold: Every arr[i] is a value from 1 to maxValue, for 0 <= i < n. Every arr[i] is divisible by arr[i - 1], for 0 < i < n. Return the number of d...
[Python3] freq table
1,500
count-the-number-of-ideal-arrays
0.255
ye15
Hard
32,101
2,338
maximum number of pairs in array
class Solution: """ Time: O(n) Memory: O(n) """ def numberOfPairs(self, nums: List[int]) -> List[int]: pairs = sum(cnt // 2 for cnt in Counter(nums).values()) return [pairs, len(nums) - 2 * pairs]
https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2472693/Python-Elegant-and-Short-or-Two-lines-or-99.91-faster-or-Counter
5
You are given a 0-indexed integer array nums. In one operation, you may do the following: Choose two integers in nums that are equal. Remove both integers from nums, forming a pair. The operation is done on nums as many times as possible. Return a 0-indexed integer array answer of size 2 where answer[0] is the number o...
Python Elegant & Short | Two lines | 99.91% faster | Counter
171
maximum-number-of-pairs-in-array
0.766
Kyrylo-Ktl
Easy
32,106
2,341
max sum of a pair with equal sum of digits
class Solution: # The plan here is to: # # • sort the elements of nums into a dict of maxheaps, # according to sum-of-digits. # # • For each key, determine whether there are at least two ...
https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2297244/Python3-oror-dict(heaps)-8-lines-w-explanation-oror-TM%3A-1300ms27MB
3
You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j]. Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the condit...
Python3 || dict(heaps), 8 lines, w/ explanation || T/M: 1300ms/27MB
111
max-sum-of-a-pair-with-equal-sum-of-digits
0.532
warrenruud
Medium
32,140
2,342
query kth smallest trimmed number
class Solution: def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]: def countingSort(indices, pos): count = [0] * 10 for idx in indices: count[ord(nums[idx][pos]) - ord('0')] += 1 start_pos = list(accumulate([0] + count,...
https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2296143/Python-O(m-*-n)-solution-based-on-O(m)-counting-sort
2
You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits. You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to: Trim each number in nums to its rightmost trimi digits. Determine the index of the ...
Python O(m * n) solution based on O(m) counting sort
99
query-kth-smallest-trimmed-number
0.408
lifuh
Medium
32,159
2,343
minimum deletions to make array divisible
class Solution: # From number theory, we know that an integer num divides each # integer in a list if and only if num divides the list's gcd. # # Our plan here is to: # • find the gcd of numDivide ...
https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2296334/Python3-oror-GCD-and-heap-6-lines-w-explanation-oror-TM%3A-56100
3
You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums. Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1. Note that an integer x divides y if y % x == 0. Exam...
Python3 || GCD and heap, 6 lines, w/ explanation || T/M: 56%/100%
37
minimum-deletions-to-make-array-divisible
0.57
warrenruud
Hard
32,177
2,344
best poker hand
class Solution: def bestHand(self, ranks: List[int], suits: List[str]) -> str: dictRanks = {} dictSuits = {} for key in ranks: dictRanks[key] = dictRanks.get(key, 0) + 1 for key in suits: dictSuits[key] = dictSuits.get(key, 0) + 1 ...
https://leetcode.com/problems/best-poker-hand/discuss/2322411/Python-oror-Easy-Approach
3
You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i]. The following are the types of poker hands you can make from best to worst: "Flush": Five cards of the same suit. "Three of a Kind": Three cards of the same rank. "Pair": ...
✅Python || Easy Approach
116
best-poker-hand
0.606
chuhonghao01
Easy
32,188
2,347
number of zero filled subarrays
class Solution: def zeroFilledSubarray(self, nums: List[int]) -> int: n = len(nums) ans = 0 i, j = 0, 0 while i <= n - 1: j = 0 if nums[i] == 0: while i + j <= n - 1 and nums[i + j] == 0: j += 1 ans...
https://leetcode.com/problems/number-of-zero-filled-subarrays/discuss/2322455/Python-oror-Two-pointers-oror-Easy-Approach
2
Given an integer array nums, return the number of subarrays filled with 0. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1,3,0,0,2,0,0,4] Output: 6 Explanation: There are 4 occurrences of [0] as a subarray. There are 2 occurrences of [0,0] as a subarray. There i...
✅Python || Two-pointers || Easy Approach
72
number-of-zero-filled-subarrays
0.571
chuhonghao01
Medium
32,201
2,348
shortest impossible sequence of rolls
class Solution: def shortestSequence(self, rolls: List[int], k: int) -> int: ans = 0 seen = set() for x in rolls: seen.add(x) if len(seen) == k: ans += 1 seen.clear() return ans+1
https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/discuss/2351553/100-faster-at-my-time-or-easy-python3-solution
1
You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i]. Return the length of the shortest sequence of rolls that cannot be taken from rolls. A sequence of rolls of length len is the result of rolling a k side...
100% faster at my time | easy python3 solution
40
shortest-impossible-sequence-of-rolls
0.684
vimla_kushwaha
Hard
32,214
2,350
first letter to appear twice
class Solution: def repeatedCharacter(self, s: str) -> str: setS = set() for x in s: if x in setS: return x else: setS.add(x)
https://leetcode.com/problems/first-letter-to-appear-twice/discuss/2324754/Python-oror-Map-oror-Easy-Approach
17
Given a string s consisting of lowercase English letters, return the first letter to appear twice. Note: A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b. s will contain at least one letter that appears twice. Example 1: Input: s = "abccbaacz" Output:...
✅Python || Map || Easy Approach
1,100
first-letter-to-appear-twice
0.76
chuhonghao01
Easy
32,219
2,351
equal row and column pairs
class Solution: # Consider this grid for an example: # grid = [[1,2,1,9] # [2,8,9,2] # [1,2,1,9] # [9,2,6,3]] ...
https://leetcode.com/problems/equal-row-and-column-pairs/discuss/2328910/Python3-oror-3-lines-transpose-Ctr-w-explanation-oror-TM%3A-100100
12
Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal. A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array). Example 1: Input: grid = [[3,2,1],[1,7,6],[2,7,7]] Output: 1 Explanation: The...
Python3 || 3 lines, transpose, Ctr w/ explanation || T/M: 100%/100%
443
equal-row-and-column-pairs
0.71
warrenruud
Medium
32,258
2,352
number of excellent pairs
class Solution: def countExcellentPairs(self, nums: List[int], k: int) -> int: hamming = sorted([self.hammingWeight(num) for num in set(nums)]) ans = 0 for h in hamming: ans += len(hamming) - bisect.bisect_left(hamming, k - h) return ans def hammingWeight(sel...
https://leetcode.com/problems/number-of-excellent-pairs/discuss/2324641/Python3-Sorting-Hamming-Weights-%2B-Binary-Search-With-Detailed-Explanations
20
You are given a 0-indexed positive integer array nums and a positive integer k. A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied: Both the numbers num1 and num2 exist in the array nums. The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equ...
[Python3] Sorting Hamming Weights + Binary Search With Detailed Explanations
674
number-of-excellent-pairs
0.458
xil899
Hard
32,283
2,354
make array zero by subtracting equal amounts
class Solution: def minimumOperations(self, nums: List[int]) -> int: return len(set(nums) - {0})
https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2357747/Set
17
You are given a non-negative integer array nums. In one operation, you must: Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums. Subtract x from every positive element in nums. Return the minimum number of operations to make every element in nums equal to 0. Example...
Set
1,500
make-array-zero-by-subtracting-equal-amounts
0.727
votrubac
Easy
32,291
2,357
maximum number of groups entering a competition
class Solution: def maximumGroups(self, grades: List[int]) -> int: x = len(grades) n = 0.5 * ((8 * x + 1) ** 0.5 - 1) ans = int(n) return ans
https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2358259/Python-oror-Math-oror-Two-Easy-Approaches
4
You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions: The sum of the grades of students in the ith group is less than the sum...
✅Python || Math || Two Easy Approaches
155
maximum-number-of-groups-entering-a-competition
0.675
chuhonghao01
Medium
32,325
2,358
find closest node to given two nodes
class Solution: def get_neighbors(self, start: int) -> Dict[int, int]: distances = defaultdict(lambda: math.inf) queue = deque([start]) level = 0 while queue: for _ in range(len(queue)): curr = queue.popleft() if distances[curr] <= level: continue distances[curr] = level for ne...
https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2357692/Simple-Breadth-First-Search-with-Explanation
2
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1. You a...
Simple Breadth First Search with Explanation
137
find-closest-node-to-given-two-nodes
0.342
wickedmishra
Medium
32,334
2,359
longest cycle in a graph
class Solution: def longestCycle(self, edges: List[int]) -> int: in_d = set() out_d = set() for i, j in enumerate(edges): if j != -1: in_d.add(j) out_d.add(i) potential = in_d &amp; out_d visited = set() self.ans = -1 ...
https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2357772/Python3-One-pass-dfs
5
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1. ...
[Python3] One pass dfs
257
longest-cycle-in-a-graph
0.386
Remineva
Hard
32,340
2,360
merge similar items
class Solution: def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]: merge_item = items1 + items2 d = defaultdict(int) for i in merge_item: value,weight = i d[value] = d[value] + weight result = [] for j in sorted(d): result.append([j,d[j]]) retur...
https://leetcode.com/problems/merge-similar-items/discuss/2388802/Python-Simple-Python-Solution-Using-HashMap
8
You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties: items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item. The value of each item in items is unique. Return a 2D integer array re...
[ Python ] ✅✅ Simple Python Solution Using HashMap 🥳✌👍
393
merge-similar-items
0.753
ASHOK_KUMAR_MEGHVANSHI
Easy
32,354
2,363
count number of bad pairs
class Solution: def countBadPairs(self, nums: List[int]) -> int: nums_len = len(nums) count_dict = dict() for i in range(nums_len): nums[i] -= i if nums[i] not in count_dict: count_dict[nums[i]] = 0 count_dict[nums[i]] += 1 ...
https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388687/Python-oror-Detailed-Explanation-oror-Faster-Than-100-oror-Less-than-100-oror-Simple-oror-MATH
32
You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i]. Return the total number of bad pairs in nums. Example 1: Input: nums = [4,1,3,3] Output: 5 Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4. The pair (0, 2) is a bad pair since ...
🔥 Python || Detailed Explanation ✅ || Faster Than 100% ✅|| Less than 100% ✅ || Simple || MATH
648
count-number-of-bad-pairs
0.408
wingskh
Medium
32,380
2,364
task scheduler ii
class Solution: def taskSchedulerII(self, tasks: List[int], space: int) -> int: ans = 0 hashset = {} n = len(tasks) for x in set(tasks): hashset[x] = 0 i = 0 while i <= n - 1: flag = ans - hashset[tasks[i]] ...
https://leetcode.com/problems/task-scheduler-ii/discuss/2388355/Python-oror-Easy-Approach
2
You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task. You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another tas...
✅Python || Easy Approach
75
task-scheduler-ii
0.462
chuhonghao01
Medium
32,391
2,365
minimum replacements to sort the array
class Solution: def minimumReplacement(self, nums: List[int]) -> int: n = len(nums) k = nums[n - 1] ans = 0 for i in reversed(range(n - 1)): if nums[i] > k: l = nums[i] / k if l == int(l): ans += int(l...
https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2388550/Python-oror-One-reversed-pass-oror-Easy-Approaches
2
You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it. For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7]. Return the minimum number of operations to make an arra...
✅Python || One reversed pass || Easy Approaches
84
minimum-replacements-to-sort-the-array
0.399
chuhonghao01
Hard
32,402
2,366
number of arithmetic triplets
class Solution: def arithmeticTriplets(self, nums: List[int], diff: int) -> int: ans = 0 n = len(nums) for i in range(n): if nums[i] + diff in nums and nums[i] + 2 * diff in nums: ans += 1 return ans
https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2395275/Python-oror-Easy-Approach
19
You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met: i < j < k, nums[j] - nums[i] == diff, and nums[k] - nums[j] == diff. Return the number of unique arithmetic triplets. Example 1: Input: nums ...
✅Python || Easy Approach
1,200
number-of-arithmetic-triplets
0.837
chuhonghao01
Easy
32,409
2,367
reachable nodes with restrictions
class Solution: def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int: restrictedSet = set(restricted) uf = UnionFindSet(n) for edge in edges: if edge[0] in restrictedSet or edge[1] in restrictedSet: continue e...
https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2395280/Python-oror-Graph-oror-UnionFind-oror-Easy-Approach
3
There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges. 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. You are also given an integer array restricted which represents restricted nodes. Return...
✅Python || Graph || UnionFind || Easy Approach
152
reachable-nodes-with-restrictions
0.574
chuhonghao01
Medium
32,438
2,368
check if there is a valid partition for the array
class Solution: def validPartition(self, nums: List[int]) -> bool: idxs = defaultdict(list) n = len(nums) #Find all doubles for idx in range(1, n): if nums[idx] == nums[idx - 1]: idxs[idx - 1].append(idx + 1) #Find all tri...
https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2390552/Python3-Iterative-DFS
2
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays. We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions: The subarray consists of exactly 2, equal elements. For example, the subarray [2,2] is ...
[Python3] Iterative DFS
106
check-if-there-is-a-valid-partition-for-the-array
0.401
0xRoxas
Medium
32,454
2,369
longest ideal subsequence
class Solution: def longestIdealString(self, s: str, k: int) -> int: dp = [0] * 26 for ch in s: i = ord(ch) - ord("a") dp[i] = 1 + max(dp[max(0, i - k) : min(26, i + k + 1)]) return max(dp)
https://leetcode.com/problems/longest-ideal-subsequence/discuss/2390471/DP
34
You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied: t is a subsequence of the string s. The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k. Return the length of the longest...
DP
2,300
longest-ideal-subsequence
0.379
votrubac
Medium
32,461
2,370
largest local values in a matrix
class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ans = [[0]*(n-2) for _ in range(n-2)] for i in range(n-2): for j in range(n-2): ans[i][j] = max(grid[ii][jj] for ii in range(i, i+3) for jj in range(j, j+3)) ...
https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422191/Python3-simulation
14
You are given an n x n integer matrix grid. Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that: maxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1. In other words, we want to find the largest value in every contiguous 3 x 3 matrix in ...
[Python3] simulation
1,200
largest-local-values-in-a-matrix
0.839
ye15
Easy
32,470
2,373
node with highest edge score
class Solution: def edgeScore(self, edges: List[int]) -> int: n = len(edges) cnt = defaultdict(int) ans = 0 // we have the key stores the node edges[i], and the value indicates the edge score. for i in range(n): cnt[edges[i]] += i m = max(cnt.values()...
https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422372/Python-oror-Easy-Approach-oror-Hashmap
4
You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge. The graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i]. The edge score of a node i is defined as...
✅Python || Easy Approach || Hashmap
226
node-with-highest-edge-score
0.462
chuhonghao01
Medium
32,500
2,374
construct smallest number from di string
class Solution: def smallestNumber(self, pattern: str) -> str: ans = [1] for ch in pattern: if ch == 'I': m = ans[-1]+1 while m in ans: m += 1 ans.append(m) else: ans.append(ans[-1]) for i in r...
https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422249/Python3-greedy
22
You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing. A 0-indexed string num of length n + 1 is created using the following conditions: num consists of the digits '1' to '9', where each digit is used at most once. If pattern[i] == 'I', then ...
[Python3] greedy
994
construct-smallest-number-from-di-string
0.739
ye15
Medium
32,515
2,375
count special integers
class Solution: def countSpecialNumbers(self, n: int) -> int: vals = list(map(int, str(n))) @cache def fn(i, m, on): """Return count at index i with mask m and profile flag (True/False)""" ans = 0 if i == len(vals): return 1 for v in...
https://leetcode.com/problems/count-special-integers/discuss/2422258/Python3-dp
5
We call a positive integer special if all of its digits are distinct. Given a positive integer n, return the number of special integers that belong to the interval [1, n]. Example 1: Input: n = 20 Output: 19 Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers. Examp...
[Python3] dp
466
count-special-integers
0.363
ye15
Hard
32,533
2,376
minimum recolors to get k consecutive black blocks
class Solution: def minimumRecolors(self, blocks: str, k: int) -> int: ans = 0 res = 0 for i in range(len(blocks) - k + 1): res = blocks.count('B', i, i + k) ans = max(res, ans) ans = k - ans return ans
https://leetcode.com/problems/minimum-recolors-to-get-k-consecutive-black-blocks/discuss/2454458/Python-oror-Easy-Approach-oror-Sliding-Window-oror-Count
3
You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black, respectively. You are also given an integer k, which is the desired number of consecutive black blocks. In one operation, you ...
✅Python || Easy Approach || Sliding Window || Count
318
minimum-recolors-to-get-k-consecutive-black-blocks
0.568
chuhonghao01
Easy
32,534
2,379
time needed to rearrange a binary string
class Solution: def secondsToRemoveOccurrences(self, s: str) -> int: ans = prefix = prev = 0 for i, ch in enumerate(s): if ch == '1': ans = max(prev, i - prefix) prefix += 1 if ans: prev = ans+1 return ans
https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2454195/Python3-O(N)-dp-approach
49
You are given a binary string s. In one second, all occurrences of "01" are simultaneously replaced with "10". This process repeats until no occurrences of "01" exist. Return the number of seconds needed to complete this process. Example 1: Input: s = "0110101" Output: 4 Explanation: After one second, s becomes "101...
[Python3] O(N) dp approach
2,200
time-needed-to-rearrange-a-binary-string
0.482
ye15
Medium
32,566
2,380
shifting letters ii
class Solution: def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str: cum_shifts = [0 for _ in range(len(s)+1)] for st, end, d in shifts: if d == 0: cum_shifts[st] -= 1 cum_shifts[end+1] += 1 else: cum_shif...
https://leetcode.com/problems/shifting-letters-ii/discuss/2454404/Python-Cumulative-Sum-oror-Easy-Solution
15
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0. Shifting a character...
✅ Python Cumulative Sum || Easy Solution
850
shifting-letters-ii
0.342
idntk
Medium
32,578
2,381
maximum segment sum after removals
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: mp, cur, res = {}, 0, [] for q in reversed(removeQueries[1:]): mp[q] = (nums[q], 1) rv, rLen = mp.get(q+1, (0, 0)) lv, lLen = mp.get(q-1, (0, 0)) ...
https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2454397/Do-it-backwards-O(N)
29
You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments. A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a se...
Do it backwards O(N)
1,100
maximum-segment-sum-after-removals
0.476
user9591
Hard
32,591
2,382
minimum hours of training to win a competition
class Solution: def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int: ans = 0 n = len(energy) for i in range(n): while initialEnergy <= energy[i] or initialExperience <= experience[i]: if...
https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456759/Python-oror-Easy-Approach
6
You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively. You are also given two 0-indexed integer arrays energy and experience, both of length n. You will face n opponents in order. The energy and experience...
✅Python || Easy Approach
460
minimum-hours-of-training-to-win-a-competition
0.41
chuhonghao01
Easy
32,595
2,383
largest palindromic number
class Solution: def largestPalindromic(self, num: str) -> str: ans = [] b = [str(x) for x in range(9, -1, -1)] from collections import defaultdict a = defaultdict(int) for x in num: a[x] += 1 for x in b: n = len(ans) if n % 2 ==...
https://leetcode.com/problems/largest-palindromic-number/discuss/2456725/Python-oror-Easy-Approach-oror-Hashmap
4
You are given a string num consisting of digits only. Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes. Notes: You do not need to use all the digits of num, but you must use at least one digit. The digits can be reorder...
✅Python || Easy Approach || Hashmap
178
largest-palindromic-number
0.306
chuhonghao01
Medium
32,617
2,384
amount of time for binary tree to be infected
class Solution: def amountOfTime(self, root: Optional[TreeNode], start: int) -> int: graph = defaultdict(list) stack = [(root, None)] while stack: n, p = stack.pop() if p: graph[p.val].append(n.val) graph[n.val].append(p.v...
https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2456656/Python3-bfs
33
You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start. Each minute, a node becomes infected if: The node is currently uninfected. The node is adjacent to an infected node. Return the number of minutes needed for the entire tree ...
[Python3] bfs
1,400
amount-of-time-for-binary-tree-to-be-infected
0.562
ye15
Medium
32,627
2,385
find the k sum of an array
class Solution: def kSum(self, nums: List[int], k: int) -> int: maxSum = sum([max(0, num) for num in nums]) absNums = sorted([abs(num) for num in nums]) maxHeap = [(-maxSum + absNums[0], 0)] ans = [maxSum] while len(ans) < k: nextSum, i = heapq.heappop(maxHeap) ...
https://leetcode.com/problems/find-the-k-sum-of-an-array/discuss/2456716/Python3-HeapPriority-Queue-O(NlogN-%2B-klogk)
82
You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together. We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct). Return the K-Sum of the array. A subsequence is an array th...
[Python3] Heap/Priority Queue, O(NlogN + klogk)
5,300
find-the-k-sum-of-an-array
0.377
xil899
Hard
32,635
2,386
longest subsequence with limited sum
class Solution: def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: nums = list(accumulate(sorted(nums))) return [bisect_right(nums, q) for q in queries]
https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2492737/Prefix-Sum
9
You are given an integer array nums of length n, and an integer array queries of length m. Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i]. A subsequence is an array that can be deri...
Prefix Sum
1,200
longest-subsequence-with-limited-sum
0.648
votrubac
Easy
32,638
2,389
removing stars from a string
class Solution: def removeStars(self, s: str) -> str: stack = [] for ch in s: if ch == '*': stack.pop() else: stack.append(ch) return ''.join(stack)
https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492763/Python3-stack
3
You are given a string s, which contains stars *. In one operation, you can: Choose a star in s. Remove the closest non-star character to its left, as well as remove the star itself. Return the string after all stars have been removed. Note: The input will be generated such that the operation is always possible. It can...
[Python3] stack
46
removing-stars-from-a-string
0.64
ye15
Medium
32,655
2,390
minimum amount of time to collect garbage
class Solution: def garbageCollection(self, garbage: List[str], travel: List[int]) -> int: ans = sum(map(len, garbage)) prefix = list(accumulate(travel, initial=0)) for ch in "MPG": ii = 0 for i, s in enumerate(garbage): if ch in s: ii = i ...
https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2492802/Python3-simulation
4
You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute. You are ...
[Python3] simulation
48
minimum-amount-of-time-to-collect-garbage
0.851
ye15
Medium
32,682
2,391
build a matrix with conditions
class Solution: def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: def fn(cond): """Return topological sort""" graph = [[] for _ in range(k)] indeg = [0]*k for u, v in cond: ...
https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2492822/Python3-topological-sort
12
You are given a positive integer k. You are also given: a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti]. The two arrays contain integers from 1 to k. You have to build a k x k matrix that contai...
[Python3] topological sort
339
build-a-matrix-with-conditions
0.592
ye15
Hard
32,704
2,392
find subarrays with equal sum
class Solution: def findSubarrays(self, nums: List[int]) -> bool: """ Bruteforce approch """ # for i in range(len(nums)-2): # summ1 = nums[i] + nums[i+1] # # for j in range(i+1,len(nums)): # for j in range(i+1,len(nums)-1): # summ = nums[j] + nums[j...
https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525818/Python-oror-Sliding-window-oror-Bruteforce
4
Given a 0-indexed integer array nums, determine whether there exist two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices. Return true if these subarrays exist, and false otherwise. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: In...
Python || Sliding window || Bruteforce
85
find-subarrays-with-equal-sum
0.639
1md3nd
Easy
32,713
2,395
strictly palindromic number
class Solution: def isStrictlyPalindromic(self, n: int) -> bool: def int2base(n,b): r="" while n>0: r+=str(n%b) n//=b return int(r[-1::-1]) for i in range(2,n-1): if int2base(n,i)!=n: return Fa...
https://leetcode.com/problems/strictly-palindromic-number/discuss/2801453/Python-oror-95.34-Faster-oror-Easy-and-Actual-Solution-oror-O(n)-Solution
2
An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic. Given an integer n, return true if n is strictly palindromic and false otherwise. A string is palindromic if it reads the same forward and backward. Example 1...
Python || 95.34% Faster || Easy and Actual Solution || O(n) Solution
186
strictly-palindromic-number
0.877
DareDevil_007
Medium
32,729
2,396
maximum rows covered by columns
class Solution: def maximumRows(self, mat: List[List[int]], cols: int) -> int: n,m = len(mat),len(mat[0]) ans = 0 def check(state,row,rowIncludedCount): nonlocal ans if row==n: if sum(state)<=cols: ans = max(ans,rowIncludedCount) ...
https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2524746/Python-Simple-Solution
4
You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix. Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if: For each cell matrix[row][col] (0 <= col <= n - 1) ...
Python Simple Solution
431
maximum-rows-covered-by-columns
0.525
RedHeadphone
Medium
32,744
2,397
maximum number of robots within budget
class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: n=len(chargeTimes) start=0 runningsum=0 max_consecutive=0 max_so_far=0 secondmax=0 for end in range(n): runningsum+=runn...
https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2526141/Python3-Intuition-Explained-or-Sliding-Window-or-Similar-Problems-Link
1
You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget. The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum...
[Python3] Intuition Explained 🔥 | Sliding Window | Similar Problems Link 🚀
61
maximum-number-of-robots-within-budget
0.322
glimloop
Hard
32,755
2,398
check distances between same letters
class Solution: # Pretty much explains itself. def checkDistances(self, s: str, distance: List[int]) -> bool: d = defaultdict(list) for i, ch in enumerate(s): d[ch].append(i) return all(b-a-1 == distance[ord(ch)-97] for ch, (a,b) in d.items())
https://leetcode.com/problems/check-distances-between-same-letters/discuss/2531135/Python3-oror-3-lines-TM%3A-36ms13.8MB
8
You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26. Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25). In a well-spaced s...
Python3 || 3 lines, T/M: 36ms/13.8MB
596
check-distances-between-same-letters
0.704
warrenruud
Easy
32,763
2,399
number of ways to reach a position after exactly k steps
class Solution: # A few points on the problem: # • The start and end is a "red herring." The answer to the problem # depends only on the distance (dist = end-start) and k. # # • A little thought will ...
https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2554923/Python3-oror-3-lines-combs-w-explanation-oror-TM%3A-9692
3
You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right. Given a positive integer k, return the number of different ways to reach the position endPos st...
Python3 || 3 lines, combs, w/ explanation || T/M: 96%/92%
157
number-of-ways-to-reach-a-position-after-exactly-k-steps
0.323
warrenruud
Medium
32,781
2,400
longest nice subarray
class Solution: def longestNiceSubarray(self, nums: List[int]) -> int: maximum_length = 1 n = len(nums) current_group = 0 left = 0 for right in range(n): # If the number at the right point is safe to include, include it in the group and update the maximum...
https://leetcode.com/problems/longest-nice-subarray/discuss/2527285/Bit-Magic-with-Explanation-and-Complexities
19
You are given an array nums consisting of positive integers. We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0. Return the length of the longest nice subarray. A subarray is a contiguous part of an array. Note that subarrays of len...
Bit Magic with Explanation and Complexities
488
longest-nice-subarray
0.48
wickedmishra
Medium
32,799
2,401
meeting rooms iii
class Solution: def mostBooked(self, n: int, meetings: List[List[int]]) -> int: meetings.sort() # make sure start times are sorted!! meetingCount = [0 for _ in range(n)] availableRooms = list(range(n)); heapify(availableRooms) occupiedRooms = [] ...
https://leetcode.com/problems/meeting-rooms-iii/discuss/2527343/Python-or-More-heap-extravaganza
1
You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. Meetings are allocated to rooms in the followin...
Python | More heap extravaganza
41
meeting-rooms-iii
0.332
sr_vrd
Hard
32,809
2,402
most frequent even element
class Solution: def mostFrequentEven(self, nums: List[int]) -> int: ctr = Counter(nums) return max([c for c in ctr if not c%2], key = lambda x:(ctr[x], -x), default = -1)
https://leetcode.com/problems/most-frequent-even-element/discuss/2581151/Python-3-oror-2-lines-Counter-oror-TM%3A-9586
6
Given an integer array nums, return the most frequent even element. If there is a tie, return the smallest one. If there is no such element, return -1. Example 1: Input: nums = [0,1,2,2,4,4,1] Output: 2 Explanation: The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We return the smallest one, whic...
Python 3 || 2 lines, Counter || T/M: 95%/86%
268
most-frequent-even-element
0.516
warrenruud
Easy
32,816
2,404
optimal partition of string
class Solution: def partitionString(self, s: str) -> int: cur = set() res = 1 for c in s: if c in cur: cur = set() res += 1 cur.add(c) return res
https://leetcode.com/problems/optimal-partition-of-string/discuss/2560044/Python3-Greedy
9
Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once. Return the minimum number of substrings in such a partition. Note that each character should belong to exactly one substring in a par...
[Python3] Greedy
547
optimal-partition-of-string
0.744
0xRoxas
Medium
32,844
2,405
divide intervals into minimum number of groups
class Solution: def minGroups(self, intervals: List[List[int]]) -> int: pq = [] for left, right in sorted(intervals): if pq and pq[0] < left: heappop(pq) heappush(pq, right) return len(pq)
https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560020/Min-Heap
227
You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti]. You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other. Return the mi...
Min Heap
5,600
divide-intervals-into-minimum-number-of-groups
0.454
votrubac
Medium
32,873
2,406
longest increasing subsequence ii
class Solution: def getmax(self, st, start, end): maxi = 0 while start < end: if start%2:#odd maxi = max(maxi, st[start]) start += 1 if end%2:#odd end -= 1 maxi = max(maxi, st[end]) start //=...
https://leetcode.com/problems/longest-increasing-subsequence-ii/discuss/2591153/Python-runtime-O(n-logn)-memory-O(n)
0
You are given an integer array nums and an integer k. Find the longest subsequence of nums that meets the following requirements: The subsequence is strictly increasing and The difference between adjacent elements in the subsequence is at most k. Return the length of the longest subsequence that meets the requirements....
Python, runtime O(n logn), memory O(n)
114
longest-increasing-subsequence-ii
0.209
tsai00150
Hard
32,886
2,407
count days spent together
class Solution: def countDaysTogether(self, arAl: str, lAl: str, arBo: str, lBo: str) -> int: months = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] start = max(arAl, arBo) end = min(lAl, lBo) startDay = int(start[3:]) startMonth = int(start[:2]) endDay = int(...
https://leetcode.com/problems/count-days-spent-together/discuss/2601983/Very-Easy-Question-or-Visual-Explanation-or-100
3
Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-c...
Very Easy Question | Visual Explanation | 100%
78
count-days-spent-together
0.428
leet_satyam
Easy
32,888
2,409
maximum matching of players with trainers
class Solution: def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int: n = len(players) m = len(trainers) players.sort() trainers.sort() dp = {} def helper(i,j): if i==n or j==m: return 0 if (i,j) in ...
https://leetcode.com/problems/maximum-matching-of-players-with-trainers/discuss/2588450/Python-code-using-recursion
2
You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the jth trainer. The ith player can match with the jth trainer if the player's ability is less than or ...
Python code using recursion
53
maximum-matching-of-players-with-trainers
0.598
kamal0308
Medium
32,904
2,410
smallest subarrays with maximum bitwise or
class Solution: def smallestSubarrays(self, nums: List[int]) -> List[int]: def create(m): t = 0 for n in m: if m[n] > 0: t = t | (1 << n) return t def add(a,m): ans = bin( a ) s = str(ans)[2:] ...
https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/discuss/2588110/Secret-Python-Answer-Sliding-Window-with-Double-Dictionary-of-Binary-Count
1
You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR. In other words, let Bij be the bitwise OR of the subarr...
[Secret Python Answer🤫🐍👌😍] Sliding Window with Double Dictionary of Binary Count
113
smallest-subarrays-with-maximum-bitwise-or
0.403
xmky
Medium
32,915
2,411
minimum money required before transactions
class Solution: def minimumMoney(self, transactions: List[List[int]]) -> int: ans = val = 0 for cost, cashback in transactions: ans += max(0, cost - cashback) val = max(val, min(cost, cashback)) return ans + val
https://leetcode.com/problems/minimum-money-required-before-transactions/discuss/2588620/Python3-Greedy
0
You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki]. The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hol...
[Python3] Greedy
19
minimum-money-required-before-transactions
0.391
ye15
Hard
32,925
2,412
smallest even multiple
class Solution: def smallestEvenMultiple(self, n: int) -> int: # it's just asking for LCM of 2 and n return lcm(2, n)
https://leetcode.com/problems/smallest-even-multiple/discuss/2601867/LeetCode-The-Hard-Way-Explained-Line-By-Line
5
Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n. Example 1: Input: n = 5 Output: 10 Explanation: The smallest multiple of both 5 and 2 is 10. Example 2: Input: n = 6 Output: 6 Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple ...
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
258
smallest-even-multiple
0.879
wingkwong
Easy
32,926
2,413
length of the longest alphabetical continuous substring
class Solution: def longestContinuousSubstring(self, s: str) -> int: arr = ''.join(['1' if ord(s[i])-ord(s[i-1]) == 1 else ' ' for i in range(1,len(s))]).split() return max((len(ones)+1 for ones in arr), default = 1)
https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/discuss/2594370/Python3-oror-Str-join-and-split-2-lines-oror-TM-375ms15.7-MB
3
An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz". For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not. Given a string s consisting of lowercase letters only, r...
Python3 || Str join & split, 2 lines || T/M 375ms/15.7 MB
38
length-of-the-longest-alphabetical-continuous-substring
0.558
warrenruud
Medium
32,963
2,414
reverse odd levels of binary tree
class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: def dfs(n1, n2, level): if not n1: return if level % 2: n1.val, n2.val = n2.val, n1.val dfs(n1.left, n2.right, level ...
https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/discuss/2825833/Python-DFS
0
Given the root of a perfect binary tree, reverse the node values at each odd level of the tree. For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2]. Return the root of the reversed tree. A binary tree is perfect if all parent nodes have two children and a...
Python, DFS
4
reverse-odd-levels-of-binary-tree
0.757
blue_sky5
Medium
32,985
2,415
sum of prefix scores of strings
class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: d = defaultdict(int) for word in words: for index in range(1, len(word) + 1): d[word[:index]] += 1 result = [] for word in words: current_sum = 0 for index in range(1, len(word) + 1): current_sum = current_sum + d[...
https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590687/Python-Simple-Python-Solution-Using-Dictionary
1
You are given an array words of size n consisting of non-empty strings. We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i]. For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc". Return an ...
[ Python ] ✅✅ Simple Python Solution Using Dictionary 🥳✌👍
70
sum-of-prefix-scores-of-strings
0.426
ASHOK_KUMAR_MEGHVANSHI
Hard
33,003
2,416
sort the people
class Solution: # Ex: names = ["Larry","Curly","Moe"] heights = [130,125,155] def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: _,names = zip(*sorted(zip(heights,names), reverse = True)) # zipped --> [(130,"Larry"), (125,"C...
https://leetcode.com/problems/sort-the-people/discuss/2627285/python3-oror-2-lines-with-example-oror-TM-42ms14.3MB
7
You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n. For each index i, names[i] and heights[i] denote the name and height of the ith person. Return names sorted in descending order by the people's heights. Example 1: Input: names = ["M...
python3 || 2 lines with example || T/M = 42ms/14.3MB
575
sort-the-people
0.82
warrenruud
Easy
33,015
2,418
longest subarray with maximum bitwise and
class Solution: def longestSubarray(self, nums: List[int]) -> int: max_n = max(nums) return max(len(list(it)) for n, it in groupby(nums) if n == max_n)
https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2648255/Group-By-and-One-Pass
7
You are given an integer array nums of size n. Consider a non-empty subarray from nums that has the maximum possible bitwise AND. In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered. Return the length of the longe...
Group By and One-Pass
63
longest-subarray-with-maximum-bitwise-and
0.477
votrubac
Medium
33,067
2,419
find all good indices
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: ### forward pass. forward = [False]*len(nums) ### For the forward pass, store if index i is good or not. stack = [] for i in range(len(nums)): ### if the leangth of stack is greater or equal to k, i...
https://leetcode.com/problems/find-all-good-indices/discuss/2620637/Python3-Two-passes-O(n)-with-line-by-line-comments.
34
You are given a 0-indexed integer array nums of size n and a positive integer k. We call an index i in the range k <= i < n - k good if the following conditions are satisfied: The k elements that are just before the index i are in non-increasing order. The k elements that are just after the index i are in non-decreasin...
[Python3] Two passes O(n) with line by line comments.
1,400
find-all-good-indices
0.372
md2030
Medium
33,076
2,420
number of good paths
class Solution: def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int: n = len(vals) g = defaultdict(list) # start from node with minimum val for a, b in edges: heappush(g[a], (vals[b], b)) heappush(g[b], (vals[a], a)) ...
https://leetcode.com/problems/number-of-good-paths/discuss/2623051/Python-3Hint-solution-Heap-%2B-Union-find
0
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] deno...
[Python 3]Hint solution Heap + Union find
57
number-of-good-paths
0.398
chestnut890123
Hard
33,085
2,421
remove letter to equalize frequency
class Solution: def equalFrequency(self, word: str) -> bool: cnt = Counter(Counter(word).values()) if (len(cnt) == 1): return list(cnt.keys())[0] == 1 or list(cnt.values())[0] == 1 if (len(cnt) == 2): f1, f2 = min(cnt.keys()), max(cnt.keys()) return (f1 + ...
https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2660629/Counter-of-Counter
9
You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal. Return true if it is possible to remove one letter so that the frequency of all letters in word are e...
Counter of Counter
336
remove-letter-to-equalize-frequency
0.193
votrubac
Easy
33,088
2,423
bitwise xor of all pairings
class Solution: def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int: m, n = map(len, (nums1, nums2)) return (m % 2 * reduce(xor, nums2)) ^ (n % 2 * reduce(xor, nums1))
https://leetcode.com/problems/bitwise-xor-of-all-pairings/discuss/2646655/JavaPython-3-Bit-manipulations-analysis.
10
You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once). Return the bitwise XOR of all integ...
[Java/Python 3] Bit manipulations analysis.
221
bitwise-xor-of-all-pairings
0.586
rock
Medium
33,118
2,425
number of pairs satisfying inequality
class Solution: def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int: n=len(nums1) for i in range(n): nums1[i]=nums1[i]-nums2[i] ans=0 arr=[] for i in range(n): x=bisect_right(arr,nums1[i]+diff) ans+=x i...
https://leetcode.com/problems/number-of-pairs-satisfying-inequality/discuss/2647569/Python-Binary-Search-oror-Time%3A-2698-ms-(50)-Space%3A-32.5-MB-(100)
0
You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that: 0 <= i < j <= n - 1 and nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff. Return the number of pairs that satisfy the conditions. Example 1: Input: nums1 = [3,2,5], nums2 = [2,2...
Python Binary Search || Time: 2698 ms (50%), Space: 32.5 MB (100%)
15
number-of-pairs-satisfying-inequality
0.422
koder_786
Hard
33,137
2,426
number of common factors
class Solution: def commonFactors(self, a: int, b: int) -> int: c=0 mi=min(a,b) for i in range(1,mi+1): if a%i==0 and b%i==0: c+=1 return c
https://leetcode.com/problems/number-of-common-factors/discuss/2817862/Easy-Python-Solution
3
Given two positive integers a and b, return the number of common factors of a and b. An integer x is a common factor of a and b if x divides both a and b. Example 1: Input: a = 12, b = 6 Output: 4 Explanation: The common factors of 12 and 6 are 1, 2, 3, 6. Example 2: Input: a = 25, b = 30 Output: 2 Explanation: The c...
Easy Python Solution
62
number-of-common-factors
0.801
Vistrit
Easy
33,141
2,427
maximum sum of an hourglass
class Solution: def maxSum(self, grid: List[List[int]]) -> int: res=0 cur=0 for i in range(len(grid)-2): for j in range(1,len(grid[0])-1): cur=sum(grid[i][j-1:j+2]) +grid[i+1][j] + sum(grid[i+2][j-1:j+2]) res = max(res,cur)...
https://leetcode.com/problems/maximum-sum-of-an-hourglass/discuss/2677741/Simple-Python-Solution-oror-O(MxN)-beats-83.88
1
You are given an m x n integer matrix grid. We define an hourglass as a part of the matrix with the following form: Return the maximum sum of the elements of an hourglass. Note that an hourglass cannot be rotated and must be entirely contained within the matrix. Example 1: Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7]...
Simple Python Solution || O(MxN) beats 83.88%
42
maximum-sum-of-an-hourglass
0.739
Graviel77
Medium
33,178
2,428
minimize xor
class Solution: def minimizeXor(self, num1: int, num2: int) -> int: nbit1 = 0 while num2>0: nbit1 = nbit1 + (num2&amp;1) num2 = num2 >> 1 # print(nbit1) chk = [] ans = 0 # print(bin(num1), bin(ans)) for i in range(31, -1...
https://leetcode.com/problems/minimize-xor/discuss/2649210/O(log(n))-using-set-and-clear-bit-(examples)
1
Given two positive integers num1 and num2, find the positive integer x such that: x has the same number of set bits as num2, and The value x XOR num1 is minimal. Note that XOR is the bitwise XOR operation. Return the integer x. The test cases are generated such that x is uniquely determined. The number of set bits of a...
O(log(n)) using set and clear bit (examples)
39
minimize-xor
0.418
dntai
Medium
33,205
2,429
maximum deletions on a string
class Solution: def deleteString(self, s: str) -> int: n = len(s) if len(set(s)) == 1: return n dp = [1] * n for i in range(n - 2, -1, -1): for l in range(1, (n - i) // 2 + 1): if s[i : i + l] == s[i + l : i + 2 * l]: dp[i] ...
https://leetcode.com/problems/maximum-deletions-on-a-string/discuss/2648661/Python3-Dynamic-Programming-Clean-and-Concise
10
You are given a string s consisting of only lowercase English letters. In one operation, you can: Delete the entire string s, or Delete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2. For example, if s = "ababc", then in one ...
[Python3] Dynamic Programming, Clean & Concise
1,000
maximum-deletions-on-a-string
0.322
xil899
Hard
33,229
2,430
the employee that worked on the longest task
class Solution: """ Time: O(n) Memory: O(1) """ def hardestWorker(self, n: int, logs: List[List[int]]) -> int: best_id = best_time = start = 0 for emp_id, end in logs: time = end - start if time > best_time or (time == best_time and best_id > emp_id): ...
https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/discuss/2693491/Python-Elegant-and-Short-or-No-indexes-or-99.32-faster
4
There are n employees, each with a unique id from 0 to n - 1. You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where: idi is the id of the employee that worked on the ith task, and leaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are unique. Note that ...
Python Elegant & Short | No indexes | 99.32% faster
47
the-employee-that-worked-on-the-longest-task
0.489
Kyrylo-Ktl
Easy
33,243
2,432
find the original array of prefix xor
class Solution: def findArray(self, pref: List[int]) -> List[int]: ans = [0 for i in range(len(pref))] ans[0] = pref[0] for i in range(1, len(pref)): ans[i] = pref[i-1]^pref[i] return ans
https://leetcode.com/problems/find-the-original-array-of-prefix-xor/discuss/2684467/Python-3-Easy-O(N)-Time-Greedy-Solution-Explained
1
You are given an integer array pref of size n. Find and return the array arr of size n that satisfies: pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]. Note that ^ denotes the bitwise-xor operation. It can be proven that the answer is unique. Example 1: Input: pref = [5,2,0,3,1] Output: [5,7,2,3,2] Explanation: From the arr...
[Python 3] Easy O(N) Time Greedy Solution Explained
29
find-the-original-array-of-prefix-xor
0.857
user2667O
Medium
33,265
2,433
using a robot to print the lexicographically smallest string
class Solution: def robotWithString(self, s: str) -> str: cnt, lo, p, t = Counter(s), 'a', [], [] for ch in s: t += ch cnt[ch] -= 1 while lo < 'z' and cnt[lo] == 0: lo = chr(ord(lo) + 1) while t and t[-1] <= lo: p += t.p...
https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2678810/Counter
78
You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty: Remove the first character of a string s and give it to the robot. The robot will append this character to the string t. Remove the last character of a string t and give it to...
Counter
3,600
using-a-robot-to-print-the-lexicographically-smallest-string
0.381
votrubac
Medium
33,297
2,434
paths in matrix whose sum is divisible by k
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: dp = [[[0 for i in range(k)] for _ in range(len(grid[0]))] for _ in range(len(grid))] rem = grid[0][0] % k dp[0][0][rem] = 1 for i in range(1, len(grid[0])): dp[0][i][(rem + grid[0][i]) % k] = ...
https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2702890/Python-or-3d-dynamic-programming-approach-or-O(m*n*k)
1
You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right. Return the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo...
Python | 3d dynamic programming approach | O(m*n*k)
16
paths-in-matrix-whose-sum-is-divisible-by-k
0.41
LordVader1
Hard
33,315
2,435
number of valid clock times
class Solution: def countTime(self, t: str) -> int: mm = (6 if t[3] == '?' else 1) * (10 if t[4] == '?' else 1) match [t[0], t[1]]: case ('?', '?'): return mm * 24 case ('?', ('0' | '1' | '2' | '3')): return mm * 3 case ('?', _): ...
https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706741/Structural-pattern-matching
24
You are given a string of length 5 called time, representing the current time on a digital clock in the format "hh:mm". The earliest possible time is "00:00" and the latest possible time is "23:59". In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9. Re...
Structural pattern matching
806
number-of-valid-clock-times
0.42
votrubac
Easy
33,331
2,437
range product queries of powers
class Solution: def productQueries(self, n: int, queries: List[List[int]]) -> List[int]: MOD = (10**9)+7 binary = bin(n)[2:] powers = [] result = [] for index, val in enumerate(binary[::-1]): if val == "1": powers.append(2**index) ...
https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706690/Python-or-Prefix-Product
8
Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array. You are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti]. Ea...
Python | Prefix Product
320
range-product-queries-of-powers
0.384
Dhanush_krish
Medium
33,359
2,438
minimize maximum of array
class Solution: def minimizeArrayValue(self, nums: List[int]) -> int: return max(ceil(n / (i + 1)) for i, n in enumerate(accumulate(nums)))
https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706472/Average
45
You are given a 0-indexed array nums comprising of n non-negative integers. In one operation, you must: Choose an integer i such that 1 <= i < n and nums[i] > 0. Decrease nums[i] by 1. Increase nums[i - 1] by 1. Return the minimum possible value of the maximum integer of nums after performing any number of operations. ...
Average
2,800
minimize-maximum-of-array
0.331
votrubac
Medium
33,375
2,439
create components with same value
class Solution: def componentValue(self, nums: List[int], edges: List[List[int]]) -> int: tree = [[] for _ in nums] for u, v in edges: tree[u].append(v) tree[v].append(u) def fn(u, p): """Post-order dfs.""" ans = nums[u] f...
https://leetcode.com/problems/create-components-with-same-value/discuss/2707304/Python3-post-order-dfs
11
There is an undirected tree with n nodes labeled from 0 to n - 1. You are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also 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 ...
[Python3] post-order dfs
264
create-components-with-same-value
0.543
ye15
Hard
33,393
2,440
largest positive integer that exists with its negative
class Solution: def findMaxK(self, nums: List[int]) -> int: nums.sort() for i in nums[::-1]: if -i in nums: return i return -1
https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2774238/Easy-Python-Solution
3
Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array. Return the positive integer k. If there is no such integer, return -1. Example 1: Input: nums = [-1,2,-3,3] Output: 3 Explanation: 3 is the only valid k we can find in the array. Exa...
Easy Python Solution
64
largest-positive-integer-that-exists-with-its-negative
0.678
Vistrit
Easy
33,395
2,441
count number of distinct integers after reverse operations
class Solution: def countDistinctIntegers(self, nums: List[int]) -> int: return len(set([int(str(i)[::-1]) for i in nums] + nums))
https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/discuss/2708055/One-Liner-or-Explained
5
You are given an array nums consisting of positive integers. You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums. Return the number of distinct integers in the final array. Example 1: Input: nums = [1,13,1...
One Liner | Explained
427
count-number-of-distinct-integers-after-reverse-operations
0.788
lukewu28
Medium
33,429
2,442
sum of number and its reverse
class Solution: def sumOfNumberAndReverse(self, num: int) -> bool: digits = [] while num > 0: digits.append(num % 10) num = num // 10 digits.reverse() hi, lo = 0, len(digits) - 1 while hi <= lo: if hi == lo: if digits[hi] %...
https://leetcode.com/problems/sum-of-number-and-its-reverse/discuss/2708439/Python3-O(-digits)-solution-beats-100-47ms
2
Given a non-negative integer num, return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise. Example 1: Input: num = 443 Output: true Explanation: 172 + 271 = 443 so we return true. Example 2: Input: num = 63 Output: false Explanation: 63 cannot be expressed as the...
[Python3] O(# digits) solution beats 100% 47ms
326
sum-of-number-and-its-reverse
0.453
jfang2021
Medium
33,466
2,443
count subarrays with fixed bounds
class Solution: def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int: if minK > maxK: return 0 def count(l, r): if l + 1 == r: return 0 dic = Counter([nums[l]]) ans, j = 0, l + 1 for i in range(l + 1, r): dic[...
https://leetcode.com/problems/count-subarrays-with-fixed-bounds/discuss/2708034/Python3-Sliding-Window-O(N)-with-Explanations
1
You are given an integer array nums and two integers minK and maxK. A fixed-bound subarray of nums is a subarray that satisfies the following conditions: The minimum value in the subarray is equal to minK. The maximum value in the subarray is equal to maxK. Return the number of fixed-bound subarrays. A subarray is a co...
[Python3] Sliding Window O(N) with Explanations
97
count-subarrays-with-fixed-bounds
0.432
xil899
Hard
33,498
2,444
determine if two events have conflict
class Solution: """ Time: O(1) Memory: O(1) """ def haveConflict(self, a: List[str], b: List[str]) -> bool: a_start, a_end = a b_start, b_end = b return b_start <= a_start <= b_end or \ b_start <= a_end <= b_end or \ a_start <= b_start <= a_en...
https://leetcode.com/problems/determine-if-two-events-have-conflict/discuss/2744018/Python-Elegant-and-Short
3
You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where: event1 = [startTime1, endTime1] and event2 = [startTime2, endTime2]. Event times are valid 24 hours format in the form of HH:MM. A conflict happens when two events have some non-empty interse...
Python Elegant & Short
79
determine-if-two-events-have-conflict
0.494
Kyrylo-Ktl
Easy
33,507
2,446
number of subarrays with gcd equal to k
class Solution: def subarrayGCD(self, nums: List[int], k: int) -> int: n = len(nums) ans = 0 for i in range(n): temp = nums[i] for j in range(i, n): temp = math.gcd(temp, nums[j]) if temp == k: ans += 1 ...
https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/discuss/2734224/Python3-Brute-Force-%2B-Early-Stopping-Clean-and-Concise
4
Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k. A subarray is a contiguous non-empty sequence of elements within an array. The greatest common divisor of an array is the largest integer that evenly divides all the ar...
[Python3] Brute Force + Early Stopping, Clean & Concise
423
number-of-subarrays-with-gcd-equal-to-k
0.482
xil899
Medium
33,524
2,447
minimum cost to make array equal
class Solution: def minCost(self, nums: List[int], cost: List[int]) -> int: arr = sorted(zip(nums, cost)) total, cnt = sum(cost), 0 for num, c in arr: cnt += c if cnt > total // 2: target = num break return sum(c * abs(num - tar...
https://leetcode.com/problems/minimum-cost-to-make-array-equal/discuss/2734183/Python3-Weighted-Median-O(NlogN)-with-Explanations
109
You are given two 0-indexed arrays nums and cost consisting each of n positive integers. You can do the following operation any number of times: Increase or decrease any element of the array nums by 1. The cost of doing one operation on the ith element is cost[i]. Return the minimum total cost such that all the element...
[Python3] Weighted Median O(NlogN) with Explanations
2,300
minimum-cost-to-make-array-equal
0.346
xil899
Hard
33,535
2,448